From 3c0286f46b021b4a15dc763dfa50a8447fe07e53 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Thu, 29 Sep 2016 19:30:26 +0200 Subject: [PATCH 01/32] Update version to 0.4.1-SNAPSHOT --- google-cloud-bigquery/pom.xml | 2 +- google-cloud-compute/pom.xml | 2 +- google-cloud-contrib/google-cloud-nio-examples/pom.xml | 2 +- google-cloud-contrib/google-cloud-nio/pom.xml | 2 +- google-cloud-contrib/pom.xml | 2 +- google-cloud-core/pom.xml | 2 +- google-cloud-datastore/pom.xml | 2 +- google-cloud-dns/pom.xml | 2 +- google-cloud-errorreporting/pom.xml | 2 +- google-cloud-examples/pom.xml | 2 +- google-cloud-language/pom.xml | 2 +- google-cloud-logging/pom.xml | 2 +- google-cloud-monitoring/pom.xml | 2 +- google-cloud-pubsub/pom.xml | 2 +- google-cloud-resourcemanager/pom.xml | 2 +- google-cloud-speech/pom.xml | 2 +- google-cloud-storage/pom.xml | 2 +- google-cloud-trace/pom.xml | 2 +- google-cloud-translate/pom.xml | 2 +- google-cloud-vision/pom.xml | 2 +- google-cloud/pom.xml | 2 +- pom.xml | 2 +- 22 files changed, 22 insertions(+), 22 deletions(-) diff --git a/google-cloud-bigquery/pom.xml b/google-cloud-bigquery/pom.xml index 5602b7ee9f3c..f623dd7ca343 100644 --- a/google-cloud-bigquery/pom.xml +++ b/google-cloud-bigquery/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-bigquery diff --git a/google-cloud-compute/pom.xml b/google-cloud-compute/pom.xml index e22437cb2d72..5c8d0efe528a 100644 --- a/google-cloud-compute/pom.xml +++ b/google-cloud-compute/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-compute diff --git a/google-cloud-contrib/google-cloud-nio-examples/pom.xml b/google-cloud-contrib/google-cloud-nio-examples/pom.xml index 3b05850580cc..469774e01e84 100644 --- a/google-cloud-contrib/google-cloud-nio-examples/pom.xml +++ b/google-cloud-contrib/google-cloud-nio-examples/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-contrib - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-nio-examples diff --git a/google-cloud-contrib/google-cloud-nio/pom.xml b/google-cloud-contrib/google-cloud-nio/pom.xml index 872718c29cb2..84604fd2daa1 100644 --- a/google-cloud-contrib/google-cloud-nio/pom.xml +++ b/google-cloud-contrib/google-cloud-nio/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-contrib - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-nio diff --git a/google-cloud-contrib/pom.xml b/google-cloud-contrib/pom.xml index 41d84f6e3b08..5f3e9912047a 100644 --- a/google-cloud-contrib/pom.xml +++ b/google-cloud-contrib/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-contrib diff --git a/google-cloud-core/pom.xml b/google-cloud-core/pom.xml index f6161fee3c43..e3fb52ed2ef8 100644 --- a/google-cloud-core/pom.xml +++ b/google-cloud-core/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-core diff --git a/google-cloud-datastore/pom.xml b/google-cloud-datastore/pom.xml index bc7dfb4865fb..7c80588b70ff 100644 --- a/google-cloud-datastore/pom.xml +++ b/google-cloud-datastore/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-datastore diff --git a/google-cloud-dns/pom.xml b/google-cloud-dns/pom.xml index 3a4cc5b88a34..91ce85326766 100644 --- a/google-cloud-dns/pom.xml +++ b/google-cloud-dns/pom.xml @@ -13,7 +13,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-dns diff --git a/google-cloud-errorreporting/pom.xml b/google-cloud-errorreporting/pom.xml index 65a4ca1895ba..31e9d3d9727a 100644 --- a/google-cloud-errorreporting/pom.xml +++ b/google-cloud-errorreporting/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-errorreporting diff --git a/google-cloud-examples/pom.xml b/google-cloud-examples/pom.xml index 36725fcc8ee8..45d3218ea6cd 100644 --- a/google-cloud-examples/pom.xml +++ b/google-cloud-examples/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-examples diff --git a/google-cloud-language/pom.xml b/google-cloud-language/pom.xml index f94581bdd793..90663b119546 100644 --- a/google-cloud-language/pom.xml +++ b/google-cloud-language/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-language diff --git a/google-cloud-logging/pom.xml b/google-cloud-logging/pom.xml index e205797560f1..d2185f866bb2 100644 --- a/google-cloud-logging/pom.xml +++ b/google-cloud-logging/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-logging diff --git a/google-cloud-monitoring/pom.xml b/google-cloud-monitoring/pom.xml index 8ed99c73f8da..7df6f00c2df9 100644 --- a/google-cloud-monitoring/pom.xml +++ b/google-cloud-monitoring/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-monitoring diff --git a/google-cloud-pubsub/pom.xml b/google-cloud-pubsub/pom.xml index e22115f27f9a..4f6d7b884d81 100644 --- a/google-cloud-pubsub/pom.xml +++ b/google-cloud-pubsub/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-pubsub diff --git a/google-cloud-resourcemanager/pom.xml b/google-cloud-resourcemanager/pom.xml index d1fb101bf7bd..1ef16075f131 100644 --- a/google-cloud-resourcemanager/pom.xml +++ b/google-cloud-resourcemanager/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-resourcemanager diff --git a/google-cloud-speech/pom.xml b/google-cloud-speech/pom.xml index 048dbf1e3f03..012c047afebf 100644 --- a/google-cloud-speech/pom.xml +++ b/google-cloud-speech/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-speech diff --git a/google-cloud-storage/pom.xml b/google-cloud-storage/pom.xml index 5a81e7c07931..219e4abfc1b3 100644 --- a/google-cloud-storage/pom.xml +++ b/google-cloud-storage/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-storage diff --git a/google-cloud-trace/pom.xml b/google-cloud-trace/pom.xml index 7868cc6d0db5..d2c241bc0c27 100644 --- a/google-cloud-trace/pom.xml +++ b/google-cloud-trace/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-trace diff --git a/google-cloud-translate/pom.xml b/google-cloud-translate/pom.xml index dd14c5d812a6..81d85e710d6a 100644 --- a/google-cloud-translate/pom.xml +++ b/google-cloud-translate/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-translate diff --git a/google-cloud-vision/pom.xml b/google-cloud-vision/pom.xml index 5a8c7aedda65..66a6cb76b2f2 100644 --- a/google-cloud-vision/pom.xml +++ b/google-cloud-vision/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT google-cloud-vision diff --git a/google-cloud/pom.xml b/google-cloud/pom.xml index f00ffecbf6ea..d0ec54a3e311 100644 --- a/google-cloud/pom.xml +++ b/google-cloud/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.0 + 0.4.1-SNAPSHOT diff --git a/pom.xml b/pom.xml index e688c8f068d5..1518b6bdcacc 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.google.cloud google-cloud-pom pom - 0.4.0 + 0.4.1-SNAPSHOT Google Cloud https://github.com/GoogleCloudPlatform/google-cloud-java From 6e391f8d74a3cacd8cb2c1da359903126c946883 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Fri, 30 Sep 2016 09:58:25 +0200 Subject: [PATCH 02/32] Add reset() method to LocalDatastoreHelper (#1293) --- .../testing/LocalDatastoreHelper.java | 26 +++++++++++++++++ .../testing/LocalDatastoreHelperTest.java | 28 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java index 106fab01f005..c01e9e0ba4db 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java @@ -23,6 +23,7 @@ import com.google.cloud.RetryParams; import com.google.cloud.datastore.DatastoreOptions; import com.google.common.base.Strings; +import com.google.common.io.CharStreams; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; @@ -508,6 +509,24 @@ public static boolean sendQuitRequest(int port) { return result.toString().startsWith(shutdownMsg); } + public String sendPostRequest(String request) throws IOException { + URL url = new URL("http", "localhost", this.port, request); + HttpURLConnection con = (HttpURLConnection) url.openConnection(); + con.setRequestMethod("POST"); + con.setDoOutput(true); + OutputStream out = con.getOutputStream(); + out.write("".getBytes()); + out.flush(); + + InputStream in = con.getInputStream(); + String response = CharStreams.toString(new InputStreamReader(con.getInputStream())); + in.close(); + return response; + } + + /** + * Quit the local emulator and related local service. + */ public void stop() throws IOException, InterruptedException { sendQuitRequest(port); if (processReader != null) { @@ -521,6 +540,13 @@ public void stop() throws IOException, InterruptedException { } } + /** + * Reset the internal state of the emulator. + */ + public void reset() throws IOException { + sendPostRequest("/reset"); + } + private static void deleteRecurse(Path path) throws IOException { if (path == null || !Files.exists(path)) { return; diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java index a5a49e472ae3..cab189ae8cb9 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java @@ -17,16 +17,26 @@ package com.google.cloud.datastore.testing; import static org.junit.Assert.assertEquals; +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 com.google.cloud.AuthCredentials; +import com.google.cloud.datastore.Datastore; +import com.google.cloud.datastore.DatastoreException; import com.google.cloud.datastore.DatastoreOptions; +import com.google.cloud.datastore.Entity; +import com.google.cloud.datastore.Key; +import org.junit.Rule; import org.junit.Test; +import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; +import java.io.IOException; + @RunWith(JUnit4.class) public class LocalDatastoreHelperTest { @@ -34,6 +44,9 @@ public class LocalDatastoreHelperTest { private static final String PROJECT_ID_PREFIX = "test-project-"; private static final String NAMESPACE = "namespace"; + @Rule + public ExpectedException thrown = ExpectedException.none(); + @Test public void testCreate() { LocalDatastoreHelper helper = LocalDatastoreHelper.create(0.75); @@ -57,4 +70,19 @@ public void testOptions() { assertSame(AuthCredentials.noAuth(), options.authCredentials()); assertEquals(NAMESPACE, options.namespace()); } + + @Test + public void testStartStopReset() throws IOException, InterruptedException { + LocalDatastoreHelper helper = LocalDatastoreHelper.create(); + helper.start(); + Datastore datastore = helper.options().service(); + Key key = datastore.newKeyFactory().kind("kind").newKey("name"); + datastore.put(Entity.builder(key).build()); + assertNotNull(datastore.get(key)); + helper.reset(); + assertNull(datastore.get(key)); + helper.stop(); + thrown.expect(DatastoreException.class); + datastore.get(key); + } } From dcee4732c3c8ec0249f252131ca101d8d4ec7343 Mon Sep 17 00:00:00 2001 From: garrettjonesgoogle Date: Fri, 30 Sep 2016 06:50:18 -0700 Subject: [PATCH 03/32] Regenerating spi layer - fixing some Codacy warnings (#1298) --- .../spi/v1beta1/ErrorGroupServiceApi.java | 8 ++--- .../v1beta1/ErrorGroupServiceSettings.java | 4 +-- .../spi/v1beta1/ErrorStatsServiceApi.java | 8 ++--- .../v1beta1/ErrorStatsServiceSettings.java | 12 ++++--- .../spi/v1beta1/ReportErrorsServiceApi.java | 8 ++--- .../v1beta1/ReportErrorsServiceSettings.java | 2 +- .../spi/v1beta1/MockErrorGroupService.java | 3 +- .../spi/v1beta1/MockErrorStatsService.java | 3 +- .../spi/v1beta1/MockReportErrorsService.java | 3 +- .../spi/v1beta1/LanguageServiceApi.java | 16 ++++----- .../spi/v1beta1/LanguageServiceSettings.java | 6 ++-- .../spi/v1beta1/LanguageServiceTest.java | 2 +- .../spi/v1beta1/MockLanguageService.java | 3 +- .../logging/spi/v2/ConfigServiceV2Api.java | 8 ++--- .../spi/v2/ConfigServiceV2Settings.java | 13 +++---- .../logging/spi/v2/LoggingServiceV2Api.java | 8 ++--- .../spi/v2/LoggingServiceV2Settings.java | 14 ++++---- .../logging/spi/v2/MetricsServiceV2Api.java | 8 ++--- .../spi/v2/MetricsServiceV2Settings.java | 16 +++++---- .../logging/spi/v2/MockConfigServiceV2.java | 2 +- .../logging/spi/v2/MockLoggingServiceV2.java | 2 +- .../logging/spi/v2/MockMetricsServiceV2.java | 2 +- .../spi/v3/AgentTranslationServiceApi.java | 8 ++--- .../v3/AgentTranslationServiceSettings.java | 2 +- .../monitoring/spi/v3/GroupServiceApi.java | 8 ++--- .../spi/v3/GroupServiceSettings.java | 17 ++++----- .../monitoring/spi/v3/MetricServiceApi.java | 14 ++++---- .../spi/v3/MetricServiceSettings.java | 25 +++++++------ .../spi/v3/MockAgentTranslationService.java | 3 +- .../monitoring/spi/v3/MockGroupService.java | 3 +- .../monitoring/spi/v3/MockMetricService.java | 3 +- .../cloud/pubsub/spi/v1/PublisherApi.java | 8 ++--- .../pubsub/spi/v1/PublisherSettings.java | 25 ++++++------- .../cloud/pubsub/spi/v1/SubscriberApi.java | 35 +++++++++++-------- .../pubsub/spi/v1/SubscriberSettings.java | 28 ++++++++------- .../cloud/pubsub/spi/v1/MockIAMPolicy.java | 3 +- .../cloud/pubsub/spi/v1/MockPublisher.java | 3 +- .../cloud/pubsub/spi/v1/MockSubscriber.java | 3 +- .../cloud/speech/spi/v1beta1/SpeechApi.java | 23 ++++++------ .../speech/spi/v1beta1/SpeechSettings.java | 5 +-- .../cloud/speech/spi/v1beta1/MockSpeech.java | 3 +- .../cloud/trace/spi/v1/TraceServiceApi.java | 8 ++--- .../trace/spi/v1/TraceServiceSettings.java | 9 ++--- .../cloud/trace/spi/v1/MockTraceService.java | 3 +- .../vision/spi/v1/ImageAnnotatorApi.java | 8 ++--- .../vision/spi/v1/ImageAnnotatorSettings.java | 3 +- .../vision/spi/v1/MockImageAnnotator.java | 3 +- 47 files changed, 211 insertions(+), 193 deletions(-) diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceApi.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceApi.java index 3cba0f469d82..8c9ff4b4004c 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceApi.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceApi.java @@ -87,10 +87,6 @@ public class ErrorGroupServiceApi implements AutoCloseable { private final ApiCallable getGroupCallable; private final ApiCallable updateGroupCallable; - public final ErrorGroupServiceSettings getSettings() { - return settings; - } - private static final PathTemplate GROUP_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}/groups/{group}"); @@ -172,6 +168,10 @@ public void close() throws IOException { } } + public final ErrorGroupServiceSettings getSettings() { + return settings; + } + // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Get the specified group. diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceSettings.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceSettings.java index 7c94e46179c9..f591c034ca78 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceSettings.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceSettings.java @@ -169,8 +169,8 @@ private ErrorGroupServiceSettings(Builder settingsBuilder) throws IOException { public static class Builder extends ServiceApiSettings.Builder { private final ImmutableList methodSettingsBuilders; - private SimpleCallSettings.Builder getGroupSettings; - private SimpleCallSettings.Builder updateGroupSettings; + private final SimpleCallSettings.Builder getGroupSettings; + private final SimpleCallSettings.Builder updateGroupSettings; private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS; diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceApi.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceApi.java index a1efc7a1ff53..c2a79541d076 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceApi.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceApi.java @@ -103,10 +103,6 @@ public class ErrorStatsServiceApi implements AutoCloseable { listEventsPagedCallable; private final ApiCallable deleteEventsCallable; - public final ErrorStatsServiceSettings getSettings() { - return settings; - } - private static final PathTemplate PROJECT_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}"); @@ -185,6 +181,10 @@ public void close() throws IOException { } } + public final ErrorStatsServiceSettings getSettings() { + return settings; + } + // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Lists the specified groups. diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceSettings.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceSettings.java index 992c5b1a1bab..e04773777a7a 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceSettings.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceSettings.java @@ -14,6 +14,7 @@ package com.google.cloud.errorreporting.spi.v1beta1; import com.google.api.gax.core.ConnectionSettings; +import com.google.api.gax.core.PagedListResponse; import com.google.api.gax.core.RetrySettings; import com.google.api.gax.grpc.ApiCallSettings; import com.google.api.gax.grpc.PageStreamingCallSettings; @@ -183,7 +184,7 @@ private ErrorStatsServiceSettings(Builder settingsBuilder) throws IOException { deleteEventsSettings = settingsBuilder.deleteEventsSettings().build(); } - private static PageStreamingDescriptor< + private static final PageStreamingDescriptor< ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats> LIST_GROUP_STATS_PAGE_STR_DESC = new PageStreamingDescriptor< @@ -220,7 +221,7 @@ public Iterable extractResources(ListGroupStatsResponse payload } }; - private static PageStreamingDescriptor + private static final PageStreamingDescriptor LIST_EVENTS_PAGE_STR_DESC = new PageStreamingDescriptor() { @Override @@ -260,12 +261,13 @@ public Iterable extractResources(ListEventsResponse payload) { public static class Builder extends ServiceApiSettings.Builder { private final ImmutableList methodSettingsBuilders; - private PageStreamingCallSettings.Builder< + private final PageStreamingCallSettings.Builder< ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats> listGroupStatsSettings; - private PageStreamingCallSettings.Builder + private final PageStreamingCallSettings.Builder< + ListEventsRequest, ListEventsResponse, ErrorEvent> listEventsSettings; - private SimpleCallSettings.Builder + private final SimpleCallSettings.Builder deleteEventsSettings; private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS; diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceApi.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceApi.java index 67dca4414078..8ecedcb0205c 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceApi.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceApi.java @@ -88,10 +88,6 @@ public class ReportErrorsServiceApi implements AutoCloseable { private final ApiCallable reportErrorEventCallable; - public final ReportErrorsServiceSettings getSettings() { - return settings; - } - private static final PathTemplate PROJECT_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}"); @@ -161,6 +157,10 @@ public void close() throws IOException { } } + public final ReportErrorsServiceSettings getSettings() { + return settings; + } + // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Report an individual error event. diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceSettings.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceSettings.java index 69f92e1e5cf9..a61c66655385 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceSettings.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceSettings.java @@ -161,7 +161,7 @@ private ReportErrorsServiceSettings(Builder settingsBuilder) throws IOException public static class Builder extends ServiceApiSettings.Builder { private final ImmutableList methodSettingsBuilders; - private SimpleCallSettings.Builder + private final SimpleCallSettings.Builder reportErrorEventSettings; private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS; diff --git a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/MockErrorGroupService.java b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/MockErrorGroupService.java index 90ae067c4c37..6e1a53925694 100644 --- a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/MockErrorGroupService.java +++ b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/MockErrorGroupService.java @@ -15,14 +15,13 @@ package com.google.cloud.errorreporting.spi.v1beta1; import com.google.api.gax.testing.MockGrpcService; -import com.google.devtools.clouderrorreporting.v1beta1.ErrorGroupServiceGrpc; import com.google.protobuf.GeneratedMessageV3; import io.grpc.ServerServiceDefinition; import java.util.List; @javax.annotation.Generated("by GAPIC") public class MockErrorGroupService implements MockGrpcService { - private MockErrorGroupServiceImpl serviceImpl; + private final MockErrorGroupServiceImpl serviceImpl; public MockErrorGroupService() { serviceImpl = new MockErrorGroupServiceImpl(); diff --git a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/MockErrorStatsService.java b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/MockErrorStatsService.java index d3769a4d44ff..3a6cdcf64de6 100644 --- a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/MockErrorStatsService.java +++ b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/MockErrorStatsService.java @@ -15,14 +15,13 @@ package com.google.cloud.errorreporting.spi.v1beta1; import com.google.api.gax.testing.MockGrpcService; -import com.google.devtools.clouderrorreporting.v1beta1.ErrorStatsServiceGrpc; import com.google.protobuf.GeneratedMessageV3; import io.grpc.ServerServiceDefinition; import java.util.List; @javax.annotation.Generated("by GAPIC") public class MockErrorStatsService implements MockGrpcService { - private MockErrorStatsServiceImpl serviceImpl; + private final MockErrorStatsServiceImpl serviceImpl; public MockErrorStatsService() { serviceImpl = new MockErrorStatsServiceImpl(); diff --git a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/MockReportErrorsService.java b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/MockReportErrorsService.java index c519f91b52ac..e37b2109e026 100644 --- a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/MockReportErrorsService.java +++ b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/MockReportErrorsService.java @@ -15,14 +15,13 @@ package com.google.cloud.errorreporting.spi.v1beta1; import com.google.api.gax.testing.MockGrpcService; -import com.google.devtools.clouderrorreporting.v1beta1.ReportErrorsServiceGrpc; import com.google.protobuf.GeneratedMessageV3; import io.grpc.ServerServiceDefinition; import java.util.List; @javax.annotation.Generated("by GAPIC") public class MockReportErrorsService implements MockGrpcService { - private MockReportErrorsServiceImpl serviceImpl; + private final MockReportErrorsServiceImpl serviceImpl; public MockReportErrorsService() { serviceImpl = new MockReportErrorsServiceImpl(); diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceApi.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceApi.java index 836cf1b47fb2..d47133cf5af3 100644 --- a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceApi.java +++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceApi.java @@ -97,10 +97,6 @@ public class LanguageServiceApi implements AutoCloseable { analyzeEntitiesCallable; private final ApiCallable annotateTextCallable; - public final LanguageServiceSettings getSettings() { - return settings; - } - /** * Constructs an instance of LanguageServiceApi with default settings. */ @@ -155,6 +151,10 @@ public void close() throws IOException { } } + public final LanguageServiceSettings getSettings() { + return settings; + } + // AUTO-GENERATED DOCUMENTATION AND METHOD /** * Analyzes the sentiment of the provided text. @@ -310,7 +310,7 @@ public final AnalyzeEntitiesResponse analyzeEntities(AnalyzeEntitiesRequest requ *

    * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
    *   Document document = Document.newBuilder().build();
-   *   Features features = Features.newBuilder().build();
+   *   AnnotateTextRequest.Features features = AnnotateTextRequest.Features.newBuilder().build();
    *   EncodingType encodingType = EncodingType.NONE;
    *   AnnotateTextResponse response = languageServiceApi.annotateText(document, features, encodingType);
    * }
@@ -322,7 +322,7 @@ public final AnalyzeEntitiesResponse analyzeEntities(AnalyzeEntitiesRequest requ
    * @throws com.google.api.gax.grpc.ApiException if the remote call fails
    */
   public final AnnotateTextResponse annotateText(
-      Document document, Features features, EncodingType encodingType) {
+      Document document, AnnotateTextRequest.Features features, EncodingType encodingType) {
     AnnotateTextRequest request =
         AnnotateTextRequest.newBuilder()
             .setDocument(document)
@@ -343,7 +343,7 @@ public final AnnotateTextResponse annotateText(
    * 

    * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
    *   Document document = Document.newBuilder().build();
-   *   Features features = Features.newBuilder().build();
+   *   AnnotateTextRequest.Features features = AnnotateTextRequest.Features.newBuilder().build();
    *   EncodingType encodingType = EncodingType.NONE;
    *   AnnotateTextRequest request = AnnotateTextRequest.newBuilder()
    *     .setDocument(document)
@@ -372,7 +372,7 @@ public final AnnotateTextResponse annotateText(AnnotateTextRequest request) {
    * 

    * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
    *   Document document = Document.newBuilder().build();
-   *   Features features = Features.newBuilder().build();
+   *   AnnotateTextRequest.Features features = AnnotateTextRequest.Features.newBuilder().build();
    *   EncodingType encodingType = EncodingType.NONE;
    *   AnnotateTextRequest request = AnnotateTextRequest.newBuilder()
    *     .setDocument(document)
diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceSettings.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceSettings.java
index 4db00138dbdd..de0a26308a09 100644
--- a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceSettings.java
+++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceSettings.java
@@ -185,11 +185,11 @@ private LanguageServiceSettings(Builder settingsBuilder) throws IOException {
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder
         analyzeSentimentSettings;
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder
         analyzeEntitiesSettings;
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder
         annotateTextSettings;
 
     private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS;
diff --git a/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta1/LanguageServiceTest.java b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta1/LanguageServiceTest.java
index b52a92850f2c..962cba6419fc 100644
--- a/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta1/LanguageServiceTest.java
+++ b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta1/LanguageServiceTest.java
@@ -130,7 +130,7 @@ public void annotateTextTest() {
     mockLanguageService.setResponses(expectedResponses);
 
     Document document = Document.newBuilder().build();
-    Features features = Features.newBuilder().build();
+    AnnotateTextRequest.Features features = AnnotateTextRequest.Features.newBuilder().build();
     EncodingType encodingType = EncodingType.NONE;
 
     AnnotateTextResponse actualResponse = api.annotateText(document, features, encodingType);
diff --git a/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta1/MockLanguageService.java b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta1/MockLanguageService.java
index 24f01c0acb9b..cafe2987206f 100644
--- a/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta1/MockLanguageService.java
+++ b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta1/MockLanguageService.java
@@ -15,14 +15,13 @@
 package com.google.cloud.language.spi.v1beta1;
 
 import com.google.api.gax.testing.MockGrpcService;
-import com.google.cloud.language.v1beta1.LanguageServiceGrpc;
 import com.google.protobuf.GeneratedMessageV3;
 import io.grpc.ServerServiceDefinition;
 import java.util.List;
 
 @javax.annotation.Generated("by GAPIC")
 public class MockLanguageService implements MockGrpcService {
-  private MockLanguageServiceImpl serviceImpl;
+  private final MockLanguageServiceImpl serviceImpl;
 
   public MockLanguageService() {
     serviceImpl = new MockLanguageServiceImpl();
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Api.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Api.java
index 10ed2502a01f..6172bac44b91 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Api.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Api.java
@@ -100,10 +100,6 @@ public class ConfigServiceV2Api implements AutoCloseable {
   private final ApiCallable updateSinkCallable;
   private final ApiCallable deleteSinkCallable;
 
-  public final ConfigServiceV2Settings getSettings() {
-    return settings;
-  }
-
   private static final PathTemplate PARENT_PATH_TEMPLATE =
       PathTemplate.createWithoutUrlEncoding("projects/{project}");
 
@@ -212,6 +208,10 @@ public void close() throws IOException {
     }
   }
 
+  public final ConfigServiceV2Settings getSettings() {
+    return settings;
+  }
+
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * Lists sinks.
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Settings.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Settings.java
index db0dc45cf200..82273360d909 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Settings.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Settings.java
@@ -14,6 +14,7 @@
 package com.google.cloud.logging.spi.v2;
 
 import com.google.api.gax.core.ConnectionSettings;
+import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -204,7 +205,7 @@ private ConfigServiceV2Settings(Builder settingsBuilder) throws IOException {
     deleteSinkSettings = settingsBuilder.deleteSinkSettings().build();
   }
 
-  private static PageStreamingDescriptor
+  private static final PageStreamingDescriptor
       LIST_SINKS_PAGE_STR_DESC =
           new PageStreamingDescriptor() {
             @Override
@@ -244,12 +245,12 @@ public Iterable extractResources(ListSinksResponse payload) {
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
-    private PageStreamingCallSettings.Builder
+    private final PageStreamingCallSettings.Builder
         listSinksSettings;
-    private SimpleCallSettings.Builder getSinkSettings;
-    private SimpleCallSettings.Builder createSinkSettings;
-    private SimpleCallSettings.Builder updateSinkSettings;
-    private SimpleCallSettings.Builder deleteSinkSettings;
+    private final SimpleCallSettings.Builder getSinkSettings;
+    private final SimpleCallSettings.Builder createSinkSettings;
+    private final SimpleCallSettings.Builder updateSinkSettings;
+    private final SimpleCallSettings.Builder deleteSinkSettings;
 
     private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS;
 
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Api.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Api.java
index ee24b1012771..712ca4ed21cc 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Api.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Api.java
@@ -112,10 +112,6 @@ public class LoggingServiceV2Api implements AutoCloseable {
               MonitoredResourceDescriptor>>
       listMonitoredResourceDescriptorsPagedCallable;
 
-  public final LoggingServiceV2Settings getSettings() {
-    return settings;
-  }
-
   private static final PathTemplate PARENT_PATH_TEMPLATE =
       PathTemplate.createWithoutUrlEncoding("projects/{project}");
 
@@ -227,6 +223,10 @@ public void close() throws IOException {
     }
   }
 
+  public final LoggingServiceV2Settings getSettings() {
+    return settings;
+  }
+
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * Deletes a log and all its log entries.
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Settings.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Settings.java
index 360c5970b0c0..0cc02e00c964 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Settings.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Settings.java
@@ -15,6 +15,7 @@
 
 import com.google.api.MonitoredResourceDescriptor;
 import com.google.api.gax.core.ConnectionSettings;
+import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -206,7 +207,8 @@ private LoggingServiceV2Settings(Builder settingsBuilder) throws IOException {
         settingsBuilder.listMonitoredResourceDescriptorsSettings().build();
   }
 
-  private static PageStreamingDescriptor
+  private static final PageStreamingDescriptor<
+          ListLogEntriesRequest, ListLogEntriesResponse, LogEntry>
       LIST_LOG_ENTRIES_PAGE_STR_DESC =
           new PageStreamingDescriptor() {
             @Override
@@ -241,7 +243,7 @@ public Iterable extractResources(ListLogEntriesResponse payload) {
             }
           };
 
-  private static PageStreamingDescriptor<
+  private static final PageStreamingDescriptor<
           ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
           MonitoredResourceDescriptor>
       LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC =
@@ -292,13 +294,13 @@ public Iterable extractResources(
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
-    private SimpleCallSettings.Builder deleteLogSettings;
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder deleteLogSettings;
+    private final SimpleCallSettings.Builder
         writeLogEntriesSettings;
-    private PageStreamingCallSettings.Builder<
+    private final PageStreamingCallSettings.Builder<
             ListLogEntriesRequest, ListLogEntriesResponse, LogEntry>
         listLogEntriesSettings;
-    private PageStreamingCallSettings.Builder<
+    private final PageStreamingCallSettings.Builder<
             ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
             MonitoredResourceDescriptor>
         listMonitoredResourceDescriptorsSettings;
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Api.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Api.java
index 5a1b16237a76..53c07512a22c 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Api.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Api.java
@@ -100,10 +100,6 @@ public class MetricsServiceV2Api implements AutoCloseable {
   private final ApiCallable updateLogMetricCallable;
   private final ApiCallable deleteLogMetricCallable;
 
-  public final MetricsServiceV2Settings getSettings() {
-    return settings;
-  }
-
   private static final PathTemplate PARENT_PATH_TEMPLATE =
       PathTemplate.createWithoutUrlEncoding("projects/{project}");
 
@@ -213,6 +209,10 @@ public void close() throws IOException {
     }
   }
 
+  public final MetricsServiceV2Settings getSettings() {
+    return settings;
+  }
+
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * Lists logs-based metrics.
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Settings.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Settings.java
index e48680230dcf..c58f60f8e3e0 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Settings.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Settings.java
@@ -14,6 +14,7 @@
 package com.google.cloud.logging.spi.v2;
 
 import com.google.api.gax.core.ConnectionSettings;
+import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -204,7 +205,8 @@ private MetricsServiceV2Settings(Builder settingsBuilder) throws IOException {
     deleteLogMetricSettings = settingsBuilder.deleteLogMetricSettings().build();
   }
 
-  private static PageStreamingDescriptor
+  private static final PageStreamingDescriptor<
+          ListLogMetricsRequest, ListLogMetricsResponse, LogMetric>
       LIST_LOG_METRICS_PAGE_STR_DESC =
           new PageStreamingDescriptor() {
             @Override
@@ -245,13 +247,15 @@ public Iterable extractResources(ListLogMetricsResponse payload) {
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
-    private PageStreamingCallSettings.Builder<
+    private final PageStreamingCallSettings.Builder<
             ListLogMetricsRequest, ListLogMetricsResponse, LogMetric>
         listLogMetricsSettings;
-    private SimpleCallSettings.Builder getLogMetricSettings;
-    private SimpleCallSettings.Builder createLogMetricSettings;
-    private SimpleCallSettings.Builder updateLogMetricSettings;
-    private SimpleCallSettings.Builder deleteLogMetricSettings;
+    private final SimpleCallSettings.Builder getLogMetricSettings;
+    private final SimpleCallSettings.Builder
+        createLogMetricSettings;
+    private final SimpleCallSettings.Builder
+        updateLogMetricSettings;
+    private final SimpleCallSettings.Builder deleteLogMetricSettings;
 
     private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS;
 
diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MockConfigServiceV2.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MockConfigServiceV2.java
index faf30424ebd5..ad81fa344b11 100644
--- a/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MockConfigServiceV2.java
+++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MockConfigServiceV2.java
@@ -21,7 +21,7 @@
 
 @javax.annotation.Generated("by GAPIC")
 public class MockConfigServiceV2 implements MockGrpcService {
-  private MockConfigServiceV2Impl serviceImpl;
+  private final MockConfigServiceV2Impl serviceImpl;
 
   public MockConfigServiceV2() {
     serviceImpl = new MockConfigServiceV2Impl();
diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MockLoggingServiceV2.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MockLoggingServiceV2.java
index 236addeff7a9..27154d7df82a 100644
--- a/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MockLoggingServiceV2.java
+++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MockLoggingServiceV2.java
@@ -21,7 +21,7 @@
 
 @javax.annotation.Generated("by GAPIC")
 public class MockLoggingServiceV2 implements MockGrpcService {
-  private MockLoggingServiceV2Impl serviceImpl;
+  private final MockLoggingServiceV2Impl serviceImpl;
 
   public MockLoggingServiceV2() {
     serviceImpl = new MockLoggingServiceV2Impl();
diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MockMetricsServiceV2.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MockMetricsServiceV2.java
index 8b0ea5526094..2b5095215b8b 100644
--- a/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MockMetricsServiceV2.java
+++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MockMetricsServiceV2.java
@@ -21,7 +21,7 @@
 
 @javax.annotation.Generated("by GAPIC")
 public class MockMetricsServiceV2 implements MockGrpcService {
-  private MockMetricsServiceV2Impl serviceImpl;
+  private final MockMetricsServiceV2Impl serviceImpl;
 
   public MockMetricsServiceV2() {
     serviceImpl = new MockMetricsServiceV2Impl();
diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceApi.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceApi.java
index acec003d843f..f08630cd7fa9 100644
--- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceApi.java
+++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceApi.java
@@ -93,10 +93,6 @@ public class AgentTranslationServiceApi implements AutoCloseable {
   private final ApiCallable
       createCollectdTimeSeriesCallable;
 
-  public final AgentTranslationServiceSettings getSettings() {
-    return settings;
-  }
-
   private static final PathTemplate PROJECT_PATH_TEMPLATE =
       PathTemplate.createWithoutUrlEncoding("projects/{project}");
 
@@ -168,6 +164,10 @@ public void close() throws IOException {
     }
   }
 
+  public final AgentTranslationServiceSettings getSettings() {
+    return settings;
+  }
+
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * **Stackdriver Monitoring Agent only:** Creates a new time series.
diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceSettings.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceSettings.java
index ae87487fde4c..9af3c0b4c166 100644
--- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceSettings.java
+++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceSettings.java
@@ -161,7 +161,7 @@ private AgentTranslationServiceSettings(Builder settingsBuilder) throws IOExcept
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder
         createCollectdTimeSeriesSettings;
 
     private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS;
diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceApi.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceApi.java
index 78608f7f1c0d..48f7a007e528 100644
--- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceApi.java
+++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceApi.java
@@ -120,10 +120,6 @@ public class GroupServiceApi implements AutoCloseable {
           PagedListResponse>
       listGroupMembersPagedCallable;
 
-  public final GroupServiceSettings getSettings() {
-    return settings;
-  }
-
   private static final PathTemplate PROJECT_PATH_TEMPLATE =
       PathTemplate.createWithoutUrlEncoding("projects/{project}");
 
@@ -236,6 +232,10 @@ public void close() throws IOException {
     }
   }
 
+  public final GroupServiceSettings getSettings() {
+    return settings;
+  }
+
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * Lists the existing groups. The project ID in the URL path must refer
diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceSettings.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceSettings.java
index 5a13158b02d2..2b2b02fea282 100644
--- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceSettings.java
+++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceSettings.java
@@ -15,6 +15,7 @@
 
 import com.google.api.MonitoredResource;
 import com.google.api.gax.core.ConnectionSettings;
+import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -214,7 +215,7 @@ private GroupServiceSettings(Builder settingsBuilder) throws IOException {
     listGroupMembersSettings = settingsBuilder.listGroupMembersSettings().build();
   }
 
-  private static PageStreamingDescriptor
+  private static final PageStreamingDescriptor
       LIST_GROUPS_PAGE_STR_DESC =
           new PageStreamingDescriptor() {
             @Override
@@ -248,7 +249,7 @@ public Iterable extractResources(ListGroupsResponse payload) {
             }
           };
 
-  private static PageStreamingDescriptor<
+  private static final PageStreamingDescriptor<
           ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource>
       LIST_GROUP_MEMBERS_PAGE_STR_DESC =
           new PageStreamingDescriptor<
@@ -294,13 +295,13 @@ public Iterable extractResources(ListGroupMembersResponse pay
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
-    private PageStreamingCallSettings.Builder
+    private final PageStreamingCallSettings.Builder
         listGroupsSettings;
-    private SimpleCallSettings.Builder getGroupSettings;
-    private SimpleCallSettings.Builder createGroupSettings;
-    private SimpleCallSettings.Builder updateGroupSettings;
-    private SimpleCallSettings.Builder deleteGroupSettings;
-    private PageStreamingCallSettings.Builder<
+    private final SimpleCallSettings.Builder getGroupSettings;
+    private final SimpleCallSettings.Builder createGroupSettings;
+    private final SimpleCallSettings.Builder updateGroupSettings;
+    private final SimpleCallSettings.Builder deleteGroupSettings;
+    private final PageStreamingCallSettings.Builder<
             ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource>
         listGroupMembersSettings;
 
diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceApi.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceApi.java
index da6546754f39..f1ba47dc1283 100644
--- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceApi.java
+++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceApi.java
@@ -128,10 +128,6 @@ public class MetricServiceApi implements AutoCloseable {
       listTimeSeriesPagedCallable;
   private final ApiCallable createTimeSeriesCallable;
 
-  public final MetricServiceSettings getSettings() {
-    return settings;
-  }
-
   private static final PathTemplate PROJECT_PATH_TEMPLATE =
       PathTemplate.createWithoutUrlEncoding("projects/{project}");
 
@@ -297,6 +293,10 @@ public void close() throws IOException {
     }
   }
 
+  public final MetricServiceSettings getSettings() {
+    return settings;
+  }
+
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account.
@@ -861,7 +861,7 @@ public final ApiCallable deleteMetricDescr
    *   TimeInterval interval = TimeInterval.newBuilder().build();
    *   Aggregation aggregation = Aggregation.newBuilder().build();
    *   String orderBy = "";
-   *   TimeSeriesView view = TimeSeriesView.FULL;
+   *   ListTimeSeriesRequest.TimeSeriesView view = ListTimeSeriesRequest.TimeSeriesView.FULL;
    *   ListTimeSeriesRequest request = ListTimeSeriesRequest.newBuilder()
    *     .setName(formattedName)
    *     .setFilter(filter)
@@ -896,7 +896,7 @@ public final ApiCallable deleteMetricDescr
    *   TimeInterval interval = TimeInterval.newBuilder().build();
    *   Aggregation aggregation = Aggregation.newBuilder().build();
    *   String orderBy = "";
-   *   TimeSeriesView view = TimeSeriesView.FULL;
+   *   ListTimeSeriesRequest.TimeSeriesView view = ListTimeSeriesRequest.TimeSeriesView.FULL;
    *   ListTimeSeriesRequest request = ListTimeSeriesRequest.newBuilder()
    *     .setName(formattedName)
    *     .setFilter(filter)
@@ -932,7 +932,7 @@ public final ApiCallable deleteMetricDescr
    *   TimeInterval interval = TimeInterval.newBuilder().build();
    *   Aggregation aggregation = Aggregation.newBuilder().build();
    *   String orderBy = "";
-   *   TimeSeriesView view = TimeSeriesView.FULL;
+   *   ListTimeSeriesRequest.TimeSeriesView view = ListTimeSeriesRequest.TimeSeriesView.FULL;
    *   ListTimeSeriesRequest request = ListTimeSeriesRequest.newBuilder()
    *     .setName(formattedName)
    *     .setFilter(filter)
diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceSettings.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceSettings.java
index e52ce64c5ca1..dd1ec8c244ca 100644
--- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceSettings.java
+++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceSettings.java
@@ -16,6 +16,7 @@
 import com.google.api.MetricDescriptor;
 import com.google.api.MonitoredResourceDescriptor;
 import com.google.api.gax.core.ConnectionSettings;
+import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -252,7 +253,7 @@ private MetricServiceSettings(Builder settingsBuilder) throws IOException {
     createTimeSeriesSettings = settingsBuilder.createTimeSeriesSettings().build();
   }
 
-  private static PageStreamingDescriptor<
+  private static final PageStreamingDescriptor<
           ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
           MonitoredResourceDescriptor>
       LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC =
@@ -297,7 +298,7 @@ public Iterable extractResources(
             }
           };
 
-  private static PageStreamingDescriptor<
+  private static final PageStreamingDescriptor<
           ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor>
       LIST_METRIC_DESCRIPTORS_PAGE_STR_DESC =
           new PageStreamingDescriptor<
@@ -338,7 +339,8 @@ public Iterable extractResources(
             }
           };
 
-  private static PageStreamingDescriptor
+  private static final PageStreamingDescriptor<
+          ListTimeSeriesRequest, ListTimeSeriesResponse, TimeSeries>
       LIST_TIME_SERIES_PAGE_STR_DESC =
           new PageStreamingDescriptor() {
             @Override
@@ -379,26 +381,27 @@ public Iterable extractResources(ListTimeSeriesResponse payload) {
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
-    private PageStreamingCallSettings.Builder<
+    private final PageStreamingCallSettings.Builder<
             ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
             MonitoredResourceDescriptor>
         listMonitoredResourceDescriptorsSettings;
-    private SimpleCallSettings.Builder<
+    private final SimpleCallSettings.Builder<
             GetMonitoredResourceDescriptorRequest, MonitoredResourceDescriptor>
         getMonitoredResourceDescriptorSettings;
-    private PageStreamingCallSettings.Builder<
+    private final PageStreamingCallSettings.Builder<
             ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor>
         listMetricDescriptorsSettings;
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder
         getMetricDescriptorSettings;
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder
         createMetricDescriptorSettings;
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder
         deleteMetricDescriptorSettings;
-    private PageStreamingCallSettings.Builder<
+    private final PageStreamingCallSettings.Builder<
             ListTimeSeriesRequest, ListTimeSeriesResponse, TimeSeries>
         listTimeSeriesSettings;
-    private SimpleCallSettings.Builder createTimeSeriesSettings;
+    private final SimpleCallSettings.Builder
+        createTimeSeriesSettings;
 
     private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS;
 
diff --git a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockAgentTranslationService.java b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockAgentTranslationService.java
index a580421d56a4..3455f64948c8 100644
--- a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockAgentTranslationService.java
+++ b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockAgentTranslationService.java
@@ -15,14 +15,13 @@
 package com.google.cloud.monitoring.spi.v3;
 
 import com.google.api.gax.testing.MockGrpcService;
-import com.google.monitoring.v3.AgentTranslationServiceGrpc;
 import com.google.protobuf.GeneratedMessageV3;
 import io.grpc.ServerServiceDefinition;
 import java.util.List;
 
 @javax.annotation.Generated("by GAPIC")
 public class MockAgentTranslationService implements MockGrpcService {
-  private MockAgentTranslationServiceImpl serviceImpl;
+  private final MockAgentTranslationServiceImpl serviceImpl;
 
   public MockAgentTranslationService() {
     serviceImpl = new MockAgentTranslationServiceImpl();
diff --git a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockGroupService.java b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockGroupService.java
index 6322a7e084ef..f28a8f5f3a45 100644
--- a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockGroupService.java
+++ b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockGroupService.java
@@ -15,14 +15,13 @@
 package com.google.cloud.monitoring.spi.v3;
 
 import com.google.api.gax.testing.MockGrpcService;
-import com.google.monitoring.v3.GroupServiceGrpc;
 import com.google.protobuf.GeneratedMessageV3;
 import io.grpc.ServerServiceDefinition;
 import java.util.List;
 
 @javax.annotation.Generated("by GAPIC")
 public class MockGroupService implements MockGrpcService {
-  private MockGroupServiceImpl serviceImpl;
+  private final MockGroupServiceImpl serviceImpl;
 
   public MockGroupService() {
     serviceImpl = new MockGroupServiceImpl();
diff --git a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockMetricService.java b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockMetricService.java
index 384d0c7acb96..2f21f8b1eee3 100644
--- a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockMetricService.java
+++ b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockMetricService.java
@@ -15,14 +15,13 @@
 package com.google.cloud.monitoring.spi.v3;
 
 import com.google.api.gax.testing.MockGrpcService;
-import com.google.monitoring.v3.MetricServiceGrpc;
 import com.google.protobuf.GeneratedMessageV3;
 import io.grpc.ServerServiceDefinition;
 import java.util.List;
 
 @javax.annotation.Generated("by GAPIC")
 public class MockMetricService implements MockGrpcService {
-  private MockMetricServiceImpl serviceImpl;
+  private final MockMetricServiceImpl serviceImpl;
 
   public MockMetricService() {
     serviceImpl = new MockMetricServiceImpl();
diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherApi.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherApi.java
index 1d131fd560d5..717563c89914 100644
--- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherApi.java
+++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherApi.java
@@ -118,10 +118,6 @@ public class PublisherApi implements AutoCloseable {
   private final ApiCallable
       testIamPermissionsCallable;
 
-  public final PublisherSettings getSettings() {
-    return settings;
-  }
-
   private static final PathTemplate PROJECT_PATH_TEMPLATE =
       PathTemplate.createWithoutUrlEncoding("projects/{project}");
 
@@ -243,6 +239,10 @@ public void close() throws IOException {
     }
   }
 
+  public final PublisherSettings getSettings() {
+    return settings;
+  }
+
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * Creates the given topic with the given name.
diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherSettings.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherSettings.java
index c626216fe117..53089e87744f 100644
--- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherSettings.java
+++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherSettings.java
@@ -14,6 +14,7 @@
 package com.google.cloud.pubsub.spi.v1;
 
 import com.google.api.gax.core.ConnectionSettings;
+import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.BundlingCallSettings;
@@ -258,7 +259,7 @@ private PublisherSettings(Builder settingsBuilder) throws IOException {
     testIamPermissionsSettings = settingsBuilder.testIamPermissionsSettings().build();
   }
 
-  private static PageStreamingDescriptor
+  private static final PageStreamingDescriptor
       LIST_TOPICS_PAGE_STR_DESC =
           new PageStreamingDescriptor() {
             @Override
@@ -292,7 +293,7 @@ public Iterable extractResources(ListTopicsResponse payload) {
             }
           };
 
-  private static PageStreamingDescriptor<
+  private static final PageStreamingDescriptor<
           ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String>
       LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_DESC =
           new PageStreamingDescriptor<
@@ -334,7 +335,7 @@ public Iterable extractResources(ListTopicSubscriptionsResponse payload)
             }
           };
 
-  private static BundlingDescriptor PUBLISH_BUNDLING_DESC =
+  private static final BundlingDescriptor PUBLISH_BUNDLING_DESC =
       new BundlingDescriptor() {
         @Override
         public String getBundlePartitionKey(PublishRequest request) {
@@ -402,18 +403,18 @@ public long countBytes(PublishRequest request) {
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
-    private SimpleCallSettings.Builder createTopicSettings;
-    private BundlingCallSettings.Builder publishSettings;
-    private SimpleCallSettings.Builder getTopicSettings;
-    private PageStreamingCallSettings.Builder
+    private final SimpleCallSettings.Builder createTopicSettings;
+    private final BundlingCallSettings.Builder publishSettings;
+    private final SimpleCallSettings.Builder getTopicSettings;
+    private final PageStreamingCallSettings.Builder
         listTopicsSettings;
-    private PageStreamingCallSettings.Builder<
+    private final PageStreamingCallSettings.Builder<
             ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String>
         listTopicSubscriptionsSettings;
-    private SimpleCallSettings.Builder deleteTopicSettings;
-    private SimpleCallSettings.Builder setIamPolicySettings;
-    private SimpleCallSettings.Builder getIamPolicySettings;
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder deleteTopicSettings;
+    private final SimpleCallSettings.Builder setIamPolicySettings;
+    private final SimpleCallSettings.Builder getIamPolicySettings;
+    private final SimpleCallSettings.Builder
         testIamPermissionsSettings;
 
     private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS;
diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberApi.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberApi.java
index 147cc4be18a6..1d2a33d77990 100644
--- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberApi.java
+++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberApi.java
@@ -121,10 +121,6 @@ public class SubscriberApi implements AutoCloseable {
   private final ApiCallable
       testIamPermissionsCallable;
 
-  public final SubscriberSettings getSettings() {
-    return settings;
-  }
-
   private static final PathTemplate PROJECT_PATH_TEMPLATE =
       PathTemplate.createWithoutUrlEncoding("projects/{project}");
 
@@ -273,14 +269,19 @@ public void close() throws IOException {
     }
   }
 
+  public final SubscriberSettings getSettings() {
+    return settings;
+  }
+
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Creates a subscription to a given topic for a given subscriber.
+   * Creates a subscription to a given topic.
    * If the subscription already exists, returns `ALREADY_EXISTS`.
    * If the corresponding topic doesn't exist, returns `NOT_FOUND`.
    *
    * If the name is not provided in the request, the server will assign a random
-   * name for this subscription on the same project as the topic.
+   * name for this subscription on the same project as the topic. Note that
+   * for REST API requests, you must specify a name.
    *
    * Sample code:
    * 

@@ -315,6 +316,7 @@ public void close() throws IOException {
    * deadline. To override this value for a given message, call
    * `ModifyAckDeadline` with the corresponding `ack_id` if using
    * pull.
+   * The maximum custom deadline you can specify is 600 seconds (10 minutes).
    *
    * For push delivery, this value is also used to set the request timeout for
    * the call to the push endpoint.
@@ -322,7 +324,7 @@ public void close() throws IOException {
    * If the subscriber never acknowledges the message, the Pub/Sub
    * system will eventually redeliver the message.
    *
-   * If this parameter is not set, the default value of 10 seconds is used.
+   * If this parameter is 0, a default value of 10 seconds is used.
    * @throws com.google.api.gax.grpc.ApiException if the remote call fails
    */
   public final Subscription createSubscription(
@@ -341,12 +343,13 @@ public final Subscription createSubscription(
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Creates a subscription to a given topic for a given subscriber.
+   * Creates a subscription to a given topic.
    * If the subscription already exists, returns `ALREADY_EXISTS`.
    * If the corresponding topic doesn't exist, returns `NOT_FOUND`.
    *
    * If the name is not provided in the request, the server will assign a random
-   * name for this subscription on the same project as the topic.
+   * name for this subscription on the same project as the topic. Note that
+   * for REST API requests, you must specify a name.
    *
    * Sample code:
    * 

@@ -370,12 +373,13 @@ public final Subscription createSubscription(Subscription request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Creates a subscription to a given topic for a given subscriber.
+   * Creates a subscription to a given topic.
    * If the subscription already exists, returns `ALREADY_EXISTS`.
    * If the corresponding topic doesn't exist, returns `NOT_FOUND`.
    *
    * If the name is not provided in the request, the server will assign a random
-   * name for this subscription on the same project as the topic.
+   * name for this subscription on the same project as the topic. Note that
+   * for REST API requests, you must specify a name.
    *
    * Sample code:
    * 

@@ -650,7 +654,8 @@ public final ApiCallable deleteSubscriptionCal
    * Modifies the ack deadline for a specific message. This method is useful
    * to indicate that more time is needed to process a message by the
    * subscriber, or to make the message available for redelivery if the
-   * processing was interrupted.
+   * processing was interrupted. Note that this does not modify the
+   * subscription-level `ackDeadlineSeconds` used for subsequent messages.
    *
    * Sample code:
    * 

@@ -688,7 +693,8 @@ public final void modifyAckDeadline(
    * Modifies the ack deadline for a specific message. This method is useful
    * to indicate that more time is needed to process a message by the
    * subscriber, or to make the message available for redelivery if the
-   * processing was interrupted.
+   * processing was interrupted. Note that this does not modify the
+   * subscription-level `ackDeadlineSeconds` used for subsequent messages.
    *
    * Sample code:
    * 

@@ -717,7 +723,8 @@ public final void modifyAckDeadline(ModifyAckDeadlineRequest request) {
    * Modifies the ack deadline for a specific message. This method is useful
    * to indicate that more time is needed to process a message by the
    * subscriber, or to make the message available for redelivery if the
-   * processing was interrupted.
+   * processing was interrupted. Note that this does not modify the
+   * subscription-level `ackDeadlineSeconds` used for subsequent messages.
    *
    * Sample code:
    * 

diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberSettings.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberSettings.java
index 1eb8e6af5849..d29209d5e860 100644
--- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberSettings.java
+++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberSettings.java
@@ -14,6 +14,7 @@
 package com.google.cloud.pubsub.spi.v1;
 
 import com.google.api.gax.core.ConnectionSettings;
+import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -268,7 +269,7 @@ private SubscriberSettings(Builder settingsBuilder) throws IOException {
     testIamPermissionsSettings = settingsBuilder.testIamPermissionsSettings().build();
   }
 
-  private static PageStreamingDescriptor<
+  private static final PageStreamingDescriptor<
           ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription>
       LIST_SUBSCRIPTIONS_PAGE_STR_DESC =
           new PageStreamingDescriptor<
@@ -314,20 +315,23 @@ public Iterable extractResources(ListSubscriptionsResponse payload
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
-    private SimpleCallSettings.Builder createSubscriptionSettings;
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder createSubscriptionSettings;
+    private final SimpleCallSettings.Builder
         getSubscriptionSettings;
-    private PageStreamingCallSettings.Builder<
+    private final PageStreamingCallSettings.Builder<
             ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription>
         listSubscriptionsSettings;
-    private SimpleCallSettings.Builder deleteSubscriptionSettings;
-    private SimpleCallSettings.Builder modifyAckDeadlineSettings;
-    private SimpleCallSettings.Builder acknowledgeSettings;
-    private SimpleCallSettings.Builder pullSettings;
-    private SimpleCallSettings.Builder modifyPushConfigSettings;
-    private SimpleCallSettings.Builder setIamPolicySettings;
-    private SimpleCallSettings.Builder getIamPolicySettings;
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder
+        deleteSubscriptionSettings;
+    private final SimpleCallSettings.Builder
+        modifyAckDeadlineSettings;
+    private final SimpleCallSettings.Builder acknowledgeSettings;
+    private final SimpleCallSettings.Builder pullSettings;
+    private final SimpleCallSettings.Builder
+        modifyPushConfigSettings;
+    private final SimpleCallSettings.Builder setIamPolicySettings;
+    private final SimpleCallSettings.Builder getIamPolicySettings;
+    private final SimpleCallSettings.Builder
         testIamPermissionsSettings;
 
     private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS;
diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/MockIAMPolicy.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/MockIAMPolicy.java
index 241181d4a8a7..af1f8b9c4bd1 100644
--- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/MockIAMPolicy.java
+++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/MockIAMPolicy.java
@@ -15,14 +15,13 @@
 package com.google.cloud.pubsub.spi.v1;
 
 import com.google.api.gax.testing.MockGrpcService;
-import com.google.iam.v1.IAMPolicyGrpc;
 import com.google.protobuf.GeneratedMessageV3;
 import io.grpc.ServerServiceDefinition;
 import java.util.List;
 
 @javax.annotation.Generated("by GAPIC")
 public class MockIAMPolicy implements MockGrpcService {
-  private MockIAMPolicyImpl serviceImpl;
+  private final MockIAMPolicyImpl serviceImpl;
 
   public MockIAMPolicy() {
     serviceImpl = new MockIAMPolicyImpl();
diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/MockPublisher.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/MockPublisher.java
index 9c5b0a594a44..406d8149f40a 100644
--- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/MockPublisher.java
+++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/MockPublisher.java
@@ -16,13 +16,12 @@
 
 import com.google.api.gax.testing.MockGrpcService;
 import com.google.protobuf.GeneratedMessageV3;
-import com.google.pubsub.v1.PublisherGrpc;
 import io.grpc.ServerServiceDefinition;
 import java.util.List;
 
 @javax.annotation.Generated("by GAPIC")
 public class MockPublisher implements MockGrpcService {
-  private MockPublisherImpl serviceImpl;
+  private final MockPublisherImpl serviceImpl;
 
   public MockPublisher() {
     serviceImpl = new MockPublisherImpl();
diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/MockSubscriber.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/MockSubscriber.java
index 1355a9fd1ef1..eb326938b92b 100644
--- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/MockSubscriber.java
+++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/MockSubscriber.java
@@ -16,13 +16,12 @@
 
 import com.google.api.gax.testing.MockGrpcService;
 import com.google.protobuf.GeneratedMessageV3;
-import com.google.pubsub.v1.SubscriberGrpc;
 import io.grpc.ServerServiceDefinition;
 import java.util.List;
 
 @javax.annotation.Generated("by GAPIC")
 public class MockSubscriber implements MockGrpcService {
-  private MockSubscriberImpl serviceImpl;
+  private final MockSubscriberImpl serviceImpl;
 
   public MockSubscriber() {
     serviceImpl = new MockSubscriberImpl();
diff --git a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechApi.java b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechApi.java
index a77b0d40a1c8..149793e08103 100644
--- a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechApi.java
+++ b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechApi.java
@@ -91,10 +91,6 @@ public class SpeechApi implements AutoCloseable {
   private final ApiCallable syncRecognizeCallable;
   private final ApiCallable asyncRecognizeCallable;
 
-  public final SpeechSettings getSettings() {
-    return settings;
-  }
-
   /**
    * Constructs an instance of SpeechApi with default settings.
    */
@@ -146,6 +142,10 @@ public void close() throws IOException {
     }
   }
 
+  public final SpeechSettings getSettings() {
+    return settings;
+  }
+
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * Perform synchronous speech-recognition: receive results after all audio
@@ -224,8 +224,9 @@ public final ApiCallable syncRecogn
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * Perform asynchronous speech-recognition: receive results via the
-   * google.longrunning.Operations interface. `Operation.response` returns
-   * `AsyncRecognizeResponse`.
+   * google.longrunning.Operations interface. Returns either an
+   * `Operation.error` or an `Operation.response` which contains
+   * an `AsyncRecognizeResponse` message.
    *
    * Sample code:
    * 

@@ -250,8 +251,9 @@ public final Operation asyncRecognize(RecognitionConfig config, RecognitionAudio
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * Perform asynchronous speech-recognition: receive results via the
-   * google.longrunning.Operations interface. `Operation.response` returns
-   * `AsyncRecognizeResponse`.
+   * google.longrunning.Operations interface. Returns either an
+   * `Operation.error` or an `Operation.response` which contains
+   * an `AsyncRecognizeResponse` message.
    *
    * Sample code:
    * 

@@ -276,8 +278,9 @@ public final Operation asyncRecognize(AsyncRecognizeRequest request) {
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * Perform asynchronous speech-recognition: receive results via the
-   * google.longrunning.Operations interface. `Operation.response` returns
-   * `AsyncRecognizeResponse`.
+   * google.longrunning.Operations interface. Returns either an
+   * `Operation.error` or an `Operation.response` which contains
+   * an `AsyncRecognizeResponse` message.
    *
    * Sample code:
    * 

diff --git a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechSettings.java b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechSettings.java
index 1b3c3774be9c..6cffd44dac83 100644
--- a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechSettings.java
+++ b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechSettings.java
@@ -171,9 +171,10 @@ private SpeechSettings(Builder settingsBuilder) throws IOException {
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder
         syncRecognizeSettings;
-    private SimpleCallSettings.Builder asyncRecognizeSettings;
+    private final SimpleCallSettings.Builder
+        asyncRecognizeSettings;
 
     private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS;
 
diff --git a/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/MockSpeech.java b/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/MockSpeech.java
index ec3185919394..4d08b3fd6cfc 100644
--- a/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/MockSpeech.java
+++ b/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/MockSpeech.java
@@ -15,14 +15,13 @@
 package com.google.cloud.speech.spi.v1beta1;
 
 import com.google.api.gax.testing.MockGrpcService;
-import com.google.cloud.speech.v1beta1.SpeechGrpc;
 import com.google.protobuf.GeneratedMessageV3;
 import io.grpc.ServerServiceDefinition;
 import java.util.List;
 
 @javax.annotation.Generated("by GAPIC")
 public class MockSpeech implements MockGrpcService {
-  private MockSpeechImpl serviceImpl;
+  private final MockSpeechImpl serviceImpl;
 
   public MockSpeech() {
     serviceImpl = new MockSpeechImpl();
diff --git a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceApi.java b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceApi.java
index f7e3afe0b9c9..0342aa225dba 100644
--- a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceApi.java
+++ b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceApi.java
@@ -101,10 +101,6 @@ public class TraceServiceApi implements AutoCloseable {
           ListTracesRequest, PagedListResponse>
       listTracesPagedCallable;
 
-  public final TraceServiceSettings getSettings() {
-    return settings;
-  }
-
   /**
    * Constructs an instance of TraceServiceApi with default settings.
    */
@@ -160,6 +156,10 @@ public void close() throws IOException {
     }
   }
 
+  public final TraceServiceSettings getSettings() {
+    return settings;
+  }
+
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * Sends new traces to Cloud Trace or updates existing traces. If the ID of
diff --git a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java
index 413759d4e53b..39445d3c148b 100644
--- a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java
+++ b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java
@@ -14,6 +14,7 @@
 package com.google.cloud.trace.spi.v1;
 
 import com.google.api.gax.core.ConnectionSettings;
+import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -182,7 +183,7 @@ private TraceServiceSettings(Builder settingsBuilder) throws IOException {
     listTracesSettings = settingsBuilder.listTracesSettings().build();
   }
 
-  private static PageStreamingDescriptor
+  private static final PageStreamingDescriptor
       LIST_TRACES_PAGE_STR_DESC =
           new PageStreamingDescriptor() {
             @Override
@@ -224,9 +225,9 @@ public Iterable extractResources(ListTracesResponse payload) {
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
-    private SimpleCallSettings.Builder patchTracesSettings;
-    private SimpleCallSettings.Builder getTraceSettings;
-    private PageStreamingCallSettings.Builder
+    private final SimpleCallSettings.Builder patchTracesSettings;
+    private final SimpleCallSettings.Builder getTraceSettings;
+    private final PageStreamingCallSettings.Builder
         listTracesSettings;
 
     private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS;
diff --git a/google-cloud-trace/src/test/java/com/google/cloud/trace/spi/v1/MockTraceService.java b/google-cloud-trace/src/test/java/com/google/cloud/trace/spi/v1/MockTraceService.java
index 95c45f72975d..a4a79046cdf7 100644
--- a/google-cloud-trace/src/test/java/com/google/cloud/trace/spi/v1/MockTraceService.java
+++ b/google-cloud-trace/src/test/java/com/google/cloud/trace/spi/v1/MockTraceService.java
@@ -15,14 +15,13 @@
 package com.google.cloud.trace.spi.v1;
 
 import com.google.api.gax.testing.MockGrpcService;
-import com.google.devtools.cloudtrace.v1.TraceServiceGrpc;
 import com.google.protobuf.GeneratedMessageV3;
 import io.grpc.ServerServiceDefinition;
 import java.util.List;
 
 @javax.annotation.Generated("by GAPIC")
 public class MockTraceService implements MockGrpcService {
-  private MockTraceServiceImpl serviceImpl;
+  private final MockTraceServiceImpl serviceImpl;
 
   public MockTraceService() {
     serviceImpl = new MockTraceServiceImpl();
diff --git a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorApi.java b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorApi.java
index ed0fedf62399..461f37be77af 100644
--- a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorApi.java
+++ b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorApi.java
@@ -89,10 +89,6 @@ public class ImageAnnotatorApi implements AutoCloseable {
   private final ApiCallable
       batchAnnotateImagesCallable;
 
-  public final ImageAnnotatorSettings getSettings() {
-    return settings;
-  }
-
   /**
    * Constructs an instance of ImageAnnotatorApi with default settings.
    */
@@ -142,6 +138,10 @@ public void close() throws IOException {
     }
   }
 
+  public final ImageAnnotatorSettings getSettings() {
+    return settings;
+  }
+
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
    * Run image detection and annotation for a batch of images.
diff --git a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorSettings.java b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorSettings.java
index 3828d661041a..cb742141e4e0 100644
--- a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorSettings.java
+++ b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorSettings.java
@@ -161,7 +161,8 @@ private ImageAnnotatorSettings(Builder settingsBuilder) throws IOException {
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
-    private SimpleCallSettings.Builder
+    private final SimpleCallSettings.Builder<
+            BatchAnnotateImagesRequest, BatchAnnotateImagesResponse>
         batchAnnotateImagesSettings;
 
     private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS;
diff --git a/google-cloud-vision/src/test/java/com/google/cloud/vision/spi/v1/MockImageAnnotator.java b/google-cloud-vision/src/test/java/com/google/cloud/vision/spi/v1/MockImageAnnotator.java
index db4b51a7fe06..a7b49ad4c92e 100644
--- a/google-cloud-vision/src/test/java/com/google/cloud/vision/spi/v1/MockImageAnnotator.java
+++ b/google-cloud-vision/src/test/java/com/google/cloud/vision/spi/v1/MockImageAnnotator.java
@@ -15,14 +15,13 @@
 package com.google.cloud.vision.spi.v1;
 
 import com.google.api.gax.testing.MockGrpcService;
-import com.google.cloud.vision.v1.ImageAnnotatorGrpc;
 import com.google.protobuf.GeneratedMessageV3;
 import io.grpc.ServerServiceDefinition;
 import java.util.List;
 
 @javax.annotation.Generated("by GAPIC")
 public class MockImageAnnotator implements MockGrpcService {
-  private MockImageAnnotatorImpl serviceImpl;
+  private final MockImageAnnotatorImpl serviceImpl;
 
   public MockImageAnnotator() {
     serviceImpl = new MockImageAnnotatorImpl();

From 88b8b4a069d5fe90d16c288c8967713a20cae682 Mon Sep 17 00:00:00 2001
From: Marco Ziccardi 
Date: Sun, 2 Oct 2016 21:18:58 +0200
Subject: [PATCH 04/32] Allow storage.reader to read gzip blobs in compressed
 chunks (#1301)

---
 .../cloud/storage/spi/DefaultStorageRpc.java  | 23 ++++++++++++-
 .../cloud/storage/it/ITStorageTest.java       | 33 +++++++++++++++++++
 2 files changed, 55 insertions(+), 1 deletion(-)

diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/spi/DefaultStorageRpc.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/spi/DefaultStorageRpc.java
index 54e4447ebff5..14271274bf23 100644
--- a/google-cloud-storage/src/main/java/com/google/cloud/storage/spi/DefaultStorageRpc.java
+++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/spi/DefaultStorageRpc.java
@@ -51,9 +51,11 @@
 import com.google.api.client.http.HttpResponseException;
 import com.google.api.client.http.HttpTransport;
 import com.google.api.client.http.InputStreamContent;
+import com.google.api.client.http.LowLevelHttpResponse;
 import com.google.api.client.http.json.JsonHttpContent;
 import com.google.api.client.json.JsonFactory;
 import com.google.api.client.json.jackson.JacksonFactory;
+import com.google.api.client.util.IOUtils;
 import com.google.api.services.storage.Storage;
 import com.google.api.services.storage.Storage.Objects.Get;
 import com.google.api.services.storage.Storage.Objects.Insert;
@@ -65,6 +67,7 @@
 import com.google.api.services.storage.model.ObjectAccessControl;
 import com.google.api.services.storage.model.Objects;
 import com.google.api.services.storage.model.StorageObject;
+import com.google.cloud.BaseServiceException;
 import com.google.cloud.storage.StorageException;
 import com.google.cloud.storage.StorageOptions;
 import com.google.common.base.Function;
@@ -78,6 +81,7 @@
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.lang.reflect.Field;
 import java.math.BigInteger;
 import java.util.ArrayList;
 import java.util.LinkedList;
@@ -500,7 +504,24 @@ public Tuple read(StorageObject from, Map options, lo
       requestHeaders.setRange(range.toString());
       setEncryptionHeaders(requestHeaders, ENCRYPTION_KEY_PREFIX, options);
       ByteArrayOutputStream output = new ByteArrayOutputStream(bytes);
-      req.executeMedia().download(output);
+      HttpResponse httpResponse = req.executeMedia();
+      // todo(mziccard) remove when
+      // https://github.com/GoogleCloudPlatform/google-cloud-java/issues/982 is fixed
+      String contentEncoding = httpResponse.getContentEncoding();
+      if (contentEncoding != null && contentEncoding.contains("gzip")) {
+        try {
+          Field responseField = httpResponse.getClass().getDeclaredField("response");
+          responseField.setAccessible(true);
+          LowLevelHttpResponse lowLevelHttpResponse =
+              (LowLevelHttpResponse) responseField.get(httpResponse);
+          IOUtils.copy(lowLevelHttpResponse.getContent(), output);
+        } catch (IllegalAccessException|NoSuchFieldException ex) {
+          throw new StorageException(
+              BaseServiceException.UNKNOWN_CODE, "Error parsing gzip response", ex);
+        }
+      } else {
+        httpResponse.download(output);
+      }
       String etag = req.getLastResponseHeaders().getETag();
       return Tuple.of(etag, output.toByteArray());
     } catch (IOException ex) {
diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java
index e45fb117bfe7..cc2f820f6675 100644
--- a/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java
+++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java
@@ -53,6 +53,7 @@
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 import com.google.common.io.BaseEncoding;
+import com.google.common.io.ByteStreams;
 
 import org.junit.AfterClass;
 import org.junit.BeforeClass;
@@ -79,6 +80,7 @@
 import java.util.concurrent.TimeUnit;
 import java.util.logging.Level;
 import java.util.logging.Logger;
+import java.util.zip.GZIPInputStream;
 
 import javax.crypto.spec.SecretKeySpec;
 
@@ -96,6 +98,8 @@ public class ITStorageTest {
   private static final String OTHER_BASE64_KEY = "IcOIQGlliNr5pr3vJb63l+XMqc7NjXqjfw/deBoNxPA=";
   private static final Key KEY =
       new SecretKeySpec(BaseEncoding.base64().decode(BASE64_KEY), "AES256");
+  private static final byte[] COMPRESSED_CONTENT = BaseEncoding.base64()
+      .decode("H4sIAAAAAAAAAPNIzcnJV3DPz0/PSVVwzskvTVEILskvSkxPVQQA/LySchsAAAA=");
 
   @BeforeClass
   public static void beforeClass() throws NoSuchAlgorithmException, InvalidKeySpecException {
@@ -1381,4 +1385,33 @@ public void testBlobAcl() {
       // expected
     }
   }
+
+  @Test
+  public void testReadCompressedBlob() throws IOException {
+    String blobName = "test-read-compressed-blob";
+    BlobInfo blobInfo = BlobInfo.builder(BlobId.of(BUCKET, blobName))
+        .contentType("text/plain")
+        .contentEncoding("gzip")
+        .build();
+    Blob blob = storage.create(blobInfo, COMPRESSED_CONTENT);
+    try (ByteArrayOutputStream output = new ByteArrayOutputStream()) {
+      try (ReadChannel reader = storage.reader(BlobId.of(BUCKET, blobName))) {
+        reader.chunkSize(8);
+        ByteBuffer buffer = ByteBuffer.allocate(8);
+        while (reader.read(buffer) != -1) {
+          buffer.flip();
+          output.write(buffer.array(), 0, buffer.limit());
+          buffer.clear();
+        }
+      }
+      assertArrayEquals(BLOB_STRING_CONTENT.getBytes(UTF_8),
+          storage.readAllBytes(BUCKET, blobName));
+      assertArrayEquals(COMPRESSED_CONTENT, output.toByteArray());
+      try (GZIPInputStream zipInput =
+               new GZIPInputStream(new ByteArrayInputStream(output.toByteArray()))) {
+        assertArrayEquals(BLOB_STRING_CONTENT.getBytes(UTF_8), ByteStreams.toByteArray(zipInput));
+      }
+    }
+    blob.delete();
+  }
 }

From b61af33af8eb0c5401b387fd940da33e4936c61c Mon Sep 17 00:00:00 2001
From: Marco Ziccardi 
Date: Sun, 2 Oct 2016 22:23:16 +0200
Subject: [PATCH 05/32] Fix datastore emulator md5 checksum (#1302)

---
 .../google/cloud/datastore/testing/LocalDatastoreHelper.java    | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java
index c01e9e0ba4db..35e1d0593641 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java
@@ -71,7 +71,7 @@ public class LocalDatastoreHelper {
   private static final double DEFAULT_CONSISTENCY = 0.9;
   private static final String GCD_BASENAME = "cloud-datastore-emulator-" + GCD_VERSION;
   private static final String GCD_FILENAME = GCD_BASENAME + ".zip";
-  private static final String MD5_CHECKSUM = "e68695ff005421ccb7144689d9633df1";
+  private static final String MD5_CHECKSUM = "ec2237a0f0ac54964c6bd95e12c73720";
   private static final URL GCD_URL;
   private static final String GCLOUD = "gcloud";
   private static final Path INSTALLED_GCD_PATH;

From 88344a2769f2ff44afdaa236763dbc310ac221ac Mon Sep 17 00:00:00 2001
From: garrettjonesgoogle 
Date: Tue, 4 Oct 2016 07:47:33 -0700
Subject: [PATCH 06/32] Regenerating spi layer - format cleanup (#1306)

* Formatting using latest google-java-format (1.1)
* Removing unused imports
---
 .../spi/v1beta1/ErrorGroupServiceApi.java     |  97 ++--
 .../v1beta1/ErrorGroupServiceSettings.java    |  80 +--
 .../spi/v1beta1/ErrorStatsServiceApi.java     | 112 ++---
 .../v1beta1/ErrorStatsServiceSettings.java    |  88 +---
 .../spi/v1beta1/ReportErrorsServiceApi.java   | 105 ++--
 .../v1beta1/ReportErrorsServiceSettings.java  |  72 +--
 .../spi/v1beta1/package-info.java             |  30 +-
 .../spi/v1beta1/ErrorGroupServiceTest.java    |   2 -
 .../spi/v1beta1/ReportErrorsServiceTest.java  |   2 -
 .../spi/v1beta1/LanguageServiceApi.java       | 106 ++--
 .../spi/v1beta1/LanguageServiceSettings.java  |  87 +---
 .../language/spi/v1beta1/package-info.java    |  12 +-
 .../spi/v1beta1/LanguageServiceTest.java      |   2 -
 .../logging/spi/v2/ConfigServiceV2Api.java    | 152 +++---
 .../spi/v2/ConfigServiceV2Settings.java       | 103 ++--
 .../logging/spi/v2/LoggingServiceV2Api.java   | 198 ++++----
 .../spi/v2/LoggingServiceV2Settings.java      |  95 +---
 .../logging/spi/v2/MetricsServiceV2Api.java   | 153 +++---
 .../spi/v2/MetricsServiceV2Settings.java      | 103 ++--
 .../cloud/logging/spi/v2/package-info.java    |  32 +-
 .../spi/v3/AgentTranslationServiceApi.java    |  99 ++--
 .../v3/AgentTranslationServiceSettings.java   |  71 +--
 .../monitoring/spi/v3/GroupServiceApi.java    | 244 +++++----
 .../spi/v3/GroupServiceSettings.java          | 111 ++---
 .../monitoring/spi/v3/MetricServiceApi.java   | 303 ++++++------
 .../spi/v3/MetricServiceSettings.java         | 127 ++---
 .../cloud/monitoring/spi/v3/package-info.java |  53 +-
 .../spi/v3/AgentTranslationServiceTest.java   |   2 -
 .../cloud/pubsub/spi/v1/PublisherApi.java     | 251 +++++-----
 .../pubsub/spi/v1/PublisherSettings.java      | 135 ++---
 .../cloud/pubsub/spi/v1/SubscriberApi.java    | 467 +++++++++---------
 .../pubsub/spi/v1/SubscriberSettings.java     | 151 ++----
 .../cloud/pubsub/spi/v1/package-info.java     |  21 +-
 .../cloud/speech/spi/v1beta1/SpeechApi.java   | 109 ++--
 .../speech/spi/v1beta1/SpeechSettings.java    |  79 +--
 .../speech/spi/v1beta1/package-info.java      |  12 +-
 .../cloud/speech/spi/v1beta1/SpeechTest.java  |   2 -
 .../cloud/trace/spi/v1/TraceServiceApi.java   | 110 ++---
 .../trace/spi/v1/TraceServiceSettings.java    |  87 +---
 .../cloud/trace/spi/v1/package-info.java      |  19 +-
 .../vision/spi/v1/ImageAnnotatorApi.java      |  59 ++-
 .../vision/spi/v1/ImageAnnotatorSettings.java |  71 +--
 .../cloud/vision/spi/v1/package-info.java     |  16 +-
 .../vision/spi/v1/ImageAnnotatorTest.java     |   2 -
 44 files changed, 1726 insertions(+), 2506 deletions(-)

diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceApi.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceApi.java
index 8c9ff4b4004c..fecd24c11af0 100644
--- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceApi.java
+++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceApi.java
@@ -42,28 +42,27 @@
  * 
* *

Note: close() needs to be called on the errorGroupServiceApi object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + * as threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * *

This class can be customized by passing in a custom instance of ErrorGroupServiceSettings to * create(). For example: @@ -90,43 +89,31 @@ public class ErrorGroupServiceApi implements AutoCloseable { private static final PathTemplate GROUP_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}/groups/{group}"); - /** - * Formats a string containing the fully-qualified path to represent - * a group resource. - */ + /** Formats a string containing the fully-qualified path to represent a group resource. */ public static final String formatGroupName(String project, String group) { return GROUP_PATH_TEMPLATE.instantiate( "project", project, "group", group); } - /** - * Parses the project from the given fully-qualified path which - * represents a group resource. - */ + /** Parses the project from the given fully-qualified path which represents a group resource. */ public static final String parseProjectFromGroupName(String groupName) { return GROUP_PATH_TEMPLATE.parse(groupName).get("project"); } - /** - * Parses the group from the given fully-qualified path which - * represents a group resource. - */ + /** Parses the group from the given fully-qualified path which represents a group resource. */ public static final String parseGroupFromGroupName(String groupName) { return GROUP_PATH_TEMPLATE.parse(groupName).get("group"); } - /** - * Constructs an instance of ErrorGroupServiceApi with default settings. - */ + /** Constructs an instance of ErrorGroupServiceApi with default settings. */ public static final ErrorGroupServiceApi create() throws IOException { return create(ErrorGroupServiceSettings.defaultBuilder().build()); } /** - * Constructs an instance of ErrorGroupServiceApi, using the given settings. - * The channels are created based on the settings passed in, or defaults for any - * settings that are not set. + * Constructs an instance of ErrorGroupServiceApi, using the given settings. The channels are + * created based on the settings passed in, or defaults for any settings that are not set. */ public static final ErrorGroupServiceApi create(ErrorGroupServiceSettings settings) throws IOException { @@ -134,9 +121,8 @@ public static final ErrorGroupServiceApi create(ErrorGroupServiceSettings settin } /** - * Constructs an instance of ErrorGroupServiceApi, using the given settings. - * This is protected so that it easy to make a subclass, but otherwise, the static - * factory methods should be preferred. + * Constructs an instance of ErrorGroupServiceApi, using the given settings. This is protected so + * that it easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected ErrorGroupServiceApi(ErrorGroupServiceSettings settings) throws IOException { this.settings = settings; @@ -176,7 +162,8 @@ public final ErrorGroupServiceSettings getSettings() { /** * Get the specified group. * - * Sample code: + *

Sample code: + * *


    * try (ErrorGroupServiceApi errorGroupServiceApi = ErrorGroupServiceApi.create()) {
    *   String formattedGroupName = ErrorGroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
@@ -185,13 +172,11 @@ public final ErrorGroupServiceSettings getSettings() {
    * 
* * @param groupName [Required] The group resource name. Written as - * <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>. - * Call - * <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list"> - * <code>groupStats.list</code></a> to return a list of groups belonging to - * this project. - * - * Example: <code>projects/my-project-123/groups/my-group</code> + * <code>projects/<var>projectID</var>/groups/<var>group_name</var></code>. + * Call <a href="/error-reporting/reference/rest/v1beta1/projects.groupStats/list"> + * <code>groupStats.list</code></a> to return a list of groups belonging to + * this project. + *

Example: <code>projects/my-project-123/groups/my-group</code> * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final ErrorGroup getGroup(String groupName) { @@ -204,7 +189,8 @@ public final ErrorGroup getGroup(String groupName) { /** * Get the specified group. * - * Sample code: + *

Sample code: + * *


    * try (ErrorGroupServiceApi errorGroupServiceApi = ErrorGroupServiceApi.create()) {
    *   String formattedGroupName = ErrorGroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
@@ -226,7 +212,8 @@ private final ErrorGroup getGroup(GetGroupRequest request) {
   /**
    * Get the specified group.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ErrorGroupServiceApi errorGroupServiceApi = ErrorGroupServiceApi.create()) {
    *   String formattedGroupName = ErrorGroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
@@ -245,10 +232,10 @@ public final ApiCallable getGroupCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Replace the data for the specified group.
-   * Fails if the group does not exist.
+   * Replace the data for the specified group. Fails if the group does not exist.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (ErrorGroupServiceApi errorGroupServiceApi = ErrorGroupServiceApi.create()) {
    *   ErrorGroup group = ErrorGroup.newBuilder().build();
@@ -266,10 +253,10 @@ public final ErrorGroup updateGroup(ErrorGroup group) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Replace the data for the specified group.
-   * Fails if the group does not exist.
+   * Replace the data for the specified group. Fails if the group does not exist.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (ErrorGroupServiceApi errorGroupServiceApi = ErrorGroupServiceApi.create()) {
    *   ErrorGroup group = ErrorGroup.newBuilder().build();
@@ -289,10 +276,10 @@ private final ErrorGroup updateGroup(UpdateGroupRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Replace the data for the specified group.
-   * Fails if the group does not exist.
+   * Replace the data for the specified group. Fails if the group does not exist.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (ErrorGroupServiceApi errorGroupServiceApi = ErrorGroupServiceApi.create()) {
    *   ErrorGroup group = ErrorGroup.newBuilder().build();
diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceSettings.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceSettings.java
index f591c034ca78..4dc8bbeae7f1 100644
--- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceSettings.java
+++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceSettings.java
@@ -16,7 +16,6 @@
 import com.google.api.gax.core.ConnectionSettings;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
-import com.google.api.gax.grpc.PageStreamingDescriptor;
 import com.google.api.gax.grpc.ServiceApiSettings;
 import com.google.api.gax.grpc.SimpleCallSettings;
 import com.google.auth.Credentials;
@@ -43,15 +42,15 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (clouderrorreporting.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (clouderrorreporting.googleapis.com) and default port (443) are + * used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of getGroup to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of getGroup to 30 seconds: * *

  * 
@@ -65,25 +64,17 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class ErrorGroupServiceSettings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "clouderrorreporting.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -94,58 +85,42 @@ public class ErrorGroupServiceSettings extends ServiceApiSettings {
   private final SimpleCallSettings getGroupSettings;
   private final SimpleCallSettings updateGroupSettings;
 
-  /**
-   * Returns the object with the settings used for calls to getGroup.
-   */
+  /** Returns the object with the settings used for calls to getGroup. */
   public SimpleCallSettings getGroupSettings() {
     return getGroupSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to updateGroup.
-   */
+  /** Returns the object with the settings used for calls to updateGroup. */
   public SimpleCallSettings updateGroupSettings() {
     return updateGroupSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -163,9 +138,7 @@ private ErrorGroupServiceSettings(Builder settingsBuilder) throws IOException {
     updateGroupSettings = settingsBuilder.updateGroupSettings().build();
   }
 
-  /**
-   * Builder for ErrorGroupServiceSettings.
-   */
+  /** Builder for ErrorGroupServiceSettings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -289,25 +262,20 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to getGroup.
-     */
+    /** Returns the builder for the settings used for calls to getGroup. */
     public SimpleCallSettings.Builder getGroupSettings() {
       return getGroupSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to updateGroup.
-     */
+    /** Returns the builder for the settings used for calls to updateGroup. */
     public SimpleCallSettings.Builder updateGroupSettings() {
       return updateGroupSettings;
     }
diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceApi.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceApi.java
index c2a79541d076..f333c555e500 100644
--- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceApi.java
+++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceApi.java
@@ -50,28 +50,27 @@
  * 
* *

Note: close() needs to be called on the errorStatsServiceApi object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + * as threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * *

This class can be customized by passing in a custom instance of ErrorStatsServiceSettings to * create(). For example: @@ -106,33 +105,24 @@ public class ErrorStatsServiceApi implements AutoCloseable { private static final PathTemplate PROJECT_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}"); - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - */ + /** Formats a string containing the fully-qualified path to represent a project resource. */ public static final String formatProjectName(String project) { return PROJECT_PATH_TEMPLATE.instantiate("project", project); } - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - */ + /** Parses the project from the given fully-qualified path which represents a project resource. */ public static final String parseProjectFromProjectName(String projectName) { return PROJECT_PATH_TEMPLATE.parse(projectName).get("project"); } - /** - * Constructs an instance of ErrorStatsServiceApi with default settings. - */ + /** Constructs an instance of ErrorStatsServiceApi with default settings. */ public static final ErrorStatsServiceApi create() throws IOException { return create(ErrorStatsServiceSettings.defaultBuilder().build()); } /** - * Constructs an instance of ErrorStatsServiceApi, using the given settings. - * The channels are created based on the settings passed in, or defaults for any - * settings that are not set. + * Constructs an instance of ErrorStatsServiceApi, using the given settings. The channels are + * created based on the settings passed in, or defaults for any settings that are not set. */ public static final ErrorStatsServiceApi create(ErrorStatsServiceSettings settings) throws IOException { @@ -140,9 +130,8 @@ public static final ErrorStatsServiceApi create(ErrorStatsServiceSettings settin } /** - * Constructs an instance of ErrorStatsServiceApi, using the given settings. - * This is protected so that it easy to make a subclass, but otherwise, the static - * factory methods should be preferred. + * Constructs an instance of ErrorStatsServiceApi, using the given settings. This is protected so + * that it easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected ErrorStatsServiceApi(ErrorStatsServiceSettings settings) throws IOException { this.settings = settings; @@ -189,7 +178,8 @@ public final ErrorStatsServiceSettings getSettings() { /** * Lists the specified groups. * - * Sample code: + *

Sample code: + * *


    * try (ErrorStatsServiceApi errorStatsServiceApi = ErrorStatsServiceApi.create()) {
    *   String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]");
@@ -201,15 +191,13 @@ public final ErrorStatsServiceSettings getSettings() {
    * 
* * @param projectName [Required] The resource name of the Google Cloud Platform project. Written - * as <code>projects/</code> plus the - * <a href="https://support.google.com/cloud/answer/6158840">Google Cloud - * Platform project ID</a>. - * - * Example: <code>projects/my-project-123</code>. - * @param timeRange [Required] List data for the given time range. - * The service is tuned for retrieving data up to (approximately) 'now'. - * Retrieving data for arbitrary time periods in the past can result in - * higher response times or in returning incomplete results. + * as <code>projects/</code> plus the <a + * href="https://support.google.com/cloud/answer/6158840">Google Cloud Platform project + * ID</a>. + *

Example: <code>projects/my-project-123</code>. + * @param timeRange [Required] List data for the given time range. The service is tuned for + * retrieving data up to (approximately) 'now'. Retrieving data for arbitrary time periods in + * the past can result in higher response times or in returning incomplete results. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final PagedListResponse @@ -227,7 +215,8 @@ public final ErrorStatsServiceSettings getSettings() { /** * Lists the specified groups. * - * Sample code: + *

Sample code: + * *


    * try (ErrorStatsServiceApi errorStatsServiceApi = ErrorStatsServiceApi.create()) {
    *   String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]");
@@ -254,7 +243,8 @@ public final ErrorStatsServiceSettings getSettings() {
   /**
    * Lists the specified groups.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ErrorStatsServiceApi errorStatsServiceApi = ErrorStatsServiceApi.create()) {
    *   String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]");
@@ -282,7 +272,8 @@ public final ErrorStatsServiceSettings getSettings() {
   /**
    * Lists the specified groups.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ErrorStatsServiceApi errorStatsServiceApi = ErrorStatsServiceApi.create()) {
    *   String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]");
@@ -314,7 +305,8 @@ public final ApiCallable listGrou
   /**
    * Lists the specified events.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ErrorStatsServiceApi errorStatsServiceApi = ErrorStatsServiceApi.create()) {
    *   String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]");
@@ -326,9 +318,8 @@ public final ApiCallable listGrou
    * 
* * @param projectName [Required] The resource name of the Google Cloud Platform project. Written - * as `projects/` plus the - * [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). - * Example: `projects/my-project-123`. + * as `projects/` plus the [Google Cloud Platform project + * ID](https://support.google.com/cloud/answer/6158840). Example: `projects/my-project-123`. * @param groupId [Required] The group for which events shall be returned. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ @@ -344,7 +335,8 @@ public final PagedListResponseSample code: + * *

    * try (ErrorStatsServiceApi errorStatsServiceApi = ErrorStatsServiceApi.create()) {
    *   String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]");
@@ -371,7 +363,8 @@ public final PagedListResponseSample code:
+   *
    * 

    * try (ErrorStatsServiceApi errorStatsServiceApi = ErrorStatsServiceApi.create()) {
    *   String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]");
@@ -398,7 +391,8 @@ public final PagedListResponseSample code:
+   *
    * 

    * try (ErrorStatsServiceApi errorStatsServiceApi = ErrorStatsServiceApi.create()) {
    *   String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]");
@@ -430,7 +424,8 @@ public final ApiCallable listEventsCallab
   /**
    * Deletes all error events of a given project.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ErrorStatsServiceApi errorStatsServiceApi = ErrorStatsServiceApi.create()) {
    *   String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]");
@@ -439,9 +434,8 @@ public final ApiCallable listEventsCallab
    * 
* * @param projectName [Required] The resource name of the Google Cloud Platform project. Written - * as `projects/` plus the - * [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). - * Example: `projects/my-project-123`. + * as `projects/` plus the [Google Cloud Platform project + * ID](https://support.google.com/cloud/answer/6158840). Example: `projects/my-project-123`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final DeleteEventsResponse deleteEvents(String projectName) { @@ -455,7 +449,8 @@ public final DeleteEventsResponse deleteEvents(String projectName) { /** * Deletes all error events of a given project. * - * Sample code: + *

Sample code: + * *


    * try (ErrorStatsServiceApi errorStatsServiceApi = ErrorStatsServiceApi.create()) {
    *   String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]");
@@ -477,7 +472,8 @@ private final DeleteEventsResponse deleteEvents(DeleteEventsRequest request) {
   /**
    * Deletes all error events of a given project.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ErrorStatsServiceApi errorStatsServiceApi = ErrorStatsServiceApi.create()) {
    *   String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]");
diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceSettings.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceSettings.java
index e04773777a7a..b34dde3f867b 100644
--- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceSettings.java
+++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceSettings.java
@@ -14,7 +14,6 @@
 package com.google.cloud.errorreporting.spi.v1beta1;
 
 import com.google.api.gax.core.ConnectionSettings;
-import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -50,15 +49,15 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (clouderrorreporting.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (clouderrorreporting.googleapis.com) and default port (443) are + * used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of deleteEvents to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of deleteEvents to 30 seconds: * *

  * 
@@ -72,25 +71,17 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class ErrorStatsServiceSettings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "clouderrorreporting.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -105,67 +96,49 @@ public class ErrorStatsServiceSettings extends ServiceApiSettings {
       listEventsSettings;
   private final SimpleCallSettings deleteEventsSettings;
 
-  /**
-   * Returns the object with the settings used for calls to listGroupStats.
-   */
+  /** Returns the object with the settings used for calls to listGroupStats. */
   public PageStreamingCallSettings
       listGroupStatsSettings() {
     return listGroupStatsSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to listEvents.
-   */
+  /** Returns the object with the settings used for calls to listEvents. */
   public PageStreamingCallSettings
       listEventsSettings() {
     return listEventsSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to deleteEvents.
-   */
+  /** Returns the object with the settings used for calls to deleteEvents. */
   public SimpleCallSettings deleteEventsSettings() {
     return deleteEventsSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -255,9 +228,7 @@ public Iterable extractResources(ListEventsResponse payload) {
             }
           };
 
-  /**
-   * Builder for ErrorStatsServiceSettings.
-   */
+  /** Builder for ErrorStatsServiceSettings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -401,35 +372,28 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listGroupStats.
-     */
+    /** Returns the builder for the settings used for calls to listGroupStats. */
     public PageStreamingCallSettings.Builder<
             ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats>
         listGroupStatsSettings() {
       return listGroupStatsSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listEvents.
-     */
+    /** Returns the builder for the settings used for calls to listEvents. */
     public PageStreamingCallSettings.Builder
         listEventsSettings() {
       return listEventsSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to deleteEvents.
-     */
+    /** Returns the builder for the settings used for calls to deleteEvents. */
     public SimpleCallSettings.Builder
         deleteEventsSettings() {
       return deleteEventsSettings;
diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceApi.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceApi.java
index 8ecedcb0205c..cdd5714e093e 100644
--- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceApi.java
+++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceApi.java
@@ -42,29 +42,29 @@
  * 
  * 
* - *

Note: close() needs to be called on the reportErrorsServiceApi object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls + *

Note: close() needs to be called on the reportErrorsServiceApi object to clean up resources + * such as threads. In the example above, try-with-resources is used, which automatically calls * close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * *

This class can be customized by passing in a custom instance of ReportErrorsServiceSettings to * create(). For example: @@ -91,33 +91,24 @@ public class ReportErrorsServiceApi implements AutoCloseable { private static final PathTemplate PROJECT_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}"); - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - */ + /** Formats a string containing the fully-qualified path to represent a project resource. */ public static final String formatProjectName(String project) { return PROJECT_PATH_TEMPLATE.instantiate("project", project); } - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - */ + /** Parses the project from the given fully-qualified path which represents a project resource. */ public static final String parseProjectFromProjectName(String projectName) { return PROJECT_PATH_TEMPLATE.parse(projectName).get("project"); } - /** - * Constructs an instance of ReportErrorsServiceApi with default settings. - */ + /** Constructs an instance of ReportErrorsServiceApi with default settings. */ public static final ReportErrorsServiceApi create() throws IOException { return create(ReportErrorsServiceSettings.defaultBuilder().build()); } /** - * Constructs an instance of ReportErrorsServiceApi, using the given settings. - * The channels are created based on the settings passed in, or defaults for any - * settings that are not set. + * Constructs an instance of ReportErrorsServiceApi, using the given settings. The channels are + * created based on the settings passed in, or defaults for any settings that are not set. */ public static final ReportErrorsServiceApi create(ReportErrorsServiceSettings settings) throws IOException { @@ -125,9 +116,9 @@ public static final ReportErrorsServiceApi create(ReportErrorsServiceSettings se } /** - * Constructs an instance of ReportErrorsServiceApi, using the given settings. - * This is protected so that it easy to make a subclass, but otherwise, the static - * factory methods should be preferred. + * Constructs an instance of ReportErrorsServiceApi, using the given settings. This is protected + * so that it easy to make a subclass, but otherwise, the static factory methods should be + * preferred. */ protected ReportErrorsServiceApi(ReportErrorsServiceSettings settings) throws IOException { this.settings = settings; @@ -165,14 +156,15 @@ public final ReportErrorsServiceSettings getSettings() { /** * Report an individual error event. * - * This endpoint accepts <strong>either</strong> an OAuth token, - * <strong>or</strong> an - * <a href="https://support.google.com/cloud/answer/6158862">API key</a> - * for authentication. To use an API key, append it to the URL as the value of - * a `key` parameter. For example: - * <pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre> + *

This endpoint accepts <strong>either</strong> an OAuth token, + * <strong>or</strong> an <a + * href="https://support.google.com/cloud/answer/6158862">API key</a> for authentication. + * To use an API key, append it to the URL as the value of a `key` parameter. For example: + * <pre>POST + * https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre> + * + *

Sample code: * - * Sample code: *


    * try (ReportErrorsServiceApi reportErrorsServiceApi = ReportErrorsServiceApi.create()) {
    *   String formattedProjectName = ReportErrorsServiceApi.formatProjectName("[PROJECT]");
@@ -182,9 +174,8 @@ public final ReportErrorsServiceSettings getSettings() {
    * 
* * @param projectName [Required] The resource name of the Google Cloud Platform project. Written - * as `projects/` plus the - * [Google Cloud Platform project ID](https://support.google.com/cloud/answer/6158840). - * Example: `projects/my-project-123`. + * as `projects/` plus the [Google Cloud Platform project + * ID](https://support.google.com/cloud/answer/6158840). Example: `projects/my-project-123`. * @param event [Required] The error event to be reported. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ @@ -200,14 +191,15 @@ public final ReportErrorEventResponse reportErrorEvent( /** * Report an individual error event. * - * This endpoint accepts <strong>either</strong> an OAuth token, - * <strong>or</strong> an - * <a href="https://support.google.com/cloud/answer/6158862">API key</a> - * for authentication. To use an API key, append it to the URL as the value of - * a `key` parameter. For example: - * <pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre> + *

This endpoint accepts <strong>either</strong> an OAuth token, + * <strong>or</strong> an <a + * href="https://support.google.com/cloud/answer/6158862">API key</a> for authentication. + * To use an API key, append it to the URL as the value of a `key` parameter. For example: + * <pre>POST + * https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre> + * + *

Sample code: * - * Sample code: *


    * try (ReportErrorsServiceApi reportErrorsServiceApi = ReportErrorsServiceApi.create()) {
    *   String formattedProjectName = ReportErrorsServiceApi.formatProjectName("[PROJECT]");
@@ -231,14 +223,15 @@ public final ReportErrorEventResponse reportErrorEvent(ReportErrorEventRequest r
   /**
    * Report an individual error event.
    *
-   * This endpoint accepts <strong>either</strong> an OAuth token,
-   * <strong>or</strong> an
-   * <a href="https://support.google.com/cloud/answer/6158862">API key</a>
-   * for authentication. To use an API key, append it to the URL as the value of
-   * a `key` parameter. For example:
-   * <pre>POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre>
+   * 

This endpoint accepts <strong>either</strong> an OAuth token, + * <strong>or</strong> an <a + * href="https://support.google.com/cloud/answer/6158862">API key</a> for authentication. + * To use an API key, append it to the URL as the value of a `key` parameter. For example: + * <pre>POST + * https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456</pre> + * + *

Sample code: * - * Sample code: *


    * try (ReportErrorsServiceApi reportErrorsServiceApi = ReportErrorsServiceApi.create()) {
    *   String formattedProjectName = ReportErrorsServiceApi.formatProjectName("[PROJECT]");
diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceSettings.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceSettings.java
index a61c66655385..a4b390017c31 100644
--- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceSettings.java
+++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceSettings.java
@@ -16,7 +16,6 @@
 import com.google.api.gax.core.ConnectionSettings;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
-import com.google.api.gax.grpc.PageStreamingDescriptor;
 import com.google.api.gax.grpc.ServiceApiSettings;
 import com.google.api.gax.grpc.SimpleCallSettings;
 import com.google.auth.Credentials;
@@ -42,15 +41,15 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (clouderrorreporting.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (clouderrorreporting.googleapis.com) and default port (443) are + * used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of reportErrorEvent to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of reportErrorEvent to 30 seconds: * *

  * 
@@ -64,25 +63,17 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class ReportErrorsServiceSettings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "clouderrorreporting.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -93,52 +84,38 @@ public class ReportErrorsServiceSettings extends ServiceApiSettings {
   private final SimpleCallSettings
       reportErrorEventSettings;
 
-  /**
-   * Returns the object with the settings used for calls to reportErrorEvent.
-   */
+  /** Returns the object with the settings used for calls to reportErrorEvent. */
   public SimpleCallSettings
       reportErrorEventSettings() {
     return reportErrorEventSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -155,9 +132,7 @@ private ReportErrorsServiceSettings(Builder settingsBuilder) throws IOException
     reportErrorEventSettings = settingsBuilder.reportErrorEventSettings().build();
   }
 
-  /**
-   * Builder for ReportErrorsServiceSettings.
-   */
+  /** Builder for ReportErrorsServiceSettings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -271,18 +246,15 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to reportErrorEvent.
-     */
+    /** Returns the builder for the settings used for calls to reportErrorEvent. */
     public SimpleCallSettings.Builder
         reportErrorEventSettings() {
       return reportErrorEventSettings;
diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/package-info.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/package-info.java
index 84d05a4d0496..15a1f4bf3564 100644
--- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/package-info.java
+++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/package-info.java
@@ -15,15 +15,14 @@
 /**
  * A client to Stackdriver Error Reporting API.
  *
- * The interfaces provided are listed below, along with a usage sample
+ * 

The interfaces provided are listed below, along with a usage sample * - * ==================== - * ErrorGroupServiceApi - * ==================== + *

==================== ErrorGroupServiceApi ==================== * - * Service Description: Service for retrieving and updating individual error groups. + *

Service Description: Service for retrieving and updating individual error groups. + * + *

Sample for ErrorGroupServiceApi: * - * Sample for ErrorGroupServiceApi: *

  * 
  * try (ErrorGroupServiceApi errorGroupServiceApi = ErrorGroupServiceApi.create()) {
@@ -33,14 +32,13 @@
  * 
  * 
* - * ==================== - * ErrorStatsServiceApi - * ==================== + * ==================== ErrorStatsServiceApi ==================== * - * Service Description: An API for retrieving and managing error statistics as well as data for + *

Service Description: An API for retrieving and managing error statistics as well as data for * individual events. * - * Sample for ErrorStatsServiceApi: + *

Sample for ErrorStatsServiceApi: + * *

  * 
  * try (ErrorStatsServiceApi errorStatsServiceApi = ErrorStatsServiceApi.create()) {
@@ -50,13 +48,12 @@
  * 
  * 
* - * ====================== - * ReportErrorsServiceApi - * ====================== + * ====================== ReportErrorsServiceApi ====================== * - * Service Description: An API for reporting error events. + *

Service Description: An API for reporting error events. + * + *

Sample for ReportErrorsServiceApi: * - * Sample for ReportErrorsServiceApi: *

  * 
  * try (ReportErrorsServiceApi reportErrorsServiceApi = ReportErrorsServiceApi.create()) {
@@ -66,6 +63,5 @@
  * }
  * 
  * 
- * */ package com.google.cloud.errorreporting.spi.v1beta1; diff --git a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceTest.java b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceTest.java index 7ef1423e0800..1a176a4adfa6 100644 --- a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceTest.java +++ b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceTest.java @@ -14,10 +14,8 @@ package com.google.cloud.errorreporting.spi.v1beta1; -import com.google.api.gax.core.PagedListResponse; import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; -import com.google.common.collect.Lists; import com.google.devtools.clouderrorreporting.v1beta1.ErrorGroup; import com.google.devtools.clouderrorreporting.v1beta1.GetGroupRequest; import com.google.devtools.clouderrorreporting.v1beta1.UpdateGroupRequest; diff --git a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceTest.java b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceTest.java index ff909ae74914..5149d16a357c 100644 --- a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceTest.java +++ b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceTest.java @@ -14,10 +14,8 @@ package com.google.cloud.errorreporting.spi.v1beta1; -import com.google.api.gax.core.PagedListResponse; import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; -import com.google.common.collect.Lists; import com.google.devtools.clouderrorreporting.v1beta1.ReportErrorEventRequest; import com.google.devtools.clouderrorreporting.v1beta1.ReportErrorEventResponse; import com.google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent; diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceApi.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceApi.java index d47133cf5af3..1f663b9929f6 100644 --- a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceApi.java +++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceApi.java @@ -14,7 +14,6 @@ package com.google.cloud.language.spi.v1beta1; import com.google.api.gax.grpc.ApiCallable; -import com.google.api.gax.protobuf.PathTemplate; import com.google.cloud.language.v1beta1.AnalyzeEntitiesRequest; import com.google.cloud.language.v1beta1.AnalyzeEntitiesResponse; import com.google.cloud.language.v1beta1.AnalyzeSentimentRequest; @@ -49,28 +48,27 @@ *
* *

Note: close() needs to be called on the languageServiceApi object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + * as threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * *

This class can be customized by passing in a custom instance of LanguageServiceSettings to * create(). For example: @@ -97,17 +95,14 @@ public class LanguageServiceApi implements AutoCloseable { analyzeEntitiesCallable; private final ApiCallable annotateTextCallable; - /** - * Constructs an instance of LanguageServiceApi with default settings. - */ + /** Constructs an instance of LanguageServiceApi with default settings. */ public static final LanguageServiceApi create() throws IOException { return create(LanguageServiceSettings.defaultBuilder().build()); } /** - * Constructs an instance of LanguageServiceApi, using the given settings. - * The channels are created based on the settings passed in, or defaults for any - * settings that are not set. + * Constructs an instance of LanguageServiceApi, using the given settings. The channels are + * created based on the settings passed in, or defaults for any settings that are not set. */ public static final LanguageServiceApi create(LanguageServiceSettings settings) throws IOException { @@ -115,9 +110,8 @@ public static final LanguageServiceApi create(LanguageServiceSettings settings) } /** - * Constructs an instance of LanguageServiceApi, using the given settings. - * This is protected so that it easy to make a subclass, but otherwise, the static - * factory methods should be preferred. + * Constructs an instance of LanguageServiceApi, using the given settings. This is protected so + * that it easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected LanguageServiceApi(LanguageServiceSettings settings) throws IOException { this.settings = settings; @@ -159,7 +153,8 @@ public final LanguageServiceSettings getSettings() { /** * Analyzes the sentiment of the provided text. * - * Sample code: + *

Sample code: + * *


    * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
    *   Document document = Document.newBuilder().build();
@@ -168,7 +163,7 @@ public final LanguageServiceSettings getSettings() {
    * 
* * @param document Input document. Currently, `analyzeSentiment` only supports English text - * ([Document.language][google.cloud.language.v1beta1.Document.language]="EN"). + * ([Document.language][google.cloud.language.v1beta1.Document.language]="EN"). * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final AnalyzeSentimentResponse analyzeSentiment(Document document) { @@ -181,7 +176,8 @@ public final AnalyzeSentimentResponse analyzeSentiment(Document document) { /** * Analyzes the sentiment of the provided text. * - * Sample code: + *

Sample code: + * *


    * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
    *   Document document = Document.newBuilder().build();
@@ -203,7 +199,8 @@ private final AnalyzeSentimentResponse analyzeSentiment(AnalyzeSentimentRequest
   /**
    * Analyzes the sentiment of the provided text.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
    *   Document document = Document.newBuilder().build();
@@ -223,10 +220,11 @@ private final AnalyzeSentimentResponse analyzeSentiment(AnalyzeSentimentRequest
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Finds named entities (currently finds proper names) in the text,
-   * entity types, salience, mentions for each entity, and other properties.
+   * Finds named entities (currently finds proper names) in the text, entity types, salience,
+   * mentions for each entity, and other properties.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
    *   Document document = Document.newBuilder().build();
@@ -251,10 +249,11 @@ public final AnalyzeEntitiesResponse analyzeEntities(
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Finds named entities (currently finds proper names) in the text,
-   * entity types, salience, mentions for each entity, and other properties.
+   * Finds named entities (currently finds proper names) in the text, entity types, salience,
+   * mentions for each entity, and other properties.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
    *   Document document = Document.newBuilder().build();
@@ -276,10 +275,11 @@ public final AnalyzeEntitiesResponse analyzeEntities(AnalyzeEntitiesRequest requ
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Finds named entities (currently finds proper names) in the text,
-   * entity types, salience, mentions for each entity, and other properties.
+   * Finds named entities (currently finds proper names) in the text, entity types, salience,
+   * mentions for each entity, and other properties.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
    *   Document document = Document.newBuilder().build();
@@ -301,12 +301,12 @@ public final AnalyzeEntitiesResponse analyzeEntities(AnalyzeEntitiesRequest requ
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Advanced API that analyzes the document and provides a full set of text
-   * annotations, including semantic, syntactic, and sentiment information. This
-   * API is intended for users who are familiar with machine learning and need
-   * in-depth text features to build upon.
+   * Advanced API that analyzes the document and provides a full set of text annotations, including
+   * semantic, syntactic, and sentiment information. This API is intended for users who are familiar
+   * with machine learning and need in-depth text features to build upon.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
    *   Document document = Document.newBuilder().build();
@@ -334,12 +334,12 @@ public final AnnotateTextResponse annotateText(
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Advanced API that analyzes the document and provides a full set of text
-   * annotations, including semantic, syntactic, and sentiment information. This
-   * API is intended for users who are familiar with machine learning and need
-   * in-depth text features to build upon.
+   * Advanced API that analyzes the document and provides a full set of text annotations, including
+   * semantic, syntactic, and sentiment information. This API is intended for users who are familiar
+   * with machine learning and need in-depth text features to build upon.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
    *   Document document = Document.newBuilder().build();
@@ -363,12 +363,12 @@ public final AnnotateTextResponse annotateText(AnnotateTextRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Advanced API that analyzes the document and provides a full set of text
-   * annotations, including semantic, syntactic, and sentiment information. This
-   * API is intended for users who are familiar with machine learning and need
-   * in-depth text features to build upon.
+   * Advanced API that analyzes the document and provides a full set of text annotations, including
+   * semantic, syntactic, and sentiment information. This API is intended for users who are familiar
+   * with machine learning and need in-depth text features to build upon.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
    *   Document document = Document.newBuilder().build();
diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceSettings.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceSettings.java
index de0a26308a09..394c2a7add5e 100644
--- a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceSettings.java
+++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceSettings.java
@@ -16,7 +16,6 @@
 import com.google.api.gax.core.ConnectionSettings;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
-import com.google.api.gax.grpc.PageStreamingDescriptor;
 import com.google.api.gax.grpc.ServiceApiSettings;
 import com.google.api.gax.grpc.SimpleCallSettings;
 import com.google.auth.Credentials;
@@ -46,15 +45,14 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (language.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (language.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of analyzeSentiment to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of analyzeSentiment to 30 seconds: * *

  * 
@@ -68,25 +66,17 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class LanguageServiceSettings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "language.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -100,67 +90,49 @@ public class LanguageServiceSettings extends ServiceApiSettings {
       analyzeEntitiesSettings;
   private final SimpleCallSettings annotateTextSettings;
 
-  /**
-   * Returns the object with the settings used for calls to analyzeSentiment.
-   */
+  /** Returns the object with the settings used for calls to analyzeSentiment. */
   public SimpleCallSettings
       analyzeSentimentSettings() {
     return analyzeSentimentSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to analyzeEntities.
-   */
+  /** Returns the object with the settings used for calls to analyzeEntities. */
   public SimpleCallSettings
       analyzeEntitiesSettings() {
     return analyzeEntitiesSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to annotateText.
-   */
+  /** Returns the object with the settings used for calls to annotateText. */
   public SimpleCallSettings annotateTextSettings() {
     return annotateTextSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -179,9 +151,7 @@ private LanguageServiceSettings(Builder settingsBuilder) throws IOException {
     annotateTextSettings = settingsBuilder.annotateTextSettings().build();
   }
 
-  /**
-   * Builder for LanguageServiceSettings.
-   */
+  /** Builder for LanguageServiceSettings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -321,34 +291,27 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to analyzeSentiment.
-     */
+    /** Returns the builder for the settings used for calls to analyzeSentiment. */
     public SimpleCallSettings.Builder
         analyzeSentimentSettings() {
       return analyzeSentimentSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to analyzeEntities.
-     */
+    /** Returns the builder for the settings used for calls to analyzeEntities. */
     public SimpleCallSettings.Builder
         analyzeEntitiesSettings() {
       return analyzeEntitiesSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to annotateText.
-     */
+    /** Returns the builder for the settings used for calls to annotateText. */
     public SimpleCallSettings.Builder
         annotateTextSettings() {
       return annotateTextSettings;
diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/package-info.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/package-info.java
index 07c5cc884e39..9adb4a848362 100644
--- a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/package-info.java
+++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/package-info.java
@@ -15,16 +15,15 @@
 /**
  * A client to Google Cloud Natural Language API.
  *
- * The interfaces provided are listed below, along with a usage sample
+ * 

The interfaces provided are listed below, along with a usage sample * - * ================== - * LanguageServiceApi - * ================== + *

================== LanguageServiceApi ================== * - * Service Description: Provides text analysis operations such as sentiment analysis and entity + *

Service Description: Provides text analysis operations such as sentiment analysis and entity * recognition. * - * Sample for LanguageServiceApi: + *

Sample for LanguageServiceApi: + * *

  * 
  * try (LanguageServiceApi languageServiceApi = LanguageServiceApi.create()) {
@@ -33,6 +32,5 @@
  * }
  * 
  * 
- * */ package com.google.cloud.language.spi.v1beta1; diff --git a/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta1/LanguageServiceTest.java b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta1/LanguageServiceTest.java index 962cba6419fc..d9765d9ed8a2 100644 --- a/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta1/LanguageServiceTest.java +++ b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta1/LanguageServiceTest.java @@ -14,7 +14,6 @@ package com.google.cloud.language.spi.v1beta1; -import com.google.api.gax.core.PagedListResponse; import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; import com.google.cloud.language.v1beta1.AnalyzeEntitiesRequest; @@ -26,7 +25,6 @@ import com.google.cloud.language.v1beta1.AnnotateTextResponse; import com.google.cloud.language.v1beta1.Document; import com.google.cloud.language.v1beta1.EncodingType; -import com.google.common.collect.Lists; import com.google.protobuf.GeneratedMessageV3; import java.io.IOException; import java.util.ArrayList; diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Api.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Api.java index 6172bac44b91..f49aca494e33 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Api.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Api.java @@ -49,28 +49,27 @@ *
* *

Note: close() needs to be called on the configServiceV2Api object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + * as threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * *

This class can be customized by passing in a custom instance of ConfigServiceV2Settings to * create(). For example: @@ -106,59 +105,41 @@ public class ConfigServiceV2Api implements AutoCloseable { private static final PathTemplate SINK_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}/sinks/{sink}"); - /** - * Formats a string containing the fully-qualified path to represent - * a parent resource. - */ + /** Formats a string containing the fully-qualified path to represent a parent resource. */ public static final String formatParentName(String project) { return PARENT_PATH_TEMPLATE.instantiate("project", project); } - /** - * Formats a string containing the fully-qualified path to represent - * a sink resource. - */ + /** Formats a string containing the fully-qualified path to represent a sink resource. */ public static final String formatSinkName(String project, String sink) { return SINK_PATH_TEMPLATE.instantiate( "project", project, "sink", sink); } - /** - * Parses the project from the given fully-qualified path which - * represents a parent resource. - */ + /** Parses the project from the given fully-qualified path which represents a parent resource. */ public static final String parseProjectFromParentName(String parentName) { return PARENT_PATH_TEMPLATE.parse(parentName).get("project"); } - /** - * Parses the project from the given fully-qualified path which - * represents a sink resource. - */ + /** Parses the project from the given fully-qualified path which represents a sink resource. */ public static final String parseProjectFromSinkName(String sinkName) { return SINK_PATH_TEMPLATE.parse(sinkName).get("project"); } - /** - * Parses the sink from the given fully-qualified path which - * represents a sink resource. - */ + /** Parses the sink from the given fully-qualified path which represents a sink resource. */ public static final String parseSinkFromSinkName(String sinkName) { return SINK_PATH_TEMPLATE.parse(sinkName).get("sink"); } - /** - * Constructs an instance of ConfigServiceV2Api with default settings. - */ + /** Constructs an instance of ConfigServiceV2Api with default settings. */ public static final ConfigServiceV2Api create() throws IOException { return create(ConfigServiceV2Settings.defaultBuilder().build()); } /** - * Constructs an instance of ConfigServiceV2Api, using the given settings. - * The channels are created based on the settings passed in, or defaults for any - * settings that are not set. + * Constructs an instance of ConfigServiceV2Api, using the given settings. The channels are + * created based on the settings passed in, or defaults for any settings that are not set. */ public static final ConfigServiceV2Api create(ConfigServiceV2Settings settings) throws IOException { @@ -166,9 +147,8 @@ public static final ConfigServiceV2Api create(ConfigServiceV2Settings settings) } /** - * Constructs an instance of ConfigServiceV2Api, using the given settings. - * This is protected so that it easy to make a subclass, but otherwise, the static - * factory methods should be preferred. + * Constructs an instance of ConfigServiceV2Api, using the given settings. This is protected so + * that it easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected ConfigServiceV2Api(ConfigServiceV2Settings settings) throws IOException { this.settings = settings; @@ -216,7 +196,8 @@ public final ConfigServiceV2Settings getSettings() { /** * Lists sinks. * - * Sample code: + *

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedParent = ConfigServiceV2Api.formatParentName("[PROJECT]");
@@ -226,8 +207,8 @@ public final ConfigServiceV2Settings getSettings() {
    * }
    * 
* - * @param parent Required. The resource name containing the sinks. - * Example: `"projects/my-logging-project"`. + * @param parent Required. The resource name containing the sinks. Example: + * `"projects/my-logging-project"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final PagedListResponse listSinks( @@ -241,7 +222,8 @@ public final PagedListResponse lis /** * Lists sinks. * - * Sample code: + *

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedParent = ConfigServiceV2Api.formatParentName("[PROJECT]");
@@ -266,7 +248,8 @@ public final PagedListResponse lis
   /**
    * Lists sinks.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedParent = ConfigServiceV2Api.formatParentName("[PROJECT]");
@@ -291,7 +274,8 @@ public final PagedListResponse lis
   /**
    * Lists sinks.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedParent = ConfigServiceV2Api.formatParentName("[PROJECT]");
@@ -321,7 +305,8 @@ public final ApiCallable listSinksCallable(
   /**
    * Gets a sink.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedSinkName = ConfigServiceV2Api.formatSinkName("[PROJECT]", "[SINK]");
@@ -329,8 +314,8 @@ public final ApiCallable listSinksCallable(
    * }
    * 
* - * @param sinkName The resource name of the sink to return. - * Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @param sinkName The resource name of the sink to return. Example: + * `"projects/my-project-id/sinks/my-sink-id"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final LogSink getSink(String sinkName) { @@ -343,7 +328,8 @@ public final LogSink getSink(String sinkName) { /** * Gets a sink. * - * Sample code: + *

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedSinkName = ConfigServiceV2Api.formatSinkName("[PROJECT]", "[SINK]");
@@ -365,7 +351,8 @@ private final LogSink getSink(GetSinkRequest request) {
   /**
    * Gets a sink.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedSinkName = ConfigServiceV2Api.formatSinkName("[PROJECT]", "[SINK]");
@@ -386,7 +373,8 @@ public final ApiCallable getSinkCallable() {
   /**
    * Creates a sink.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedParent = ConfigServiceV2Api.formatParentName("[PROJECT]");
@@ -395,12 +383,9 @@ public final ApiCallable getSinkCallable() {
    * }
    * 
* - * @param parent The resource in which to create the sink. - * Example: `"projects/my-project-id"`. - * - * The new sink must be provided in the request. - * @param sink The new sink, which must not have an identifier that already - * exists. + * @param parent The resource in which to create the sink. Example: `"projects/my-project-id"`. + *

The new sink must be provided in the request. + * @param sink The new sink, which must not have an identifier that already exists. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final LogSink createSink(String parent, LogSink sink) { @@ -414,7 +399,8 @@ public final LogSink createSink(String parent, LogSink sink) { /** * Creates a sink. * - * Sample code: + *

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedParent = ConfigServiceV2Api.formatParentName("[PROJECT]");
@@ -438,7 +424,8 @@ public final LogSink createSink(CreateSinkRequest request) {
   /**
    * Creates a sink.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedParent = ConfigServiceV2Api.formatParentName("[PROJECT]");
@@ -461,7 +448,8 @@ public final ApiCallable createSinkCallable() {
   /**
    * Creates or updates a sink.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedSinkName = ConfigServiceV2Api.formatSinkName("[PROJECT]", "[SINK]");
@@ -470,15 +458,12 @@ public final ApiCallable createSinkCallable() {
    * }
    * 
* - * @param sinkName The resource name of the sink to update. - * Example: `"projects/my-project-id/sinks/my-sink-id"`. - * - * The updated sink must be provided in the request and have the - * same name that is specified in `sinkName`. If the sink does not - * exist, it is created. - * @param sink The updated sink, whose name must be the same as the sink - * identifier in `sinkName`. If `sinkName` does not exist, then - * this method creates a new sink. + * @param sinkName The resource name of the sink to update. Example: + * `"projects/my-project-id/sinks/my-sink-id"`. + *

The updated sink must be provided in the request and have the same name that is + * specified in `sinkName`. If the sink does not exist, it is created. + * @param sink The updated sink, whose name must be the same as the sink identifier in `sinkName`. + * If `sinkName` does not exist, then this method creates a new sink. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final LogSink updateSink(String sinkName, LogSink sink) { @@ -492,7 +477,8 @@ public final LogSink updateSink(String sinkName, LogSink sink) { /** * Creates or updates a sink. * - * Sample code: + *

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedSinkName = ConfigServiceV2Api.formatSinkName("[PROJECT]", "[SINK]");
@@ -516,7 +502,8 @@ public final LogSink updateSink(UpdateSinkRequest request) {
   /**
    * Creates or updates a sink.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedSinkName = ConfigServiceV2Api.formatSinkName("[PROJECT]", "[SINK]");
@@ -539,7 +526,8 @@ public final ApiCallable updateSinkCallable() {
   /**
    * Deletes a sink.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedSinkName = ConfigServiceV2Api.formatSinkName("[PROJECT]", "[SINK]");
@@ -547,8 +535,8 @@ public final ApiCallable updateSinkCallable() {
    * }
    * 
* - * @param sinkName The resource name of the sink to delete. - * Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @param sinkName The resource name of the sink to delete. Example: + * `"projects/my-project-id/sinks/my-sink-id"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final void deleteSink(String sinkName) { @@ -561,7 +549,8 @@ public final void deleteSink(String sinkName) { /** * Deletes a sink. * - * Sample code: + *

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedSinkName = ConfigServiceV2Api.formatSinkName("[PROJECT]", "[SINK]");
@@ -583,7 +572,8 @@ private final void deleteSink(DeleteSinkRequest request) {
   /**
    * Deletes a sink.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
    *   String formattedSinkName = ConfigServiceV2Api.formatSinkName("[PROJECT]", "[SINK]");
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Settings.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Settings.java
index 82273360d909..f44dddab6743 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Settings.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Settings.java
@@ -14,7 +14,6 @@
 package com.google.cloud.logging.spi.v2;
 
 import com.google.api.gax.core.ConnectionSettings;
-import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -50,15 +49,14 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (logging.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (logging.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of getSink to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of getSink to 30 seconds: * *

  * 
@@ -72,19 +70,13 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class ConfigServiceV2Settings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "logging.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder()
           .add("https://www.googleapis.com/auth/cloud-platform")
@@ -94,9 +86,7 @@ public class ConfigServiceV2Settings extends ServiceApiSettings {
           .add("https://www.googleapis.com/auth/logging.write")
           .build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -111,80 +101,58 @@ public class ConfigServiceV2Settings extends ServiceApiSettings {
   private final SimpleCallSettings updateSinkSettings;
   private final SimpleCallSettings deleteSinkSettings;
 
-  /**
-   * Returns the object with the settings used for calls to listSinks.
-   */
+  /** Returns the object with the settings used for calls to listSinks. */
   public PageStreamingCallSettings
       listSinksSettings() {
     return listSinksSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to getSink.
-   */
+  /** Returns the object with the settings used for calls to getSink. */
   public SimpleCallSettings getSinkSettings() {
     return getSinkSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to createSink.
-   */
+  /** Returns the object with the settings used for calls to createSink. */
   public SimpleCallSettings createSinkSettings() {
     return createSinkSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to updateSink.
-   */
+  /** Returns the object with the settings used for calls to updateSink. */
   public SimpleCallSettings updateSinkSettings() {
     return updateSinkSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to deleteSink.
-   */
+  /** Returns the object with the settings used for calls to deleteSink. */
   public SimpleCallSettings deleteSinkSettings() {
     return deleteSinkSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -239,9 +207,7 @@ public Iterable extractResources(ListSinksResponse payload) {
             }
           };
 
-  /**
-   * Builder for ConfigServiceV2Settings.
-   */
+  /** Builder for ConfigServiceV2Settings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -404,47 +370,36 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listSinks.
-     */
+    /** Returns the builder for the settings used for calls to listSinks. */
     public PageStreamingCallSettings.Builder
         listSinksSettings() {
       return listSinksSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to getSink.
-     */
+    /** Returns the builder for the settings used for calls to getSink. */
     public SimpleCallSettings.Builder getSinkSettings() {
       return getSinkSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to createSink.
-     */
+    /** Returns the builder for the settings used for calls to createSink. */
     public SimpleCallSettings.Builder createSinkSettings() {
       return createSinkSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to updateSink.
-     */
+    /** Returns the builder for the settings used for calls to updateSink. */
     public SimpleCallSettings.Builder updateSinkSettings() {
       return updateSinkSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to deleteSink.
-     */
+    /** Returns the builder for the settings used for calls to deleteSink. */
     public SimpleCallSettings.Builder deleteSinkSettings() {
       return deleteSinkSettings;
     }
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Api.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Api.java
index 712ca4ed21cc..0200b82f7d2a 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Api.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Api.java
@@ -52,28 +52,27 @@
  * 
* *

Note: close() needs to be called on the loggingServiceV2Api object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + * as threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * *

This class can be customized by passing in a custom instance of LoggingServiceV2Settings to * create(). For example: @@ -118,59 +117,41 @@ public class LoggingServiceV2Api implements AutoCloseable { private static final PathTemplate LOG_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}/logs/{log}"); - /** - * Formats a string containing the fully-qualified path to represent - * a parent resource. - */ + /** Formats a string containing the fully-qualified path to represent a parent resource. */ public static final String formatParentName(String project) { return PARENT_PATH_TEMPLATE.instantiate("project", project); } - /** - * Formats a string containing the fully-qualified path to represent - * a log resource. - */ + /** Formats a string containing the fully-qualified path to represent a log resource. */ public static final String formatLogName(String project, String log) { return LOG_PATH_TEMPLATE.instantiate( "project", project, "log", log); } - /** - * Parses the project from the given fully-qualified path which - * represents a parent resource. - */ + /** Parses the project from the given fully-qualified path which represents a parent resource. */ public static final String parseProjectFromParentName(String parentName) { return PARENT_PATH_TEMPLATE.parse(parentName).get("project"); } - /** - * Parses the project from the given fully-qualified path which - * represents a log resource. - */ + /** Parses the project from the given fully-qualified path which represents a log resource. */ public static final String parseProjectFromLogName(String logName) { return LOG_PATH_TEMPLATE.parse(logName).get("project"); } - /** - * Parses the log from the given fully-qualified path which - * represents a log resource. - */ + /** Parses the log from the given fully-qualified path which represents a log resource. */ public static final String parseLogFromLogName(String logName) { return LOG_PATH_TEMPLATE.parse(logName).get("log"); } - /** - * Constructs an instance of LoggingServiceV2Api with default settings. - */ + /** Constructs an instance of LoggingServiceV2Api with default settings. */ public static final LoggingServiceV2Api create() throws IOException { return create(LoggingServiceV2Settings.defaultBuilder().build()); } /** - * Constructs an instance of LoggingServiceV2Api, using the given settings. - * The channels are created based on the settings passed in, or defaults for any - * settings that are not set. + * Constructs an instance of LoggingServiceV2Api, using the given settings. The channels are + * created based on the settings passed in, or defaults for any settings that are not set. */ public static final LoggingServiceV2Api create(LoggingServiceV2Settings settings) throws IOException { @@ -178,9 +159,8 @@ public static final LoggingServiceV2Api create(LoggingServiceV2Settings settings } /** - * Constructs an instance of LoggingServiceV2Api, using the given settings. - * This is protected so that it easy to make a subclass, but otherwise, the static - * factory methods should be preferred. + * Constructs an instance of LoggingServiceV2Api, using the given settings. This is protected so + * that it easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected LoggingServiceV2Api(LoggingServiceV2Settings settings) throws IOException { this.settings = settings; @@ -229,10 +209,10 @@ public final LoggingServiceV2Settings getSettings() { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Deletes a log and all its log entries. - * The log will reappear if it receives new entries. + * Deletes a log and all its log entries. The log will reappear if it receives new entries. + * + *

Sample code: * - * Sample code: *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   String formattedLogName = LoggingServiceV2Api.formatLogName("[PROJECT]", "[LOG]");
@@ -240,8 +220,8 @@ public final LoggingServiceV2Settings getSettings() {
    * }
    * 
* - * @param logName Required. The resource name of the log to delete. Example: - * `"projects/my-project/logs/syslog"`. + * @param logName Required. The resource name of the log to delete. Example: + * `"projects/my-project/logs/syslog"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final void deleteLog(String logName) { @@ -252,10 +232,10 @@ public final void deleteLog(String logName) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Deletes a log and all its log entries. - * The log will reappear if it receives new entries. + * Deletes a log and all its log entries. The log will reappear if it receives new entries. + * + *

Sample code: * - * Sample code: *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   String formattedLogName = LoggingServiceV2Api.formatLogName("[PROJECT]", "[LOG]");
@@ -275,10 +255,10 @@ private final void deleteLog(DeleteLogRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Deletes a log and all its log entries.
-   * The log will reappear if it receives new entries.
+   * Deletes a log and all its log entries. The log will reappear if it receives new entries.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   String formattedLogName = LoggingServiceV2Api.formatLogName("[PROJECT]", "[LOG]");
@@ -297,10 +277,10 @@ public final ApiCallable deleteLogCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Writes log entries to Stackdriver Logging.  All log entries are
-   * written by this method.
+   * Writes log entries to Stackdriver Logging. All log entries are written by this method.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   String formattedLogName = LoggingServiceV2Api.formatLogName("[PROJECT]", "[LOG]");
@@ -311,22 +291,19 @@ public final ApiCallable deleteLogCallable() {
    * }
    * 
* - * @param logName Optional. A default log resource name for those log entries in `entries` - * that do not specify their own `logName`. Example: - * `"projects/my-project/logs/syslog"`. See - * [LogEntry][google.logging.v2.LogEntry]. - * @param resource Optional. A default monitored resource for those log entries in `entries` - * that do not specify their own `resource`. - * @param labels Optional. User-defined `key:value` items that are added to - * the `labels` field of each log entry in `entries`, except when a log - * entry specifies its own `key:value` item with the same key. - * Example: `{ "size": "large", "color":"red" }` - * @param entries Required. The log entries to write. The log entries must have values for - * all required fields. - * - * To improve throughput and to avoid exceeding the quota limit for calls - * to `entries.write`, use this field to write multiple log entries at once - * rather than // calling this method for each log entry. + * @param logName Optional. A default log resource name for those log entries in `entries` that do + * not specify their own `logName`. Example: `"projects/my-project/logs/syslog"`. See + * [LogEntry][google.logging.v2.LogEntry]. + * @param resource Optional. A default monitored resource for those log entries in `entries` that + * do not specify their own `resource`. + * @param labels Optional. User-defined `key:value` items that are added to the `labels` field of + * each log entry in `entries`, except when a log entry specifies its own `key:value` item + * with the same key. Example: `{ "size": "large", "color":"red" }` + * @param entries Required. The log entries to write. The log entries must have values for all + * required fields. + *

To improve throughput and to avoid exceeding the quota limit for calls to + * `entries.write`, use this field to write multiple log entries at once rather than // + * calling this method for each log entry. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final WriteLogEntriesResponse writeLogEntries( @@ -349,10 +326,10 @@ public final WriteLogEntriesResponse writeLogEntries( // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Writes log entries to Stackdriver Logging. All log entries are - * written by this method. + * Writes log entries to Stackdriver Logging. All log entries are written by this method. + * + *

Sample code: * - * Sample code: *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   List<LogEntry> entries = new ArrayList<>();
@@ -372,10 +349,10 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Writes log entries to Stackdriver Logging.  All log entries are
-   * written by this method.
+   * Writes log entries to Stackdriver Logging. All log entries are written by this method.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   List<LogEntry> entries = new ArrayList<>();
@@ -395,11 +372,11 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists log entries.  Use this method to retrieve log entries from Cloud
-   * Logging.  For ways to export log entries, see
-   * [Exporting Logs](/logging/docs/export).
+   * Lists log entries. Use this method to retrieve log entries from Cloud Logging. For ways to
+   * export log entries, see [Exporting Logs](/logging/docs/export).
+   *
+   * 

Sample code: * - * Sample code: *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   List<String> projectIds = new ArrayList<>();
@@ -412,17 +389,15 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ
    * 
* * @param projectIds Required. One or more project IDs or project numbers from which to retrieve - * log entries. Examples of a project ID: `"my-project-1A"`, `"1234567890"`. - * @param filter Optional. An [advanced logs filter](/logging/docs/view/advanced_filters). - * The filter is compared against all log entries in the projects specified by - * `projectIds`. Only entries that match the filter are retrieved. An empty - * filter matches all log entries. - * @param orderBy Optional. How the results should be sorted. Presently, the only permitted - * values are `"timestamp asc"` (default) and `"timestamp desc"`. The first - * option returns entries in order of increasing values of - * `LogEntry.timestamp` (oldest first), and the second option returns entries - * in order of decreasing timestamps (newest first). Entries with equal - * timestamps are returned in order of `LogEntry.insertId`. + * log entries. Examples of a project ID: `"my-project-1A"`, `"1234567890"`. + * @param filter Optional. An [advanced logs filter](/logging/docs/view/advanced_filters). The + * filter is compared against all log entries in the projects specified by `projectIds`. Only + * entries that match the filter are retrieved. An empty filter matches all log entries. + * @param orderBy Optional. How the results should be sorted. Presently, the only permitted values + * are `"timestamp asc"` (default) and `"timestamp desc"`. The first option returns entries in + * order of increasing values of `LogEntry.timestamp` (oldest first), and the second option + * returns entries in order of decreasing timestamps (newest first). Entries with equal + * timestamps are returned in order of `LogEntry.insertId`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final PagedListResponse @@ -438,11 +413,11 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Lists log entries. Use this method to retrieve log entries from Cloud - * Logging. For ways to export log entries, see - * [Exporting Logs](/logging/docs/export). + * Lists log entries. Use this method to retrieve log entries from Cloud Logging. For ways to + * export log entries, see [Exporting Logs](/logging/docs/export). + * + *

Sample code: * - * Sample code: *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   List<String> projectIds = new ArrayList<>();
@@ -465,11 +440,11 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists log entries.  Use this method to retrieve log entries from Cloud
-   * Logging.  For ways to export log entries, see
-   * [Exporting Logs](/logging/docs/export).
+   * Lists log entries. Use this method to retrieve log entries from Cloud Logging. For ways to
+   * export log entries, see [Exporting Logs](/logging/docs/export).
+   *
+   * 

Sample code: * - * Sample code: *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   List<String> projectIds = new ArrayList<>();
@@ -493,11 +468,11 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists log entries.  Use this method to retrieve log entries from Cloud
-   * Logging.  For ways to export log entries, see
-   * [Exporting Logs](/logging/docs/export).
+   * Lists log entries. Use this method to retrieve log entries from Cloud Logging. For ways to
+   * export log entries, see [Exporting Logs](/logging/docs/export).
+   *
+   * 

Sample code: * - * Sample code: *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   List<String> projectIds = new ArrayList<>();
@@ -527,7 +502,8 @@ public final ApiCallable listLogE
   /**
    * Lists the monitored resource descriptors used by Stackdriver Logging.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder().build();
@@ -551,7 +527,8 @@ public final ApiCallable listLogE
   /**
    * Lists the monitored resource descriptors used by Stackdriver Logging.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder().build();
@@ -576,7 +553,8 @@ public final ApiCallable listLogE
   /**
    * Lists the monitored resource descriptors used by Stackdriver Logging.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
    *   ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder().build();
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Settings.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Settings.java
index 0cc02e00c964..3db49f10b4f0 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Settings.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Settings.java
@@ -15,7 +15,6 @@
 
 import com.google.api.MonitoredResourceDescriptor;
 import com.google.api.gax.core.ConnectionSettings;
-import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -52,15 +51,14 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (logging.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (logging.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of deleteLog to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of deleteLog to 30 seconds: * *

  * 
@@ -74,19 +72,13 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class LoggingServiceV2Settings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "logging.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder()
           .add("https://www.googleapis.com/auth/cloud-platform")
@@ -96,9 +88,7 @@ public class LoggingServiceV2Settings extends ServiceApiSettings {
           .add("https://www.googleapis.com/auth/logging.write")
           .build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -116,32 +106,24 @@ public class LoggingServiceV2Settings extends ServiceApiSettings {
           MonitoredResourceDescriptor>
       listMonitoredResourceDescriptorsSettings;
 
-  /**
-   * Returns the object with the settings used for calls to deleteLog.
-   */
+  /** Returns the object with the settings used for calls to deleteLog. */
   public SimpleCallSettings deleteLogSettings() {
     return deleteLogSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to writeLogEntries.
-   */
+  /** Returns the object with the settings used for calls to writeLogEntries. */
   public SimpleCallSettings
       writeLogEntriesSettings() {
     return writeLogEntriesSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to listLogEntries.
-   */
+  /** Returns the object with the settings used for calls to listLogEntries. */
   public PageStreamingCallSettings
       listLogEntriesSettings() {
     return listLogEntriesSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to listMonitoredResourceDescriptors.
-   */
+  /** Returns the object with the settings used for calls to listMonitoredResourceDescriptors. */
   public PageStreamingCallSettings<
           ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
           MonitoredResourceDescriptor>
@@ -149,44 +131,32 @@ public SimpleCallSettings deleteLogSettings() {
     return listMonitoredResourceDescriptorsSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -288,9 +258,7 @@ public Iterable extractResources(
             }
           };
 
-  /**
-   * Builder for LoggingServiceV2Settings.
-   */
+  /** Builder for LoggingServiceV2Settings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -462,42 +430,33 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to deleteLog.
-     */
+    /** Returns the builder for the settings used for calls to deleteLog. */
     public SimpleCallSettings.Builder deleteLogSettings() {
       return deleteLogSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to writeLogEntries.
-     */
+    /** Returns the builder for the settings used for calls to writeLogEntries. */
     public SimpleCallSettings.Builder
         writeLogEntriesSettings() {
       return writeLogEntriesSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listLogEntries.
-     */
+    /** Returns the builder for the settings used for calls to listLogEntries. */
     public PageStreamingCallSettings.Builder<
             ListLogEntriesRequest, ListLogEntriesResponse, LogEntry>
         listLogEntriesSettings() {
       return listLogEntriesSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listMonitoredResourceDescriptors.
-     */
+    /** Returns the builder for the settings used for calls to listMonitoredResourceDescriptors. */
     public PageStreamingCallSettings.Builder<
             ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
             MonitoredResourceDescriptor>
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Api.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Api.java
index 53c07512a22c..e458ba1c756e 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Api.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Api.java
@@ -48,28 +48,27 @@
  * 
* *

Note: close() needs to be called on the metricsServiceV2Api object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + * as threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * *

This class can be customized by passing in a custom instance of MetricsServiceV2Settings to * create(). For example: @@ -106,59 +105,41 @@ public class MetricsServiceV2Api implements AutoCloseable { private static final PathTemplate METRIC_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}/metrics/{metric}"); - /** - * Formats a string containing the fully-qualified path to represent - * a parent resource. - */ + /** Formats a string containing the fully-qualified path to represent a parent resource. */ public static final String formatParentName(String project) { return PARENT_PATH_TEMPLATE.instantiate("project", project); } - /** - * Formats a string containing the fully-qualified path to represent - * a metric resource. - */ + /** Formats a string containing the fully-qualified path to represent a metric resource. */ public static final String formatMetricName(String project, String metric) { return METRIC_PATH_TEMPLATE.instantiate( "project", project, "metric", metric); } - /** - * Parses the project from the given fully-qualified path which - * represents a parent resource. - */ + /** Parses the project from the given fully-qualified path which represents a parent resource. */ public static final String parseProjectFromParentName(String parentName) { return PARENT_PATH_TEMPLATE.parse(parentName).get("project"); } - /** - * Parses the project from the given fully-qualified path which - * represents a metric resource. - */ + /** Parses the project from the given fully-qualified path which represents a metric resource. */ public static final String parseProjectFromMetricName(String metricName) { return METRIC_PATH_TEMPLATE.parse(metricName).get("project"); } - /** - * Parses the metric from the given fully-qualified path which - * represents a metric resource. - */ + /** Parses the metric from the given fully-qualified path which represents a metric resource. */ public static final String parseMetricFromMetricName(String metricName) { return METRIC_PATH_TEMPLATE.parse(metricName).get("metric"); } - /** - * Constructs an instance of MetricsServiceV2Api with default settings. - */ + /** Constructs an instance of MetricsServiceV2Api with default settings. */ public static final MetricsServiceV2Api create() throws IOException { return create(MetricsServiceV2Settings.defaultBuilder().build()); } /** - * Constructs an instance of MetricsServiceV2Api, using the given settings. - * The channels are created based on the settings passed in, or defaults for any - * settings that are not set. + * Constructs an instance of MetricsServiceV2Api, using the given settings. The channels are + * created based on the settings passed in, or defaults for any settings that are not set. */ public static final MetricsServiceV2Api create(MetricsServiceV2Settings settings) throws IOException { @@ -166,9 +147,8 @@ public static final MetricsServiceV2Api create(MetricsServiceV2Settings settings } /** - * Constructs an instance of MetricsServiceV2Api, using the given settings. - * This is protected so that it easy to make a subclass, but otherwise, the static - * factory methods should be preferred. + * Constructs an instance of MetricsServiceV2Api, using the given settings. This is protected so + * that it easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected MetricsServiceV2Api(MetricsServiceV2Settings settings) throws IOException { this.settings = settings; @@ -217,7 +197,8 @@ public final MetricsServiceV2Settings getSettings() { /** * Lists logs-based metrics. * - * Sample code: + *

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
@@ -227,8 +208,8 @@ public final MetricsServiceV2Settings getSettings() {
    * }
    * 
* - * @param parent Required. The resource name containing the metrics. - * Example: `"projects/my-project-id"`. + * @param parent Required. The resource name containing the metrics. Example: + * `"projects/my-project-id"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final PagedListResponse @@ -242,7 +223,8 @@ public final MetricsServiceV2Settings getSettings() { /** * Lists logs-based metrics. * - * Sample code: + *

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
@@ -267,7 +249,8 @@ public final MetricsServiceV2Settings getSettings() {
   /**
    * Lists logs-based metrics.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
@@ -293,7 +276,8 @@ public final MetricsServiceV2Settings getSettings() {
   /**
    * Lists logs-based metrics.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
@@ -323,7 +307,8 @@ public final ApiCallable listLogM
   /**
    * Gets a logs-based metric.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
@@ -331,8 +316,8 @@ public final ApiCallable listLogM
    * }
    * 
* - * @param metricName The resource name of the desired metric. - * Example: `"projects/my-project-id/metrics/my-metric-id"`. + * @param metricName The resource name of the desired metric. Example: + * `"projects/my-project-id/metrics/my-metric-id"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final LogMetric getLogMetric(String metricName) { @@ -346,7 +331,8 @@ public final LogMetric getLogMetric(String metricName) { /** * Gets a logs-based metric. * - * Sample code: + *

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
@@ -368,7 +354,8 @@ private final LogMetric getLogMetric(GetLogMetricRequest request) {
   /**
    * Gets a logs-based metric.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
@@ -389,7 +376,8 @@ public final ApiCallable getLogMetricCallable()
   /**
    * Creates a logs-based metric.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
@@ -398,12 +386,10 @@ public final ApiCallable getLogMetricCallable()
    * }
    * 
* - * @param parent The resource name of the project in which to create the metric. - * Example: `"projects/my-project-id"`. - * - * The new metric must be provided in the request. - * @param metric The new logs-based metric, which must not have an identifier that - * already exists. + * @param parent The resource name of the project in which to create the metric. Example: + * `"projects/my-project-id"`. + *

The new metric must be provided in the request. + * @param metric The new logs-based metric, which must not have an identifier that already exists. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final LogMetric createLogMetric(String parent, LogMetric metric) { @@ -417,7 +403,8 @@ public final LogMetric createLogMetric(String parent, LogMetric metric) { /** * Creates a logs-based metric. * - * Sample code: + *

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
@@ -441,7 +428,8 @@ public final LogMetric createLogMetric(CreateLogMetricRequest request) {
   /**
    * Creates a logs-based metric.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]");
@@ -464,7 +452,8 @@ public final ApiCallable createLogMetricCalla
   /**
    * Creates or updates a logs-based metric.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
@@ -473,15 +462,12 @@ public final ApiCallable createLogMetricCalla
    * }
    * 
* - * @param metricName The resource name of the metric to update. - * Example: `"projects/my-project-id/metrics/my-metric-id"`. - * - * The updated metric must be provided in the request and have the - * same identifier that is specified in `metricName`. - * If the metric does not exist, it is created. - * @param metric The updated metric, whose name must be the same as the - * metric identifier in `metricName`. If `metricName` does not - * exist, then a new metric is created. + * @param metricName The resource name of the metric to update. Example: + * `"projects/my-project-id/metrics/my-metric-id"`. + *

The updated metric must be provided in the request and have the same identifier that is + * specified in `metricName`. If the metric does not exist, it is created. + * @param metric The updated metric, whose name must be the same as the metric identifier in + * `metricName`. If `metricName` does not exist, then a new metric is created. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final LogMetric updateLogMetric(String metricName, LogMetric metric) { @@ -495,7 +481,8 @@ public final LogMetric updateLogMetric(String metricName, LogMetric metric) { /** * Creates or updates a logs-based metric. * - * Sample code: + *

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
@@ -519,7 +506,8 @@ public final LogMetric updateLogMetric(UpdateLogMetricRequest request) {
   /**
    * Creates or updates a logs-based metric.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
@@ -542,7 +530,8 @@ public final ApiCallable updateLogMetricCalla
   /**
    * Deletes a logs-based metric.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
@@ -550,8 +539,8 @@ public final ApiCallable updateLogMetricCalla
    * }
    * 
* - * @param metricName The resource name of the metric to delete. - * Example: `"projects/my-project-id/metrics/my-metric-id"`. + * @param metricName The resource name of the metric to delete. Example: + * `"projects/my-project-id/metrics/my-metric-id"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final void deleteLogMetric(String metricName) { @@ -565,7 +554,8 @@ public final void deleteLogMetric(String metricName) { /** * Deletes a logs-based metric. * - * Sample code: + *

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
@@ -587,7 +577,8 @@ private final void deleteLogMetric(DeleteLogMetricRequest request) {
   /**
    * Deletes a logs-based metric.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
    *   String formattedMetricName = MetricsServiceV2Api.formatMetricName("[PROJECT]", "[METRIC]");
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Settings.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Settings.java
index c58f60f8e3e0..33302e500c2f 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Settings.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Settings.java
@@ -14,7 +14,6 @@
 package com.google.cloud.logging.spi.v2;
 
 import com.google.api.gax.core.ConnectionSettings;
-import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -50,15 +49,14 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (logging.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (logging.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of getLogMetric to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of getLogMetric to 30 seconds: * *

  * 
@@ -72,19 +70,13 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class MetricsServiceV2Settings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "logging.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder()
           .add("https://www.googleapis.com/auth/cloud-platform")
@@ -94,9 +86,7 @@ public class MetricsServiceV2Settings extends ServiceApiSettings {
           .add("https://www.googleapis.com/auth/logging.write")
           .build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -111,80 +101,58 @@ public class MetricsServiceV2Settings extends ServiceApiSettings {
   private final SimpleCallSettings updateLogMetricSettings;
   private final SimpleCallSettings deleteLogMetricSettings;
 
-  /**
-   * Returns the object with the settings used for calls to listLogMetrics.
-   */
+  /** Returns the object with the settings used for calls to listLogMetrics. */
   public PageStreamingCallSettings
       listLogMetricsSettings() {
     return listLogMetricsSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to getLogMetric.
-   */
+  /** Returns the object with the settings used for calls to getLogMetric. */
   public SimpleCallSettings getLogMetricSettings() {
     return getLogMetricSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to createLogMetric.
-   */
+  /** Returns the object with the settings used for calls to createLogMetric. */
   public SimpleCallSettings createLogMetricSettings() {
     return createLogMetricSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to updateLogMetric.
-   */
+  /** Returns the object with the settings used for calls to updateLogMetric. */
   public SimpleCallSettings updateLogMetricSettings() {
     return updateLogMetricSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to deleteLogMetric.
-   */
+  /** Returns the object with the settings used for calls to deleteLogMetric. */
   public SimpleCallSettings deleteLogMetricSettings() {
     return deleteLogMetricSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -241,9 +209,7 @@ public Iterable extractResources(ListLogMetricsResponse payload) {
             }
           };
 
-  /**
-   * Builder for MetricsServiceV2Settings.
-   */
+  /** Builder for MetricsServiceV2Settings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -413,48 +379,37 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listLogMetrics.
-     */
+    /** Returns the builder for the settings used for calls to listLogMetrics. */
     public PageStreamingCallSettings.Builder<
             ListLogMetricsRequest, ListLogMetricsResponse, LogMetric>
         listLogMetricsSettings() {
       return listLogMetricsSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to getLogMetric.
-     */
+    /** Returns the builder for the settings used for calls to getLogMetric. */
     public SimpleCallSettings.Builder getLogMetricSettings() {
       return getLogMetricSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to createLogMetric.
-     */
+    /** Returns the builder for the settings used for calls to createLogMetric. */
     public SimpleCallSettings.Builder createLogMetricSettings() {
       return createLogMetricSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to updateLogMetric.
-     */
+    /** Returns the builder for the settings used for calls to updateLogMetric. */
     public SimpleCallSettings.Builder updateLogMetricSettings() {
       return updateLogMetricSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to deleteLogMetric.
-     */
+    /** Returns the builder for the settings used for calls to deleteLogMetric. */
     public SimpleCallSettings.Builder deleteLogMetricSettings() {
       return deleteLogMetricSettings;
     }
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/package-info.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/package-info.java
index e16b370463dc..c579f3ff26d6 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/package-info.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/package-info.java
@@ -15,15 +15,14 @@
 /**
  * A client to Stackdriver Logging API.
  *
- * The interfaces provided are listed below, along with a usage sample
+ * 

The interfaces provided are listed below, along with a usage sample * - * =================== - * LoggingServiceV2Api - * =================== + *

=================== LoggingServiceV2Api =================== * - * Service Description: Service for ingesting and querying logs. + *

Service Description: Service for ingesting and querying logs. + * + *

Sample for LoggingServiceV2Api: * - * Sample for LoggingServiceV2Api: *

  * 
  * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
@@ -33,14 +32,13 @@
  * 
  * 
* - * ================== - * ConfigServiceV2Api - * ================== + * ================== ConfigServiceV2Api ================== + * + *

Service Description: Service for configuring sinks used to export log entries outside + * Stackdriver Logging. * - * Service Description: Service for configuring sinks used to export log entries outside Stackdriver - * Logging. + *

Sample for ConfigServiceV2Api: * - * Sample for ConfigServiceV2Api: *

  * 
  * try (ConfigServiceV2Api configServiceV2Api = ConfigServiceV2Api.create()) {
@@ -50,13 +48,12 @@
  * 
  * 
* - * =================== - * MetricsServiceV2Api - * =================== + * =================== MetricsServiceV2Api =================== * - * Service Description: Service for configuring logs-based metrics. + *

Service Description: Service for configuring logs-based metrics. + * + *

Sample for MetricsServiceV2Api: * - * Sample for MetricsServiceV2Api: *

  * 
  * try (MetricsServiceV2Api metricsServiceV2Api = MetricsServiceV2Api.create()) {
@@ -65,6 +62,5 @@
  * }
  * 
  * 
- * */ package com.google.cloud.logging.spi.v2; diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceApi.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceApi.java index f08630cd7fa9..a81142c23194 100644 --- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceApi.java +++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceApi.java @@ -28,9 +28,8 @@ // AUTO-GENERATED DOCUMENTATION AND SERVICE /** - * Service Description: The AgentTranslation API allows `collectd`-based agents to - * write time series data to Cloud Monitoring. - * See [google.monitoring.v3.MetricService.CreateTimeSeries] instead. + * Service Description: The AgentTranslation API allows `collectd`-based agents to write time series + * data to Cloud Monitoring. See [google.monitoring.v3.MetricService.CreateTimeSeries] instead. * *

This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: @@ -47,32 +46,32 @@ * *

* - *

Note: close() needs to be called on the agentTranslationServiceApi object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + *

Note: close() needs to be called on the agentTranslationServiceApi object to clean up + * resources such as threads. In the example above, try-with-resources is used, which automatically + * calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * - *

This class can be customized by passing in a custom instance of AgentTranslationServiceSettings to - * create(). For example: + *

This class can be customized by passing in a custom instance of + * AgentTranslationServiceSettings to create(). For example: * *

  * 
@@ -96,33 +95,24 @@ public class AgentTranslationServiceApi implements AutoCloseable {
   private static final PathTemplate PROJECT_PATH_TEMPLATE =
       PathTemplate.createWithoutUrlEncoding("projects/{project}");
 
-  /**
-   * Formats a string containing the fully-qualified path to represent
-   * a project resource.
-   */
+  /** Formats a string containing the fully-qualified path to represent a project resource. */
   public static final String formatProjectName(String project) {
     return PROJECT_PATH_TEMPLATE.instantiate("project", project);
   }
 
-  /**
-   * Parses the project from the given fully-qualified path which
-   * represents a project resource.
-   */
+  /** Parses the project from the given fully-qualified path which represents a project resource. */
   public static final String parseProjectFromProjectName(String projectName) {
     return PROJECT_PATH_TEMPLATE.parse(projectName).get("project");
   }
 
-  /**
-   * Constructs an instance of AgentTranslationServiceApi with default settings.
-   */
+  /** Constructs an instance of AgentTranslationServiceApi with default settings. */
   public static final AgentTranslationServiceApi create() throws IOException {
     return create(AgentTranslationServiceSettings.defaultBuilder().build());
   }
 
   /**
-   * Constructs an instance of AgentTranslationServiceApi, using the given settings.
-   * The channels are created based on the settings passed in, or defaults for any
-   * settings that are not set.
+   * Constructs an instance of AgentTranslationServiceApi, using the given settings. The channels
+   * are created based on the settings passed in, or defaults for any settings that are not set.
    */
   public static final AgentTranslationServiceApi create(AgentTranslationServiceSettings settings)
       throws IOException {
@@ -130,9 +120,9 @@ public static final AgentTranslationServiceApi create(AgentTranslationServiceSet
   }
 
   /**
-   * Constructs an instance of AgentTranslationServiceApi, using the given settings.
-   * This is protected so that it easy to make a subclass, but otherwise, the static
-   * factory methods should be preferred.
+   * Constructs an instance of AgentTranslationServiceApi, using the given settings. This is
+   * protected so that it easy to make a subclass, but otherwise, the static factory methods should
+   * be preferred.
    */
   protected AgentTranslationServiceApi(AgentTranslationServiceSettings settings)
       throws IOException {
@@ -172,11 +162,12 @@ public final AgentTranslationServiceSettings getSettings() {
   /**
    * **Stackdriver Monitoring Agent only:** Creates a new time series.
    *
-   * <aside class="caution">This method is only for use by the Google Monitoring Agent.
-   * Use [projects.timeSeries.create][google.monitoring.v3.MetricService.CreateTimeSeries]
+   * 

<aside class="caution">This method is only for use by the Google Monitoring Agent. Use + * [projects.timeSeries.create][google.monitoring.v3.MetricService.CreateTimeSeries] * instead.</aside> * - * Sample code: + *

Sample code: + * *


    * try (AgentTranslationServiceApi agentTranslationServiceApi = AgentTranslationServiceApi.create()) {
    *   String formattedName = AgentTranslationServiceApi.formatProjectName("[PROJECT]");
@@ -188,13 +179,13 @@ public final AgentTranslationServiceSettings getSettings() {
    * 
* * @param name The project in which to create the time series. The format is - * `"projects/PROJECT_ID_OR_NUMBER"`. + * `"projects/PROJECT_ID_OR_NUMBER"`. * @param resource The monitored resource associated with the time series. - * @param collectdVersion The version of `collectd` that collected the data. Example: `"5.3.0-192.el6"`. - * @param collectdPayloads The `collectd` payloads representing the time series data. - * You must not include more than a single point for each - * time series, so no two payloads can have the same values - * for all of the fields `plugin`, `plugin_instance`, `type`, and `type_instance`. + * @param collectdVersion The version of `collectd` that collected the data. Example: + * `"5.3.0-192.el6"`. + * @param collectdPayloads The `collectd` payloads representing the time series data. You must not + * include more than a single point for each time series, so no two payloads can have the same + * values for all of the fields `plugin`, `plugin_instance`, `type`, and `type_instance`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final void createCollectdTimeSeries( @@ -217,11 +208,12 @@ public final void createCollectdTimeSeries( /** * **Stackdriver Monitoring Agent only:** Creates a new time series. * - * <aside class="caution">This method is only for use by the Google Monitoring Agent. - * Use [projects.timeSeries.create][google.monitoring.v3.MetricService.CreateTimeSeries] + *

<aside class="caution">This method is only for use by the Google Monitoring Agent. Use + * [projects.timeSeries.create][google.monitoring.v3.MetricService.CreateTimeSeries] * instead.</aside> * - * Sample code: + *

Sample code: + * *


    * try (AgentTranslationServiceApi agentTranslationServiceApi = AgentTranslationServiceApi.create()) {
    *   String formattedName = AgentTranslationServiceApi.formatProjectName("[PROJECT]");
@@ -249,11 +241,12 @@ public final void createCollectdTimeSeries(CreateCollectdTimeSeriesRequest reque
   /**
    * **Stackdriver Monitoring Agent only:** Creates a new time series.
    *
-   * <aside class="caution">This method is only for use by the Google Monitoring Agent.
-   * Use [projects.timeSeries.create][google.monitoring.v3.MetricService.CreateTimeSeries]
+   * 

<aside class="caution">This method is only for use by the Google Monitoring Agent. Use + * [projects.timeSeries.create][google.monitoring.v3.MetricService.CreateTimeSeries] * instead.</aside> * - * Sample code: + *

Sample code: + * *


    * try (AgentTranslationServiceApi agentTranslationServiceApi = AgentTranslationServiceApi.create()) {
    *   String formattedName = AgentTranslationServiceApi.formatProjectName("[PROJECT]");
diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceSettings.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceSettings.java
index 9af3c0b4c166..72bbff0eebbb 100644
--- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceSettings.java
+++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceSettings.java
@@ -16,7 +16,6 @@
 import com.google.api.gax.core.ConnectionSettings;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
-import com.google.api.gax.grpc.PageStreamingDescriptor;
 import com.google.api.gax.grpc.ServiceApiSettings;
 import com.google.api.gax.grpc.SimpleCallSettings;
 import com.google.auth.Credentials;
@@ -42,15 +41,14 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (monitoring.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (monitoring.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of createCollectdTimeSeries to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of createCollectdTimeSeries to 30 seconds: * *

  * 
@@ -64,25 +62,17 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class AgentTranslationServiceSettings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "monitoring.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder().build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -93,52 +83,38 @@ public class AgentTranslationServiceSettings extends ServiceApiSettings {
   private final SimpleCallSettings
       createCollectdTimeSeriesSettings;
 
-  /**
-   * Returns the object with the settings used for calls to createCollectdTimeSeries.
-   */
+  /** Returns the object with the settings used for calls to createCollectdTimeSeries. */
   public SimpleCallSettings
       createCollectdTimeSeriesSettings() {
     return createCollectdTimeSeriesSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -155,9 +131,7 @@ private AgentTranslationServiceSettings(Builder settingsBuilder) throws IOExcept
     createCollectdTimeSeriesSettings = settingsBuilder.createCollectdTimeSeriesSettings().build();
   }
 
-  /**
-   * Builder for AgentTranslationServiceSettings.
-   */
+  /** Builder for AgentTranslationServiceSettings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -274,18 +248,15 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to createCollectdTimeSeries.
-     */
+    /** Returns the builder for the settings used for calls to createCollectdTimeSeries. */
     public SimpleCallSettings.Builder
         createCollectdTimeSeriesSettings() {
       return createCollectdTimeSeriesSettings;
diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceApi.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceApi.java
index 48f7a007e528..850406c119de 100644
--- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceApi.java
+++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceApi.java
@@ -40,15 +40,12 @@
  * Service Description: The Group API lets you inspect and manage your
  * [groups](google.monitoring.v3.Group).
  *
- * A group is a named filter that is used to identify
- * a collection of monitored resources. Groups are typically used to
- * mirror the physical and/or logical topology of the environment.
- * Because group membership is computed dynamically, monitored
- * resources that are started in the future are automatically placed
- * in matching groups. By using a group to name monitored resources in,
- * for example, an alert policy, the target of that alert policy is
- * updated automatically as monitored resources are added and removed
- * from the infrastructure.
+ * 

A group is a named filter that is used to identify a collection of monitored resources. Groups + * are typically used to mirror the physical and/or logical topology of the environment. Because + * group membership is computed dynamically, monitored resources that are started in the future are + * automatically placed in matching groups. By using a group to name monitored resources in, for + * example, an alert policy, the target of that alert policy is updated automatically as monitored + * resources are added and removed from the infrastructure. * *

This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: @@ -62,29 +59,28 @@ * *

* - *

Note: close() needs to be called on the groupServiceApi object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + *

Note: close() needs to be called on the groupServiceApi object to clean up resources such as + * threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * *

This class can be customized by passing in a custom instance of GroupServiceSettings to * create(). For example: @@ -126,68 +122,49 @@ public class GroupServiceApi implements AutoCloseable { private static final PathTemplate GROUP_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}/groups/{group}"); - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - */ + /** Formats a string containing the fully-qualified path to represent a project resource. */ public static final String formatProjectName(String project) { return PROJECT_PATH_TEMPLATE.instantiate("project", project); } - /** - * Formats a string containing the fully-qualified path to represent - * a group resource. - */ + /** Formats a string containing the fully-qualified path to represent a group resource. */ public static final String formatGroupName(String project, String group) { return GROUP_PATH_TEMPLATE.instantiate( "project", project, "group", group); } - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - */ + /** Parses the project from the given fully-qualified path which represents a project resource. */ public static final String parseProjectFromProjectName(String projectName) { return PROJECT_PATH_TEMPLATE.parse(projectName).get("project"); } - /** - * Parses the project from the given fully-qualified path which - * represents a group resource. - */ + /** Parses the project from the given fully-qualified path which represents a group resource. */ public static final String parseProjectFromGroupName(String groupName) { return GROUP_PATH_TEMPLATE.parse(groupName).get("project"); } - /** - * Parses the group from the given fully-qualified path which - * represents a group resource. - */ + /** Parses the group from the given fully-qualified path which represents a group resource. */ public static final String parseGroupFromGroupName(String groupName) { return GROUP_PATH_TEMPLATE.parse(groupName).get("group"); } - /** - * Constructs an instance of GroupServiceApi with default settings. - */ + /** Constructs an instance of GroupServiceApi with default settings. */ public static final GroupServiceApi create() throws IOException { return create(GroupServiceSettings.defaultBuilder().build()); } /** - * Constructs an instance of GroupServiceApi, using the given settings. - * The channels are created based on the settings passed in, or defaults for any - * settings that are not set. + * Constructs an instance of GroupServiceApi, using the given settings. The channels are created + * based on the settings passed in, or defaults for any settings that are not set. */ public static final GroupServiceApi create(GroupServiceSettings settings) throws IOException { return new GroupServiceApi(settings); } /** - * Constructs an instance of GroupServiceApi, using the given settings. - * This is protected so that it easy to make a subclass, but otherwise, the static - * factory methods should be preferred. + * Constructs an instance of GroupServiceApi, using the given settings. This is protected so that + * it easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected GroupServiceApi(GroupServiceSettings settings) throws IOException { this.settings = settings; @@ -238,10 +215,10 @@ public final GroupServiceSettings getSettings() { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Lists the existing groups. The project ID in the URL path must refer - * to a Stackdriver account. + * Lists the existing groups. The project ID in the URL path must refer to a Stackdriver account. + * + *

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatProjectName("[PROJECT]");
@@ -264,10 +241,10 @@ public final PagedListResponse lis
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists the existing groups. The project ID in the URL path must refer
-   * to a Stackdriver account.
+   * Lists the existing groups. The project ID in the URL path must refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatProjectName("[PROJECT]");
@@ -290,10 +267,10 @@ public final PagedListResponse lis
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists the existing groups. The project ID in the URL path must refer
-   * to a Stackdriver account.
+   * Lists the existing groups. The project ID in the URL path must refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatProjectName("[PROJECT]");
@@ -321,10 +298,10 @@ public final ApiCallable listGroupsCallab
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Gets a single group. The project ID in the URL path must refer to a
-   * Stackdriver account.
+   * Gets a single group. The project ID in the URL path must refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
@@ -333,7 +310,7 @@ public final ApiCallable listGroupsCallab
    * 
* * @param name The group to retrieve. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. + * `"projects/{project_id_or_number}/groups/{group_id}"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final Group getGroup(String name) { @@ -344,10 +321,10 @@ public final Group getGroup(String name) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets a single group. The project ID in the URL path must refer to a - * Stackdriver account. + * Gets a single group. The project ID in the URL path must refer to a Stackdriver account. + * + *

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
@@ -367,10 +344,10 @@ private final Group getGroup(GetGroupRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Gets a single group. The project ID in the URL path must refer to a
-   * Stackdriver account.
+   * Gets a single group. The project ID in the URL path must refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
@@ -389,10 +366,10 @@ public final ApiCallable getGroupCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Creates a new group. The project ID in the URL path must refer to a
-   * Stackdriver account.
+   * Creates a new group. The project ID in the URL path must refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatProjectName("[PROJECT]");
@@ -403,9 +380,9 @@ public final ApiCallable getGroupCallable() {
    * 
* * @param name The project in which to create the group. The format is - * `"projects/{project_id_or_number}"`. - * @param group A group definition. It is an error to define the `name` field because - * the system assigns the name. + * `"projects/{project_id_or_number}"`. + * @param group A group definition. It is an error to define the `name` field because the system + * assigns the name. * @param validateOnly If true, validate this request but do not create the group. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ @@ -422,10 +399,10 @@ public final Group createGroup(String name, Group group, boolean validateOnly) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Creates a new group. The project ID in the URL path must refer to a - * Stackdriver account. + * Creates a new group. The project ID in the URL path must refer to a Stackdriver account. + * + *

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatProjectName("[PROJECT]");
@@ -449,10 +426,10 @@ public final Group createGroup(CreateGroupRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Creates a new group. The project ID in the URL path must refer to a
-   * Stackdriver account.
+   * Creates a new group. The project ID in the URL path must refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatProjectName("[PROJECT]");
@@ -475,11 +452,11 @@ public final ApiCallable createGroupCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Updates an existing group.
-   * You can change any group attributes except `name`.
-   * The project ID in the URL path must refer to a Stackdriver account.
+   * Updates an existing group. You can change any group attributes except `name`. The project ID in
+   * the URL path must refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   Group group = Group.newBuilder().build();
@@ -488,8 +465,8 @@ public final ApiCallable createGroupCallable() {
    * }
    * 
* - * @param group The new definition of the group. All fields of the existing group, - * excepting `name`, are replaced with the corresponding fields of this group. + * @param group The new definition of the group. All fields of the existing group, excepting + * `name`, are replaced with the corresponding fields of this group. * @param validateOnly If true, validate this request but do not update the existing group. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ @@ -501,11 +478,11 @@ public final Group updateGroup(Group group, boolean validateOnly) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Updates an existing group. - * You can change any group attributes except `name`. - * The project ID in the URL path must refer to a Stackdriver account. + * Updates an existing group. You can change any group attributes except `name`. The project ID in + * the URL path must refer to a Stackdriver account. + * + *

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   Group group = Group.newBuilder().build();
@@ -527,11 +504,11 @@ public final Group updateGroup(UpdateGroupRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Updates an existing group.
-   * You can change any group attributes except `name`.
-   * The project ID in the URL path must refer to a Stackdriver account.
+   * Updates an existing group. You can change any group attributes except `name`. The project ID in
+   * the URL path must refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   Group group = Group.newBuilder().build();
@@ -552,10 +529,10 @@ public final ApiCallable updateGroupCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Deletes an existing group. The project ID in the URL path must refer to a
-   * Stackdriver account.
+   * Deletes an existing group. The project ID in the URL path must refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
@@ -564,7 +541,7 @@ public final ApiCallable updateGroupCallable() {
    * 
* * @param name The group to delete. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. + * `"projects/{project_id_or_number}/groups/{group_id}"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final void deleteGroup(String name) { @@ -575,10 +552,10 @@ public final void deleteGroup(String name) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Deletes an existing group. The project ID in the URL path must refer to a - * Stackdriver account. + * Deletes an existing group. The project ID in the URL path must refer to a Stackdriver account. + * + *

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
@@ -598,10 +575,10 @@ private final void deleteGroup(DeleteGroupRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Deletes an existing group. The project ID in the URL path must refer to a
-   * Stackdriver account.
+   * Deletes an existing group. The project ID in the URL path must refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
@@ -620,10 +597,11 @@ public final ApiCallable deleteGroupCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists the monitored resources that are members of a group. The project ID
-   * in the URL path must refer to a Stackdriver account.
+   * Lists the monitored resources that are members of a group. The project ID in the URL path must
+   * refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
@@ -636,18 +614,15 @@ public final ApiCallable deleteGroupCallable() {
    * 
* * @param name The group whose members are listed. The format is - * `"projects/{project_id_or_number}/groups/{group_id}"`. - * @param filter An optional [list filter](/monitoring/api/learn_more#filtering) describing - * the members to be returned. The filter may reference the type, labels, and - * metadata of monitored resources that comprise the group. - * For example, to return only resources representing Compute Engine VM - * instances, use this filter: - * - * resource.type = "gce_instance" - * @param interval An optional time interval for which results should be returned. Only - * members that were part of the group during the specified interval are - * included in the response. If no interval is provided then the group - * membership over the last minute is returned. + * `"projects/{project_id_or_number}/groups/{group_id}"`. + * @param filter An optional [list filter](/monitoring/api/learn_more#filtering) describing the + * members to be returned. The filter may reference the type, labels, and metadata of + * monitored resources that comprise the group. For example, to return only resources + * representing Compute Engine VM instances, use this filter: + *

resource.type = "gce_instance" + * @param interval An optional time interval for which results should be returned. Only members + * that were part of the group during the specified interval are included in the response. If + * no interval is provided then the group membership over the last minute is returned. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final PagedListResponse< @@ -665,10 +640,11 @@ public final ApiCallable deleteGroupCallable() { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Lists the monitored resources that are members of a group. The project ID - * in the URL path must refer to a Stackdriver account. + * Lists the monitored resources that are members of a group. The project ID in the URL path must + * refer to a Stackdriver account. + * + *

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
@@ -696,10 +672,11 @@ public final ApiCallable deleteGroupCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists the monitored resources that are members of a group. The project ID
-   * in the URL path must refer to a Stackdriver account.
+   * Lists the monitored resources that are members of a group. The project ID in the URL path must
+   * refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
@@ -727,10 +704,11 @@ public final ApiCallable deleteGroupCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists the monitored resources that are members of a group. The project ID
-   * in the URL path must refer to a Stackdriver account.
+   * Lists the monitored resources that are members of a group. The project ID in the URL path must
+   * refer to a Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
    *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceSettings.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceSettings.java
index 2b2b02fea282..a5e1f1d06d73 100644
--- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceSettings.java
+++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceSettings.java
@@ -15,7 +15,6 @@
 
 import com.google.api.MonitoredResource;
 import com.google.api.gax.core.ConnectionSettings;
-import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -53,15 +52,14 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (monitoring.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (monitoring.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of getGroup to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of getGroup to 30 seconds: * *

  * 
@@ -75,25 +73,17 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class GroupServiceSettings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "monitoring.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder().build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -111,89 +101,65 @@ public class GroupServiceSettings extends ServiceApiSettings {
           ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource>
       listGroupMembersSettings;
 
-  /**
-   * Returns the object with the settings used for calls to listGroups.
-   */
+  /** Returns the object with the settings used for calls to listGroups. */
   public PageStreamingCallSettings
       listGroupsSettings() {
     return listGroupsSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to getGroup.
-   */
+  /** Returns the object with the settings used for calls to getGroup. */
   public SimpleCallSettings getGroupSettings() {
     return getGroupSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to createGroup.
-   */
+  /** Returns the object with the settings used for calls to createGroup. */
   public SimpleCallSettings createGroupSettings() {
     return createGroupSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to updateGroup.
-   */
+  /** Returns the object with the settings used for calls to updateGroup. */
   public SimpleCallSettings updateGroupSettings() {
     return updateGroupSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to deleteGroup.
-   */
+  /** Returns the object with the settings used for calls to deleteGroup. */
   public SimpleCallSettings deleteGroupSettings() {
     return deleteGroupSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to listGroupMembers.
-   */
+  /** Returns the object with the settings used for calls to listGroupMembers. */
   public PageStreamingCallSettings<
           ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource>
       listGroupMembersSettings() {
     return listGroupMembersSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -289,9 +255,7 @@ public Iterable extractResources(ListGroupMembersResponse pay
             }
           };
 
-  /**
-   * Builder for GroupServiceSettings.
-   */
+  /** Builder for GroupServiceSettings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -469,54 +433,41 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listGroups.
-     */
+    /** Returns the builder for the settings used for calls to listGroups. */
     public PageStreamingCallSettings.Builder
         listGroupsSettings() {
       return listGroupsSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to getGroup.
-     */
+    /** Returns the builder for the settings used for calls to getGroup. */
     public SimpleCallSettings.Builder getGroupSettings() {
       return getGroupSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to createGroup.
-     */
+    /** Returns the builder for the settings used for calls to createGroup. */
     public SimpleCallSettings.Builder createGroupSettings() {
       return createGroupSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to updateGroup.
-     */
+    /** Returns the builder for the settings used for calls to updateGroup. */
     public SimpleCallSettings.Builder updateGroupSettings() {
       return updateGroupSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to deleteGroup.
-     */
+    /** Returns the builder for the settings used for calls to deleteGroup. */
     public SimpleCallSettings.Builder deleteGroupSettings() {
       return deleteGroupSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listGroupMembers.
-     */
+    /** Returns the builder for the settings used for calls to listGroupMembers. */
     public PageStreamingCallSettings.Builder<
             ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource>
         listGroupMembersSettings() {
diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceApi.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceApi.java
index f1ba47dc1283..bd3599c6d493 100644
--- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceApi.java
+++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceApi.java
@@ -40,8 +40,8 @@
 
 // AUTO-GENERATED DOCUMENTATION AND SERVICE
 /**
- * Service Description: Manages metric descriptors, monitored resource descriptors, and
- * time series data.
+ * Service Description: Manages metric descriptors, monitored resource descriptors, and time series
+ * data.
  *
  * 

This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: @@ -55,29 +55,28 @@ * *

* - *

Note: close() needs to be called on the metricServiceApi object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + *

Note: close() needs to be called on the metricServiceApi object to clean up resources such as + * threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * *

This class can be customized by passing in a custom instance of MetricServiceSettings to * create(). For example: @@ -139,17 +138,14 @@ public class MetricServiceApi implements AutoCloseable { PathTemplate.createWithoutUrlEncoding( "projects/{project}/monitoredResourceDescriptors/{monitored_resource_descriptor}"); - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - */ + /** Formats a string containing the fully-qualified path to represent a project resource. */ public static final String formatProjectName(String project) { return PROJECT_PATH_TEMPLATE.instantiate("project", project); } /** - * Formats a string containing the fully-qualified path to represent - * a metric_descriptor_path resource. + * Formats a string containing the fully-qualified path to represent a metric_descriptor_path + * resource. */ public static final String formatMetricDescriptorPathName( String project, String metricDescriptorPath) { @@ -159,8 +155,8 @@ public static final String formatMetricDescriptorPathName( } /** - * Formats a string containing the fully-qualified path to represent - * a monitored_resource_descriptor resource. + * Formats a string containing the fully-qualified path to represent a + * monitored_resource_descriptor resource. */ public static final String formatMonitoredResourceDescriptorName( String project, String monitoredResourceDescriptor) { @@ -169,17 +165,14 @@ public static final String formatMonitoredResourceDescriptorName( "monitored_resource_descriptor", monitoredResourceDescriptor); } - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - */ + /** Parses the project from the given fully-qualified path which represents a project resource. */ public static final String parseProjectFromProjectName(String projectName) { return PROJECT_PATH_TEMPLATE.parse(projectName).get("project"); } /** - * Parses the project from the given fully-qualified path which - * represents a metricDescriptorPath resource. + * Parses the project from the given fully-qualified path which represents a metricDescriptorPath + * resource. */ public static final String parseProjectFromMetricDescriptorPathName( String metricDescriptorPathName) { @@ -187,8 +180,8 @@ public static final String parseProjectFromMetricDescriptorPathName( } /** - * Parses the metric_descriptor_path from the given fully-qualified path which - * represents a metricDescriptorPath resource. + * Parses the metric_descriptor_path from the given fully-qualified path which represents a + * metricDescriptorPath resource. */ public static final String parseMetricDescriptorPathFromMetricDescriptorPathName( String metricDescriptorPathName) { @@ -198,8 +191,8 @@ public static final String parseMetricDescriptorPathFromMetricDescriptorPathName } /** - * Parses the project from the given fully-qualified path which - * represents a monitoredResourceDescriptor resource. + * Parses the project from the given fully-qualified path which represents a + * monitoredResourceDescriptor resource. */ public static final String parseProjectFromMonitoredResourceDescriptorName( String monitoredResourceDescriptorName) { @@ -209,8 +202,8 @@ public static final String parseProjectFromMonitoredResourceDescriptorName( } /** - * Parses the monitored_resource_descriptor from the given fully-qualified path which - * represents a monitoredResourceDescriptor resource. + * Parses the monitored_resource_descriptor from the given fully-qualified path which represents a + * monitoredResourceDescriptor resource. */ public static final String parseMonitoredResourceDescriptorFromMonitoredResourceDescriptorName( String monitoredResourceDescriptorName) { @@ -219,26 +212,22 @@ public static final String parseMonitoredResourceDescriptorFromMonitoredResource .get("monitored_resource_descriptor"); } - /** - * Constructs an instance of MetricServiceApi with default settings. - */ + /** Constructs an instance of MetricServiceApi with default settings. */ public static final MetricServiceApi create() throws IOException { return create(MetricServiceSettings.defaultBuilder().build()); } /** - * Constructs an instance of MetricServiceApi, using the given settings. - * The channels are created based on the settings passed in, or defaults for any - * settings that are not set. + * Constructs an instance of MetricServiceApi, using the given settings. The channels are created + * based on the settings passed in, or defaults for any settings that are not set. */ public static final MetricServiceApi create(MetricServiceSettings settings) throws IOException { return new MetricServiceApi(settings); } /** - * Constructs an instance of MetricServiceApi, using the given settings. - * This is protected so that it easy to make a subclass, but otherwise, the static - * factory methods should be preferred. + * Constructs an instance of MetricServiceApi, using the given settings. This is protected so that + * it easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected MetricServiceApi(MetricServiceSettings settings) throws IOException { this.settings = settings; @@ -299,9 +288,11 @@ public final MetricServiceSettings getSettings() { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. + * Lists monitored resource descriptors that match a filter. This method does not require a + * Stackdriver account. + * + *

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -313,14 +304,11 @@ public final MetricServiceSettings getSettings() {
    * 
* * @param name The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param filter An optional [filter](/monitoring/api/v3/filters) describing - * the descriptors to be returned. The filter can reference - * the descriptor's type and labels. For example, the - * following filter returns only Google Compute Engine descriptors - * that have an `id` label: - * - * resource.type = starts_with("gce_") AND resource.label:id + * `"projects/{project_id_or_number}"`. + * @param filter An optional [filter](/monitoring/api/v3/filters) describing the descriptors to be + * returned. The filter can reference the descriptor's type and labels. For example, the + * following filter returns only Google Compute Engine descriptors that have an `id` label: + *

resource.type = starts_with("gce_") AND resource.label:id * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final PagedListResponse< @@ -338,9 +326,11 @@ public final MetricServiceSettings getSettings() { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account. + * Lists monitored resource descriptors that match a filter. This method does not require a + * Stackdriver account. + * + *

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -367,9 +357,11 @@ public final MetricServiceSettings getSettings() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account.
+   * Lists monitored resource descriptors that match a filter. This method does not require a
+   * Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -397,9 +389,11 @@ public final MetricServiceSettings getSettings() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists monitored resource descriptors that match a filter. This method does not require a Stackdriver account.
+   * Lists monitored resource descriptors that match a filter. This method does not require a
+   * Stackdriver account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -431,9 +425,11 @@ public final MetricServiceSettings getSettings() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Gets a single monitored resource descriptor. This method does not require a Stackdriver account.
+   * Gets a single monitored resource descriptor. This method does not require a Stackdriver
+   * account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatMonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]");
@@ -441,10 +437,9 @@ public final MetricServiceSettings getSettings() {
    * }
    * 
* - * @param name The monitored resource descriptor to get. The format is - * `"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}"`. - * The `{resource_type}` is a predefined type, such as - * `cloudsql_database`. + * @param name The monitored resource descriptor to get. The format is + * `"projects/{project_id_or_number}/monitoredResourceDescriptors/{resource_type}"`. The + * `{resource_type}` is a predefined type, such as `cloudsql_database`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final MonitoredResourceDescriptor getMonitoredResourceDescriptor(String name) { @@ -456,9 +451,11 @@ public final MonitoredResourceDescriptor getMonitoredResourceDescriptor(String n // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets a single monitored resource descriptor. This method does not require a Stackdriver account. + * Gets a single monitored resource descriptor. This method does not require a Stackdriver + * account. + * + *

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatMonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]");
@@ -479,9 +476,11 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor(
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Gets a single monitored resource descriptor. This method does not require a Stackdriver account.
+   * Gets a single monitored resource descriptor. This method does not require a Stackdriver
+   * account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatMonitoredResourceDescriptorName("[PROJECT]", "[MONITORED_RESOURCE_DESCRIPTOR]");
@@ -501,9 +500,11 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor(
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists metric descriptors that match a filter. This method does not require a Stackdriver account.
+   * Lists metric descriptors that match a filter. This method does not require a Stackdriver
+   * account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -515,15 +516,12 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor(
    * 
* * @param name The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param filter If this field is empty, all custom and - * system-defined metric descriptors are returned. - * Otherwise, the [filter](/monitoring/api/v3/filters) - * specifies which metric descriptors are to be - * returned. For example, the following filter matches all - * [custom metrics](/monitoring/custom-metrics): - * - * metric.type = starts_with("custom.googleapis.com/") + * `"projects/{project_id_or_number}"`. + * @param filter If this field is empty, all custom and system-defined metric descriptors are + * returned. Otherwise, the [filter](/monitoring/api/v3/filters) specifies which metric + * descriptors are to be returned. For example, the following filter matches all [custom + * metrics](/monitoring/custom-metrics): + *

metric.type = starts_with("custom.googleapis.com/") * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final PagedListResponse< @@ -537,9 +535,11 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor( // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Lists metric descriptors that match a filter. This method does not require a Stackdriver account. + * Lists metric descriptors that match a filter. This method does not require a Stackdriver + * account. + * + *

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -565,9 +565,11 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor(
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists metric descriptors that match a filter. This method does not require a Stackdriver account.
+   * Lists metric descriptors that match a filter. This method does not require a Stackdriver
+   * account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -594,9 +596,11 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor(
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Lists metric descriptors that match a filter. This method does not require a Stackdriver account.
+   * Lists metric descriptors that match a filter. This method does not require a Stackdriver
+   * account.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -629,7 +633,8 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor(
   /**
    * Gets a single metric descriptor. This method does not require a Stackdriver account.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]");
@@ -638,9 +643,8 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor(
    * 
* * @param name The metric descriptor on which to execute the request. The format is - * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. - * An example value of `{metric_id}` is - * `"compute.googleapis.com/instance/disk/read_bytes_count"`. + * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. An example value of + * `{metric_id}` is `"compute.googleapis.com/instance/disk/read_bytes_count"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final MetricDescriptor getMetricDescriptor(String name) { @@ -654,7 +658,8 @@ public final MetricDescriptor getMetricDescriptor(String name) { /** * Gets a single metric descriptor. This method does not require a Stackdriver account. * - * Sample code: + *

Sample code: + * *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]");
@@ -676,7 +681,8 @@ private final MetricDescriptor getMetricDescriptor(GetMetricDescriptorRequest re
   /**
    * Gets a single metric descriptor. This method does not require a Stackdriver account.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]");
@@ -696,11 +702,11 @@ private final MetricDescriptor getMetricDescriptor(GetMetricDescriptorRequest re
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Creates a new metric descriptor.
-   * User-created metric descriptors define
-   * [custom metrics](/monitoring/custom-metrics).
+   * Creates a new metric descriptor. User-created metric descriptors define [custom
+   * metrics](/monitoring/custom-metrics).
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -710,9 +716,8 @@ private final MetricDescriptor getMetricDescriptor(GetMetricDescriptorRequest re
    * 
* * @param name The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param metricDescriptor The new [custom metric](/monitoring/custom-metrics) - * descriptor. + * `"projects/{project_id_or_number}"`. + * @param metricDescriptor The new [custom metric](/monitoring/custom-metrics) descriptor. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final MetricDescriptor createMetricDescriptor( @@ -728,11 +733,11 @@ public final MetricDescriptor createMetricDescriptor( // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Creates a new metric descriptor. - * User-created metric descriptors define - * [custom metrics](/monitoring/custom-metrics). + * Creates a new metric descriptor. User-created metric descriptors define [custom + * metrics](/monitoring/custom-metrics). + * + *

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -754,11 +759,11 @@ public final MetricDescriptor createMetricDescriptor(CreateMetricDescriptorReque
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Creates a new metric descriptor.
-   * User-created metric descriptors define
-   * [custom metrics](/monitoring/custom-metrics).
+   * Creates a new metric descriptor. User-created metric descriptors define [custom
+   * metrics](/monitoring/custom-metrics).
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -780,10 +785,11 @@ public final MetricDescriptor createMetricDescriptor(CreateMetricDescriptorReque
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Deletes a metric descriptor. Only user-created
-   * [custom metrics](/monitoring/custom-metrics) can be deleted.
+   * Deletes a metric descriptor. Only user-created [custom metrics](/monitoring/custom-metrics) can
+   * be deleted.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]");
@@ -792,9 +798,8 @@ public final MetricDescriptor createMetricDescriptor(CreateMetricDescriptorReque
    * 
* * @param name The metric descriptor on which to execute the request. The format is - * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. - * An example of `{metric_id}` is: - * `"custom.googleapis.com/my_test_metric"`. + * `"projects/{project_id_or_number}/metricDescriptors/{metric_id}"`. An example of + * `{metric_id}` is: `"custom.googleapis.com/my_test_metric"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final void deleteMetricDescriptor(String name) { @@ -806,10 +811,11 @@ public final void deleteMetricDescriptor(String name) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Deletes a metric descriptor. Only user-created - * [custom metrics](/monitoring/custom-metrics) can be deleted. + * Deletes a metric descriptor. Only user-created [custom metrics](/monitoring/custom-metrics) can + * be deleted. + * + *

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]");
@@ -829,10 +835,11 @@ private final void deleteMetricDescriptor(DeleteMetricDescriptorRequest request)
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Deletes a metric descriptor. Only user-created
-   * [custom metrics](/monitoring/custom-metrics) can be deleted.
+   * Deletes a metric descriptor. Only user-created [custom metrics](/monitoring/custom-metrics) can
+   * be deleted.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]");
@@ -853,7 +860,8 @@ public final ApiCallable deleteMetricDescr
   /**
    * Lists time series that match a filter. This method does not require a Stackdriver account.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -888,7 +896,8 @@ public final ApiCallable deleteMetricDescr
   /**
    * Lists time series that match a filter. This method does not require a Stackdriver account.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -924,7 +933,8 @@ public final ApiCallable deleteMetricDescr
   /**
    * Lists time series that match a filter. This method does not require a Stackdriver account.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -962,12 +972,12 @@ public final ApiCallable listTime
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Creates or adds data to one or more time series.
-   * The response is empty if all time series in the request were written.
-   * If any time series could not be written, a corresponding failure message is
-   * included in the error response.
+   * Creates or adds data to one or more time series. The response is empty if all time series in
+   * the request were written. If any time series could not be written, a corresponding failure
+   * message is included in the error response.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -977,12 +987,11 @@ public final ApiCallable listTime
    * 
* * @param name The project on which to execute the request. The format is - * `"projects/{project_id_or_number}"`. - * @param timeSeries The new data to be added to a list of time series. - * Adds at most one data point to each of several time series. The new data - * point must be more recent than any other point in its time series. Each - * `TimeSeries` value must fully specify a unique time series by supplying - * all label values for the metric and the monitored resource. + * `"projects/{project_id_or_number}"`. + * @param timeSeries The new data to be added to a list of time series. Adds at most one data + * point to each of several time series. The new data point must be more recent than any other + * point in its time series. Each `TimeSeries` value must fully specify a unique time series + * by supplying all label values for the metric and the monitored resource. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final void createTimeSeries(String name, List timeSeries) { @@ -994,12 +1003,12 @@ public final void createTimeSeries(String name, List timeSeries) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Creates or adds data to one or more time series. - * The response is empty if all time series in the request were written. - * If any time series could not be written, a corresponding failure message is - * included in the error response. + * Creates or adds data to one or more time series. The response is empty if all time series in + * the request were written. If any time series could not be written, a corresponding failure + * message is included in the error response. + * + *

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
@@ -1021,12 +1030,12 @@ public final void createTimeSeries(CreateTimeSeriesRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Creates or adds data to one or more time series.
-   * The response is empty if all time series in the request were written.
-   * If any time series could not be written, a corresponding failure message is
-   * included in the error response.
+   * Creates or adds data to one or more time series. The response is empty if all time series in
+   * the request were written. If any time series could not be written, a corresponding failure
+   * message is included in the error response.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceSettings.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceSettings.java
index dd1ec8c244ca..c7c89badb66d 100644
--- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceSettings.java
+++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceSettings.java
@@ -16,7 +16,6 @@
 import com.google.api.MetricDescriptor;
 import com.google.api.MonitoredResourceDescriptor;
 import com.google.api.gax.core.ConnectionSettings;
-import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -57,15 +56,14 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (monitoring.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (monitoring.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of getMonitoredResourceDescriptor to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of getMonitoredResourceDescriptor to 30 seconds: * *

  * 
@@ -79,25 +77,17 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class MetricServiceSettings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "monitoring.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder().build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -125,9 +115,7 @@ public class MetricServiceSettings extends ServiceApiSettings {
       listTimeSeriesSettings;
   private final SimpleCallSettings createTimeSeriesSettings;
 
-  /**
-   * Returns the object with the settings used for calls to listMonitoredResourceDescriptors.
-   */
+  /** Returns the object with the settings used for calls to listMonitoredResourceDescriptors. */
   public PageStreamingCallSettings<
           ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
           MonitoredResourceDescriptor>
@@ -135,99 +123,73 @@ public class MetricServiceSettings extends ServiceApiSettings {
     return listMonitoredResourceDescriptorsSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to getMonitoredResourceDescriptor.
-   */
+  /** Returns the object with the settings used for calls to getMonitoredResourceDescriptor. */
   public SimpleCallSettings
       getMonitoredResourceDescriptorSettings() {
     return getMonitoredResourceDescriptorSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to listMetricDescriptors.
-   */
+  /** Returns the object with the settings used for calls to listMetricDescriptors. */
   public PageStreamingCallSettings<
           ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor>
       listMetricDescriptorsSettings() {
     return listMetricDescriptorsSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to getMetricDescriptor.
-   */
+  /** Returns the object with the settings used for calls to getMetricDescriptor. */
   public SimpleCallSettings
       getMetricDescriptorSettings() {
     return getMetricDescriptorSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to createMetricDescriptor.
-   */
+  /** Returns the object with the settings used for calls to createMetricDescriptor. */
   public SimpleCallSettings
       createMetricDescriptorSettings() {
     return createMetricDescriptorSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to deleteMetricDescriptor.
-   */
+  /** Returns the object with the settings used for calls to deleteMetricDescriptor. */
   public SimpleCallSettings deleteMetricDescriptorSettings() {
     return deleteMetricDescriptorSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to listTimeSeries.
-   */
+  /** Returns the object with the settings used for calls to listTimeSeries. */
   public PageStreamingCallSettings
       listTimeSeriesSettings() {
     return listTimeSeriesSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to createTimeSeries.
-   */
+  /** Returns the object with the settings used for calls to createTimeSeries. */
   public SimpleCallSettings createTimeSeriesSettings() {
     return createTimeSeriesSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -375,9 +337,7 @@ public Iterable extractResources(ListTimeSeriesResponse payload) {
             }
           };
 
-  /**
-   * Builder for MetricServiceSettings.
-   */
+  /** Builder for MetricServiceSettings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -598,18 +558,15 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listMonitoredResourceDescriptors.
-     */
+    /** Returns the builder for the settings used for calls to listMonitoredResourceDescriptors. */
     public PageStreamingCallSettings.Builder<
             ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
             MonitoredResourceDescriptor>
@@ -617,60 +574,46 @@ public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) thr
       return listMonitoredResourceDescriptorsSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to getMonitoredResourceDescriptor.
-     */
+    /** Returns the builder for the settings used for calls to getMonitoredResourceDescriptor. */
     public SimpleCallSettings.Builder<
             GetMonitoredResourceDescriptorRequest, MonitoredResourceDescriptor>
         getMonitoredResourceDescriptorSettings() {
       return getMonitoredResourceDescriptorSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listMetricDescriptors.
-     */
+    /** Returns the builder for the settings used for calls to listMetricDescriptors. */
     public PageStreamingCallSettings.Builder<
             ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor>
         listMetricDescriptorsSettings() {
       return listMetricDescriptorsSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to getMetricDescriptor.
-     */
+    /** Returns the builder for the settings used for calls to getMetricDescriptor. */
     public SimpleCallSettings.Builder
         getMetricDescriptorSettings() {
       return getMetricDescriptorSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to createMetricDescriptor.
-     */
+    /** Returns the builder for the settings used for calls to createMetricDescriptor. */
     public SimpleCallSettings.Builder
         createMetricDescriptorSettings() {
       return createMetricDescriptorSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to deleteMetricDescriptor.
-     */
+    /** Returns the builder for the settings used for calls to deleteMetricDescriptor. */
     public SimpleCallSettings.Builder
         deleteMetricDescriptorSettings() {
       return deleteMetricDescriptorSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listTimeSeries.
-     */
+    /** Returns the builder for the settings used for calls to listTimeSeries. */
     public PageStreamingCallSettings.Builder<
             ListTimeSeriesRequest, ListTimeSeriesResponse, TimeSeries>
         listTimeSeriesSettings() {
       return listTimeSeriesSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to createTimeSeries.
-     */
+    /** Returns the builder for the settings used for calls to createTimeSeries. */
     public SimpleCallSettings.Builder createTimeSeriesSettings() {
       return createTimeSeriesSettings;
     }
diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/package-info.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/package-info.java
index d37c7e7690ff..9d1a0e61adb7 100644
--- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/package-info.java
+++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/package-info.java
@@ -15,26 +15,22 @@
 /**
  * A client to Stackdriver Monitoring API.
  *
- * The interfaces provided are listed below, along with a usage sample
+ * 

The interfaces provided are listed below, along with a usage sample * - * =============== - * GroupServiceApi - * =============== + *

=============== GroupServiceApi =============== * - * Service Description: The Group API lets you inspect and manage your + *

Service Description: The Group API lets you inspect and manage your * [groups](google.monitoring.v3.Group). * - * A group is a named filter that is used to identify - * a collection of monitored resources. Groups are typically used to - * mirror the physical and/or logical topology of the environment. - * Because group membership is computed dynamically, monitored - * resources that are started in the future are automatically placed - * in matching groups. By using a group to name monitored resources in, - * for example, an alert policy, the target of that alert policy is - * updated automatically as monitored resources are added and removed - * from the infrastructure. - * - * Sample for GroupServiceApi: + *

A group is a named filter that is used to identify a collection of monitored resources. Groups + * are typically used to mirror the physical and/or logical topology of the environment. Because + * group membership is computed dynamically, monitored resources that are started in the future are + * automatically placed in matching groups. By using a group to name monitored resources in, for + * example, an alert policy, the target of that alert policy is updated automatically as monitored + * resources are added and removed from the infrastructure. + * + *

Sample for GroupServiceApi: + * *

  * 
  * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
@@ -44,14 +40,13 @@
  * 
  * 
* - * ================ - * MetricServiceApi - * ================ + * ================ MetricServiceApi ================ + * + *

Service Description: Manages metric descriptors, monitored resource descriptors, and time + * series data. * - * Service Description: Manages metric descriptors, monitored resource descriptors, and - * time series data. + *

Sample for MetricServiceApi: * - * Sample for MetricServiceApi: *

  * 
  * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
@@ -61,15 +56,14 @@
  * 
  * 
* - * ========================== - * AgentTranslationServiceApi - * ========================== + * ========================== AgentTranslationServiceApi ========================== * - * Service Description: The AgentTranslation API allows `collectd`-based agents to - * write time series data to Cloud Monitoring. - * See [google.monitoring.v3.MetricService.CreateTimeSeries] instead. + *

Service Description: The AgentTranslation API allows `collectd`-based agents to write time + * series data to Cloud Monitoring. See [google.monitoring.v3.MetricService.CreateTimeSeries] + * instead. + * + *

Sample for AgentTranslationServiceApi: * - * Sample for AgentTranslationServiceApi: *

  * 
  * try (AgentTranslationServiceApi agentTranslationServiceApi = AgentTranslationServiceApi.create()) {
@@ -81,6 +75,5 @@
  * }
  * 
  * 
- * */ package com.google.cloud.monitoring.spi.v3; diff --git a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceTest.java b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceTest.java index 21921b188880..5e622b537d0e 100644 --- a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceTest.java +++ b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceTest.java @@ -15,10 +15,8 @@ package com.google.cloud.monitoring.spi.v3; import com.google.api.MonitoredResource; -import com.google.api.gax.core.PagedListResponse; import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; -import com.google.common.collect.Lists; import com.google.monitoring.v3.CollectdPayload; import com.google.monitoring.v3.CreateCollectdTimeSeriesRequest; import com.google.protobuf.Empty; diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherApi.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherApi.java index 717563c89914..be922966c3c3 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherApi.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherApi.java @@ -56,32 +56,31 @@ *
*
* - *

Note: close() needs to be called on the publisherApi object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + *

Note: close() needs to be called on the publisherApi object to clean up resources such as + * threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * - *

This class can be customized by passing in a custom instance of PublisherSettings to - * create(). For example: + *

This class can be customized by passing in a custom instance of PublisherSettings to create(). + * For example: * *

  * 
@@ -124,68 +123,49 @@ public class PublisherApi implements AutoCloseable {
   private static final PathTemplate TOPIC_PATH_TEMPLATE =
       PathTemplate.createWithoutUrlEncoding("projects/{project}/topics/{topic}");
 
-  /**
-   * Formats a string containing the fully-qualified path to represent
-   * a project resource.
-   */
+  /** Formats a string containing the fully-qualified path to represent a project resource. */
   public static final String formatProjectName(String project) {
     return PROJECT_PATH_TEMPLATE.instantiate("project", project);
   }
 
-  /**
-   * Formats a string containing the fully-qualified path to represent
-   * a topic resource.
-   */
+  /** Formats a string containing the fully-qualified path to represent a topic resource. */
   public static final String formatTopicName(String project, String topic) {
     return TOPIC_PATH_TEMPLATE.instantiate(
         "project", project,
         "topic", topic);
   }
 
-  /**
-   * Parses the project from the given fully-qualified path which
-   * represents a project resource.
-   */
+  /** Parses the project from the given fully-qualified path which represents a project resource. */
   public static final String parseProjectFromProjectName(String projectName) {
     return PROJECT_PATH_TEMPLATE.parse(projectName).get("project");
   }
 
-  /**
-   * Parses the project from the given fully-qualified path which
-   * represents a topic resource.
-   */
+  /** Parses the project from the given fully-qualified path which represents a topic resource. */
   public static final String parseProjectFromTopicName(String topicName) {
     return TOPIC_PATH_TEMPLATE.parse(topicName).get("project");
   }
 
-  /**
-   * Parses the topic from the given fully-qualified path which
-   * represents a topic resource.
-   */
+  /** Parses the topic from the given fully-qualified path which represents a topic resource. */
   public static final String parseTopicFromTopicName(String topicName) {
     return TOPIC_PATH_TEMPLATE.parse(topicName).get("topic");
   }
 
-  /**
-   * Constructs an instance of PublisherApi with default settings.
-   */
+  /** Constructs an instance of PublisherApi with default settings. */
   public static final PublisherApi create() throws IOException {
     return create(PublisherSettings.defaultBuilder().build());
   }
 
   /**
-   * Constructs an instance of PublisherApi, using the given settings.
-   * The channels are created based on the settings passed in, or defaults for any
-   * settings that are not set.
+   * Constructs an instance of PublisherApi, using the given settings. The channels are created
+   * based on the settings passed in, or defaults for any settings that are not set.
    */
   public static final PublisherApi create(PublisherSettings settings) throws IOException {
     return new PublisherApi(settings);
   }
 
   /**
-   * Constructs an instance of PublisherApi, using the given settings.
-   * This is protected so that it easy to make a subclass, but otherwise, the static
-   * factory methods should be preferred.
+   * Constructs an instance of PublisherApi, using the given settings. This is protected so that it
+   * easy to make a subclass, but otherwise, the static factory methods should be preferred.
    */
   protected PublisherApi(PublisherSettings settings) throws IOException {
     this.settings = settings;
@@ -247,7 +227,8 @@ public final PublisherSettings getSettings() {
   /**
    * Creates the given topic with the given name.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedName = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -256,11 +237,10 @@ public final PublisherSettings getSettings() {
    * 
* * @param name The name of the topic. It must have the format - * `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, - * and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), - * underscores (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent - * signs (`%`). It must be between 3 and 255 characters in length, and it - * must not start with `"goog"`. + * `"projects/{project}/topics/{topic}"`. `{topic}` must start with a letter, and contain only + * letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), + * tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters in + * length, and it must not start with `"goog"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final Topic createTopic(String name) { @@ -273,7 +253,8 @@ public final Topic createTopic(String name) { /** * Creates the given topic with the given name. * - * Sample code: + *

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedName = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -295,7 +276,8 @@ private final Topic createTopic(Topic request) {
   /**
    * Creates the given topic with the given name.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedName = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -314,11 +296,12 @@ public final ApiCallable createTopicCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic
-   * does not exist. The message payload must not be empty; it must contain
-   *  either a non-empty data field, or at least one attribute.
+   * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. The
+   * message payload must not be empty; it must contain either a non-empty data field, or at least
+   * one attribute.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -344,11 +327,12 @@ public final PublishResponse publish(String topic, List messages)
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic
-   * does not exist. The message payload must not be empty; it must contain
-   *  either a non-empty data field, or at least one attribute.
+   * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. The
+   * message payload must not be empty; it must contain either a non-empty data field, or at least
+   * one attribute.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -374,11 +358,12 @@ public final PublishResponse publish(PublishRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic
-   * does not exist. The message payload must not be empty; it must contain
-   *  either a non-empty data field, or at least one attribute.
+   * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. The
+   * message payload must not be empty; it must contain either a non-empty data field, or at least
+   * one attribute.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -405,7 +390,8 @@ public final ApiCallable publishCallable() {
   /**
    * Gets the configuration of a topic.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -426,7 +412,8 @@ public final Topic getTopic(String topic) {
   /**
    * Gets the configuration of a topic.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -448,7 +435,8 @@ private final Topic getTopic(GetTopicRequest request) {
   /**
    * Gets the configuration of a topic.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -469,7 +457,8 @@ public final ApiCallable getTopicCallable() {
   /**
    * Lists matching topics.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedProject = PublisherApi.formatProjectName("[PROJECT]");
@@ -493,7 +482,8 @@ public final PagedListResponse lis
   /**
    * Lists matching topics.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedProject = PublisherApi.formatProjectName("[PROJECT]");
@@ -518,7 +508,8 @@ public final PagedListResponse lis
   /**
    * Lists matching topics.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedProject = PublisherApi.formatProjectName("[PROJECT]");
@@ -543,7 +534,8 @@ public final PagedListResponse lis
   /**
    * Lists matching topics.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedProject = PublisherApi.formatProjectName("[PROJECT]");
@@ -573,7 +565,8 @@ public final ApiCallable listTopicsCallab
   /**
    * Lists the name of the subscriptions for this topic.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -599,7 +592,8 @@ public final ApiCallable listTopicsCallab
   /**
    * Lists the name of the subscriptions for this topic.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -625,7 +619,8 @@ public final ApiCallable listTopicsCallab
   /**
    * Lists the name of the subscriptions for this topic.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -651,7 +646,8 @@ public final ApiCallable listTopicsCallab
   /**
    * Lists the name of the subscriptions for this topic.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -680,13 +676,13 @@ public final ApiCallable listTopicsCallab
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic
-   * does not exist. After a topic is deleted, a new topic may be created with
-   * the same name; this is an entirely new topic with none of the old
-   * configuration or subscriptions. Existing subscriptions to this topic are
+   * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a
+   * topic is deleted, a new topic may be created with the same name; this is an entirely new topic
+   * with none of the old configuration or subscriptions. Existing subscriptions to this topic are
    * not deleted, but their `topic` field is set to `_deleted-topic_`.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -705,13 +701,13 @@ public final void deleteTopic(String topic) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic
-   * does not exist. After a topic is deleted, a new topic may be created with
-   * the same name; this is an entirely new topic with none of the old
-   * configuration or subscriptions. Existing subscriptions to this topic are
+   * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a
+   * topic is deleted, a new topic may be created with the same name; this is an entirely new topic
+   * with none of the old configuration or subscriptions. Existing subscriptions to this topic are
    * not deleted, but their `topic` field is set to `_deleted-topic_`.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -731,13 +727,13 @@ private final void deleteTopic(DeleteTopicRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic
-   * does not exist. After a topic is deleted, a new topic may be created with
-   * the same name; this is an entirely new topic with none of the old
-   * configuration or subscriptions. Existing subscriptions to this topic are
+   * Deletes the topic with the given name. Returns `NOT_FOUND` if the topic does not exist. After a
+   * topic is deleted, a new topic may be created with the same name; this is an entirely new topic
+   * with none of the old configuration or subscriptions. Existing subscriptions to this topic are
    * not deleted, but their `topic` field is set to `_deleted-topic_`.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -756,10 +752,10 @@ public final ApiCallable deleteTopicCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Sets the access control policy on the specified resource. Replaces any
-   * existing policy.
+   * Sets the access control policy on the specified resource. Replaces any existing policy.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedResource = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -768,12 +764,11 @@ public final ApiCallable deleteTopicCallable() {
    * }
    * 
* - * @param resource REQUIRED: The resource for which policy is being specified. - * Resource is usually specified as a path, such as, - * projects/{project}/zones/{zone}/disks/{disk}. - * @param policy REQUIRED: The complete policy to be applied to the 'resource'. The size of - * the policy is limited to a few 10s of KB. An empty policy is in general a - * valid policy but certain services (like Projects) might reject them. + * @param resource REQUIRED: The resource for which policy is being specified. Resource is usually + * specified as a path, such as, projects/{project}/zones/{zone}/disks/{disk}. + * @param policy REQUIRED: The complete policy to be applied to the 'resource'. The size of the + * policy is limited to a few 10s of KB. An empty policy is in general a valid policy but + * certain services (like Projects) might reject them. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final Policy setIamPolicy(String resource, Policy policy) { @@ -785,10 +780,10 @@ public final Policy setIamPolicy(String resource, Policy policy) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Sets the access control policy on the specified resource. Replaces any - * existing policy. + * Sets the access control policy on the specified resource. Replaces any existing policy. + * + *

Sample code: * - * Sample code: *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedResource = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -810,10 +805,10 @@ public final Policy setIamPolicy(SetIamPolicyRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Sets the access control policy on the specified resource. Replaces any
-   * existing policy.
+   * Sets the access control policy on the specified resource. Replaces any existing policy.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedResource = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -834,10 +829,11 @@ public final ApiCallable setIamPolicyCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Gets the access control policy for a resource. Is empty if the
-   * policy or the resource does not exist.
+   * Gets the access control policy for a resource. Is empty if the policy or the resource does not
+   * exist.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedResource = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -845,8 +841,8 @@ public final ApiCallable setIamPolicyCallable() {
    * }
    * 
* - * @param resource REQUIRED: The resource for which policy is being requested. Resource - * is usually specified as a path, such as, projects/{project}. + * @param resource REQUIRED: The resource for which policy is being requested. Resource is usually + * specified as a path, such as, projects/{project}. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final Policy getIamPolicy(String resource) { @@ -857,10 +853,11 @@ public final Policy getIamPolicy(String resource) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets the access control policy for a resource. Is empty if the - * policy or the resource does not exist. + * Gets the access control policy for a resource. Is empty if the policy or the resource does not + * exist. + * + *

Sample code: * - * Sample code: *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedResource = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -880,10 +877,11 @@ private final Policy getIamPolicy(GetIamPolicyRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Gets the access control policy for a resource. Is empty if the
-   * policy or the resource does not exist.
+   * Gets the access control policy for a resource. Is empty if the policy or the resource does not
+   * exist.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedResource = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -904,7 +902,8 @@ public final ApiCallable getIamPolicyCallable() {
   /**
    * Returns permissions that a caller has on the specified resource.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedResource = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -913,10 +912,10 @@ public final ApiCallable getIamPolicyCallable() {
    * }
    * 
* - * @param resource REQUIRED: The resource for which policy detail is being requested. - * Resource is usually specified as a path, such as, projects/{project}. + * @param resource REQUIRED: The resource for which policy detail is being requested. Resource is + * usually specified as a path, such as, projects/{project}. * @param permissions The set of permissions to check for the 'resource'. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. + * wildcards (such as '*' or 'storage.*') are not allowed. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final TestIamPermissionsResponse testIamPermissions( @@ -934,7 +933,8 @@ public final TestIamPermissionsResponse testIamPermissions( /** * Returns permissions that a caller has on the specified resource. * - * Sample code: + *

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedResource = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
@@ -958,7 +958,8 @@ public final TestIamPermissionsResponse testIamPermissions(TestIamPermissionsReq
   /**
    * Returns permissions that a caller has on the specified resource.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (PublisherApi publisherApi = PublisherApi.create()) {
    *   String formattedResource = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]");
diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherSettings.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherSettings.java
index 53089e87744f..8c50b07d0d06 100644
--- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherSettings.java
+++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherSettings.java
@@ -14,7 +14,6 @@
 package com.google.cloud.pubsub.spi.v1;
 
 import com.google.api.gax.core.ConnectionSettings;
-import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.BundlingCallSettings;
@@ -65,15 +64,14 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (pubsub.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (pubsub.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of createTopic to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of createTopic to 30 seconds: * *

  * 
@@ -87,28 +85,20 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class PublisherSettings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "pubsub.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder()
           .add("https://www.googleapis.com/auth/cloud-platform")
           .add("https://www.googleapis.com/auth/pubsub")
           .build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -130,111 +120,81 @@ public class PublisherSettings extends ServiceApiSettings {
   private final SimpleCallSettings
       testIamPermissionsSettings;
 
-  /**
-   * Returns the object with the settings used for calls to createTopic.
-   */
+  /** Returns the object with the settings used for calls to createTopic. */
   public SimpleCallSettings createTopicSettings() {
     return createTopicSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to publish.
-   */
+  /** Returns the object with the settings used for calls to publish. */
   public BundlingCallSettings publishSettings() {
     return publishSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to getTopic.
-   */
+  /** Returns the object with the settings used for calls to getTopic. */
   public SimpleCallSettings getTopicSettings() {
     return getTopicSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to listTopics.
-   */
+  /** Returns the object with the settings used for calls to listTopics. */
   public PageStreamingCallSettings
       listTopicsSettings() {
     return listTopicsSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to listTopicSubscriptions.
-   */
+  /** Returns the object with the settings used for calls to listTopicSubscriptions. */
   public PageStreamingCallSettings<
           ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String>
       listTopicSubscriptionsSettings() {
     return listTopicSubscriptionsSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to deleteTopic.
-   */
+  /** Returns the object with the settings used for calls to deleteTopic. */
   public SimpleCallSettings deleteTopicSettings() {
     return deleteTopicSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to setIamPolicy.
-   */
+  /** Returns the object with the settings used for calls to setIamPolicy. */
   public SimpleCallSettings setIamPolicySettings() {
     return setIamPolicySettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to getIamPolicy.
-   */
+  /** Returns the object with the settings used for calls to getIamPolicy. */
   public SimpleCallSettings getIamPolicySettings() {
     return getIamPolicySettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to testIamPermissions.
-   */
+  /** Returns the object with the settings used for calls to testIamPermissions. */
   public SimpleCallSettings
       testIamPermissionsSettings() {
     return testIamPermissionsSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -397,9 +357,7 @@ public long countBytes(PublishRequest request) {
         }
       };
 
-  /**
-   * Builder for PublisherSettings.
-   */
+  /** Builder for PublisherSettings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -639,77 +597,58 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to createTopic.
-     */
+    /** Returns the builder for the settings used for calls to createTopic. */
     public SimpleCallSettings.Builder createTopicSettings() {
       return createTopicSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to publish.
-     */
+    /** Returns the builder for the settings used for calls to publish. */
     public BundlingCallSettings.Builder publishSettings() {
       return publishSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to getTopic.
-     */
+    /** Returns the builder for the settings used for calls to getTopic. */
     public SimpleCallSettings.Builder getTopicSettings() {
       return getTopicSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listTopics.
-     */
+    /** Returns the builder for the settings used for calls to listTopics. */
     public PageStreamingCallSettings.Builder
         listTopicsSettings() {
       return listTopicsSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listTopicSubscriptions.
-     */
+    /** Returns the builder for the settings used for calls to listTopicSubscriptions. */
     public PageStreamingCallSettings.Builder<
             ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String>
         listTopicSubscriptionsSettings() {
       return listTopicSubscriptionsSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to deleteTopic.
-     */
+    /** Returns the builder for the settings used for calls to deleteTopic. */
     public SimpleCallSettings.Builder deleteTopicSettings() {
       return deleteTopicSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to setIamPolicy.
-     */
+    /** Returns the builder for the settings used for calls to setIamPolicy. */
     public SimpleCallSettings.Builder setIamPolicySettings() {
       return setIamPolicySettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to getIamPolicy.
-     */
+    /** Returns the builder for the settings used for calls to getIamPolicy. */
     public SimpleCallSettings.Builder getIamPolicySettings() {
       return getIamPolicySettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to testIamPermissions.
-     */
+    /** Returns the builder for the settings used for calls to testIamPermissions. */
     public SimpleCallSettings.Builder
         testIamPermissionsSettings() {
       return testIamPermissionsSettings;
diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberApi.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberApi.java
index 1d2a33d77990..3505cd9d1825 100644
--- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberApi.java
+++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberApi.java
@@ -60,29 +60,28 @@
  * 
  * 
* - *

Note: close() needs to be called on the subscriberApi object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + *

Note: close() needs to be called on the subscriberApi object to clean up resources such as + * threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * *

This class can be customized by passing in a custom instance of SubscriberSettings to * create(). For example: @@ -130,94 +129,72 @@ public class SubscriberApi implements AutoCloseable { private static final PathTemplate TOPIC_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}/topics/{topic}"); - /** - * Formats a string containing the fully-qualified path to represent - * a project resource. - */ + /** Formats a string containing the fully-qualified path to represent a project resource. */ public static final String formatProjectName(String project) { return PROJECT_PATH_TEMPLATE.instantiate("project", project); } - /** - * Formats a string containing the fully-qualified path to represent - * a subscription resource. - */ + /** Formats a string containing the fully-qualified path to represent a subscription resource. */ public static final String formatSubscriptionName(String project, String subscription) { return SUBSCRIPTION_PATH_TEMPLATE.instantiate( "project", project, "subscription", subscription); } - /** - * Formats a string containing the fully-qualified path to represent - * a topic resource. - */ + /** Formats a string containing the fully-qualified path to represent a topic resource. */ public static final String formatTopicName(String project, String topic) { return TOPIC_PATH_TEMPLATE.instantiate( "project", project, "topic", topic); } - /** - * Parses the project from the given fully-qualified path which - * represents a project resource. - */ + /** Parses the project from the given fully-qualified path which represents a project resource. */ public static final String parseProjectFromProjectName(String projectName) { return PROJECT_PATH_TEMPLATE.parse(projectName).get("project"); } /** - * Parses the project from the given fully-qualified path which - * represents a subscription resource. + * Parses the project from the given fully-qualified path which represents a subscription + * resource. */ public static final String parseProjectFromSubscriptionName(String subscriptionName) { return SUBSCRIPTION_PATH_TEMPLATE.parse(subscriptionName).get("project"); } /** - * Parses the subscription from the given fully-qualified path which - * represents a subscription resource. + * Parses the subscription from the given fully-qualified path which represents a subscription + * resource. */ public static final String parseSubscriptionFromSubscriptionName(String subscriptionName) { return SUBSCRIPTION_PATH_TEMPLATE.parse(subscriptionName).get("subscription"); } - /** - * Parses the project from the given fully-qualified path which - * represents a topic resource. - */ + /** Parses the project from the given fully-qualified path which represents a topic resource. */ public static final String parseProjectFromTopicName(String topicName) { return TOPIC_PATH_TEMPLATE.parse(topicName).get("project"); } - /** - * Parses the topic from the given fully-qualified path which - * represents a topic resource. - */ + /** Parses the topic from the given fully-qualified path which represents a topic resource. */ public static final String parseTopicFromTopicName(String topicName) { return TOPIC_PATH_TEMPLATE.parse(topicName).get("topic"); } - /** - * Constructs an instance of SubscriberApi with default settings. - */ + /** Constructs an instance of SubscriberApi with default settings. */ public static final SubscriberApi create() throws IOException { return create(SubscriberSettings.defaultBuilder().build()); } /** - * Constructs an instance of SubscriberApi, using the given settings. - * The channels are created based on the settings passed in, or defaults for any - * settings that are not set. + * Constructs an instance of SubscriberApi, using the given settings. The channels are created + * based on the settings passed in, or defaults for any settings that are not set. */ public static final SubscriberApi create(SubscriberSettings settings) throws IOException { return new SubscriberApi(settings); } /** - * Constructs an instance of SubscriberApi, using the given settings. - * This is protected so that it easy to make a subclass, but otherwise, the static - * factory methods should be preferred. + * Constructs an instance of SubscriberApi, using the given settings. This is protected so that it + * easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected SubscriberApi(SubscriberSettings settings) throws IOException { this.settings = settings; @@ -275,15 +252,15 @@ public final SubscriberSettings getSettings() { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Creates a subscription to a given topic. - * If the subscription already exists, returns `ALREADY_EXISTS`. - * If the corresponding topic doesn't exist, returns `NOT_FOUND`. + * Creates a subscription to a given topic. If the subscription already exists, returns + * `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns `NOT_FOUND`. * - * If the name is not provided in the request, the server will assign a random - * name for this subscription on the same project as the topic. Note that - * for REST API requests, you must specify a name. + *

If the name is not provided in the request, the server will assign a random name for this + * subscription on the same project as the topic. Note that for REST API requests, you must + * specify a name. + * + *

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedName = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -295,36 +272,28 @@ public final SubscriberSettings getSettings() {
    * 
* * @param name The name of the subscription. It must have the format - * `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must - * start with a letter, and contain only letters (`[A-Za-z]`), numbers - * (`[0-9]`), dashes (`-`), underscores (`_`), periods (`.`), tildes (`~`), - * plus (`+`) or percent signs (`%`). It must be between 3 and 255 characters - * in length, and it must not start with `"goog"`. - * @param topic The name of the topic from which this subscription is receiving messages. - * The value of this field will be `_deleted-topic_` if the topic has been - * deleted. - * @param pushConfig If push delivery is used with this subscription, this field is - * used to configure it. An empty `pushConfig` signifies that the subscriber - * will pull and ack messages using API methods. + * `"projects/{project}/subscriptions/{subscription}"`. `{subscription}` must start with a + * letter, and contain only letters (`[A-Za-z]`), numbers (`[0-9]`), dashes (`-`), underscores + * (`_`), periods (`.`), tildes (`~`), plus (`+`) or percent signs (`%`). It must be between 3 + * and 255 characters in length, and it must not start with `"goog"`. + * @param topic The name of the topic from which this subscription is receiving messages. The + * value of this field will be `_deleted-topic_` if the topic has been deleted. + * @param pushConfig If push delivery is used with this subscription, this field is used to + * configure it. An empty `pushConfig` signifies that the subscriber will pull and ack + * messages using API methods. * @param ackDeadlineSeconds This value is the maximum time after a subscriber receives a message - * before the subscriber should acknowledge the message. After message - * delivery but before the ack deadline expires and before the message is - * acknowledged, it is an outstanding message and will not be delivered - * again during that time (on a best-effort basis). - * - * For pull subscriptions, this value is used as the initial value for the ack - * deadline. To override this value for a given message, call - * `ModifyAckDeadline` with the corresponding `ack_id` if using - * pull. - * The maximum custom deadline you can specify is 600 seconds (10 minutes). - * - * For push delivery, this value is also used to set the request timeout for - * the call to the push endpoint. - * - * If the subscriber never acknowledges the message, the Pub/Sub - * system will eventually redeliver the message. - * - * If this parameter is 0, a default value of 10 seconds is used. + * before the subscriber should acknowledge the message. After message delivery but before the + * ack deadline expires and before the message is acknowledged, it is an outstanding message + * and will not be delivered again during that time (on a best-effort basis). + *

For pull subscriptions, this value is used as the initial value for the ack deadline. To + * override this value for a given message, call `ModifyAckDeadline` with the corresponding + * `ack_id` if using pull. The maximum custom deadline you can specify is 600 seconds (10 + * minutes). + *

For push delivery, this value is also used to set the request timeout for the call to + * the push endpoint. + *

If the subscriber never acknowledges the message, the Pub/Sub system will eventually + * redeliver the message. + *

If this parameter is 0, a default value of 10 seconds is used. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final Subscription createSubscription( @@ -343,15 +312,15 @@ public final Subscription createSubscription( // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Creates a subscription to a given topic. - * If the subscription already exists, returns `ALREADY_EXISTS`. - * If the corresponding topic doesn't exist, returns `NOT_FOUND`. + * Creates a subscription to a given topic. If the subscription already exists, returns + * `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns `NOT_FOUND`. + * + *

If the name is not provided in the request, the server will assign a random name for this + * subscription on the same project as the topic. Note that for REST API requests, you must + * specify a name. * - * If the name is not provided in the request, the server will assign a random - * name for this subscription on the same project as the topic. Note that - * for REST API requests, you must specify a name. + *

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedName = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -373,15 +342,15 @@ public final Subscription createSubscription(Subscription request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Creates a subscription to a given topic.
-   * If the subscription already exists, returns `ALREADY_EXISTS`.
-   * If the corresponding topic doesn't exist, returns `NOT_FOUND`.
+   * Creates a subscription to a given topic. If the subscription already exists, returns
+   * `ALREADY_EXISTS`. If the corresponding topic doesn't exist, returns `NOT_FOUND`.
+   *
+   * 

If the name is not provided in the request, the server will assign a random name for this + * subscription on the same project as the topic. Note that for REST API requests, you must + * specify a name. * - * If the name is not provided in the request, the server will assign a random - * name for this subscription on the same project as the topic. Note that - * for REST API requests, you must specify a name. + *

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedName = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -404,7 +373,8 @@ public final ApiCallable createSubscriptionCallable(
   /**
    * Gets the configuration details of a subscription.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -426,7 +396,8 @@ public final Subscription getSubscription(String subscription) {
   /**
    * Gets the configuration details of a subscription.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -448,7 +419,8 @@ private final Subscription getSubscription(GetSubscriptionRequest request) {
   /**
    * Gets the configuration details of a subscription.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -469,7 +441,8 @@ public final ApiCallable getSubscriptionCa
   /**
    * Lists matching subscriptions.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedProject = SubscriberApi.formatProjectName("[PROJECT]");
@@ -494,7 +467,8 @@ public final ApiCallable getSubscriptionCa
   /**
    * Lists matching subscriptions.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedProject = SubscriberApi.formatProjectName("[PROJECT]");
@@ -519,7 +493,8 @@ public final ApiCallable getSubscriptionCa
   /**
    * Lists matching subscriptions.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedProject = SubscriberApi.formatProjectName("[PROJECT]");
@@ -545,7 +520,8 @@ public final ApiCallable getSubscriptionCa
   /**
    * Lists matching subscriptions.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedProject = SubscriberApi.formatProjectName("[PROJECT]");
@@ -574,13 +550,13 @@ public final ApiCallable getSubscriptionCa
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Deletes an existing subscription. All pending messages in the subscription
-   * are immediately dropped. Calls to `Pull` after deletion will return
-   * `NOT_FOUND`. After a subscription is deleted, a new one may be created with
-   * the same name, but the new one has no association with the old
-   * subscription, or its topic unless the same topic is specified.
+   * Deletes an existing subscription. All pending messages in the subscription are immediately
+   * dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is
+   * deleted, a new one may be created with the same name, but the new one has no association with
+   * the old subscription, or its topic unless the same topic is specified.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -600,13 +576,13 @@ public final void deleteSubscription(String subscription) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Deletes an existing subscription. All pending messages in the subscription
-   * are immediately dropped. Calls to `Pull` after deletion will return
-   * `NOT_FOUND`. After a subscription is deleted, a new one may be created with
-   * the same name, but the new one has no association with the old
-   * subscription, or its topic unless the same topic is specified.
+   * Deletes an existing subscription. All pending messages in the subscription are immediately
+   * dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is
+   * deleted, a new one may be created with the same name, but the new one has no association with
+   * the old subscription, or its topic unless the same topic is specified.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -626,13 +602,13 @@ private final void deleteSubscription(DeleteSubscriptionRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Deletes an existing subscription. All pending messages in the subscription
-   * are immediately dropped. Calls to `Pull` after deletion will return
-   * `NOT_FOUND`. After a subscription is deleted, a new one may be created with
-   * the same name, but the new one has no association with the old
-   * subscription, or its topic unless the same topic is specified.
+   * Deletes an existing subscription. All pending messages in the subscription are immediately
+   * dropped. Calls to `Pull` after deletion will return `NOT_FOUND`. After a subscription is
+   * deleted, a new one may be created with the same name, but the new one has no association with
+   * the old subscription, or its topic unless the same topic is specified.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -651,13 +627,13 @@ public final ApiCallable deleteSubscriptionCal
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Modifies the ack deadline for a specific message. This method is useful
-   * to indicate that more time is needed to process a message by the
-   * subscriber, or to make the message available for redelivery if the
-   * processing was interrupted. Note that this does not modify the
+   * Modifies the ack deadline for a specific message. This method is useful to indicate that more
+   * time is needed to process a message by the subscriber, or to make the message available for
+   * redelivery if the processing was interrupted. Note that this does not modify the
    * subscription-level `ackDeadlineSeconds` used for subsequent messages.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -669,11 +645,10 @@ public final ApiCallable deleteSubscriptionCal
    *
    * @param subscription The name of the subscription.
    * @param ackIds List of acknowledgment IDs.
-   * @param ackDeadlineSeconds The new ack deadline with respect to the time this request was sent to
-   * the Pub/Sub system. Must be >= 0. For example, if the value is 10, the new
-   * ack deadline will expire 10 seconds after the `ModifyAckDeadline` call
-   * was made. Specifying zero may immediately make the message available for
-   * another pull request.
+   * @param ackDeadlineSeconds The new ack deadline with respect to the time this request was sent
+   *     to the Pub/Sub system. Must be >= 0. For example, if the value is 10, the new ack
+   *     deadline will expire 10 seconds after the `ModifyAckDeadline` call was made. Specifying
+   *     zero may immediately make the message available for another pull request.
    * @throws com.google.api.gax.grpc.ApiException if the remote call fails
    */
   public final void modifyAckDeadline(
@@ -690,13 +665,13 @@ public final void modifyAckDeadline(
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Modifies the ack deadline for a specific message. This method is useful
-   * to indicate that more time is needed to process a message by the
-   * subscriber, or to make the message available for redelivery if the
-   * processing was interrupted. Note that this does not modify the
+   * Modifies the ack deadline for a specific message. This method is useful to indicate that more
+   * time is needed to process a message by the subscriber, or to make the message available for
+   * redelivery if the processing was interrupted. Note that this does not modify the
    * subscription-level `ackDeadlineSeconds` used for subsequent messages.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -720,13 +695,13 @@ public final void modifyAckDeadline(ModifyAckDeadlineRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Modifies the ack deadline for a specific message. This method is useful
-   * to indicate that more time is needed to process a message by the
-   * subscriber, or to make the message available for redelivery if the
-   * processing was interrupted. Note that this does not modify the
+   * Modifies the ack deadline for a specific message. This method is useful to indicate that more
+   * time is needed to process a message by the subscriber, or to make the message available for
+   * redelivery if the processing was interrupted. Note that this does not modify the
    * subscription-level `ackDeadlineSeconds` used for subsequent messages.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -749,15 +724,14 @@ public final ApiCallable modifyAckDeadlineCalla
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Acknowledges the messages associated with the `ack_ids` in the
-   * `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages
-   * from the subscription.
+   * Acknowledges the messages associated with the `ack_ids` in the `AcknowledgeRequest`. The
+   * Pub/Sub system can remove the relevant messages from the subscription.
    *
-   * Acknowledging a message whose ack deadline has expired may succeed,
-   * but such a message may be redelivered later. Acknowledging a message more
-   * than once will not result in an error.
+   * 

Acknowledging a message whose ack deadline has expired may succeed, but such a message may + * be redelivered later. Acknowledging a message more than once will not result in an error. + * + *

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -767,8 +741,8 @@ public final ApiCallable modifyAckDeadlineCalla
    * 
* * @param subscription The subscription whose message is being acknowledged. - * @param ackIds The acknowledgment ID for the messages being acknowledged that was returned - * by the Pub/Sub system in the `Pull` response. Must not be empty. + * @param ackIds The acknowledgment ID for the messages being acknowledged that was returned by + * the Pub/Sub system in the `Pull` response. Must not be empty. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final void acknowledge(String subscription, List ackIds) { @@ -780,15 +754,14 @@ public final void acknowledge(String subscription, List ackIds) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Acknowledges the messages associated with the `ack_ids` in the - * `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages - * from the subscription. + * Acknowledges the messages associated with the `ack_ids` in the `AcknowledgeRequest`. The + * Pub/Sub system can remove the relevant messages from the subscription. + * + *

Acknowledging a message whose ack deadline has expired may succeed, but such a message may + * be redelivered later. Acknowledging a message more than once will not result in an error. * - * Acknowledging a message whose ack deadline has expired may succeed, - * but such a message may be redelivered later. Acknowledging a message more - * than once will not result in an error. + *

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -810,15 +783,14 @@ public final void acknowledge(AcknowledgeRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Acknowledges the messages associated with the `ack_ids` in the
-   * `AcknowledgeRequest`. The Pub/Sub system can remove the relevant messages
-   * from the subscription.
+   * Acknowledges the messages associated with the `ack_ids` in the `AcknowledgeRequest`. The
+   * Pub/Sub system can remove the relevant messages from the subscription.
+   *
+   * 

Acknowledging a message whose ack deadline has expired may succeed, but such a message may + * be redelivered later. Acknowledging a message more than once will not result in an error. * - * Acknowledging a message whose ack deadline has expired may succeed, - * but such a message may be redelivered later. Acknowledging a message more - * than once will not result in an error. + *

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -839,12 +811,12 @@ public final ApiCallable acknowledgeCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Pulls messages from the server. Returns an empty list if there are no
-   * messages available in the backlog. The server may return `UNAVAILABLE` if
-   * there are too many concurrent pull requests pending for the given
-   * subscription.
+   * Pulls messages from the server. Returns an empty list if there are no messages available in the
+   * backlog. The server may return `UNAVAILABLE` if there are too many concurrent pull requests
+   * pending for the given subscription.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -855,13 +827,12 @@ public final ApiCallable acknowledgeCallable() {
    * 
* * @param subscription The subscription from which messages should be pulled. - * @param returnImmediately If this is specified as true the system will respond immediately even if - * it is not able to return a message in the `Pull` response. Otherwise the - * system is allowed to wait until at least one message is available rather - * than returning no messages. The client may cancel the request if it does - * not wish to wait any longer for the response. - * @param maxMessages The maximum number of messages returned for this request. The Pub/Sub - * system may return fewer than the number specified. + * @param returnImmediately If this is specified as true the system will respond immediately even + * if it is not able to return a message in the `Pull` response. Otherwise the system is + * allowed to wait until at least one message is available rather than returning no messages. + * The client may cancel the request if it does not wish to wait any longer for the response. + * @param maxMessages The maximum number of messages returned for this request. The Pub/Sub system + * may return fewer than the number specified. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final PullResponse pull(String subscription, boolean returnImmediately, int maxMessages) { @@ -877,12 +848,12 @@ public final PullResponse pull(String subscription, boolean returnImmediately, i // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Pulls messages from the server. Returns an empty list if there are no - * messages available in the backlog. The server may return `UNAVAILABLE` if - * there are too many concurrent pull requests pending for the given - * subscription. + * Pulls messages from the server. Returns an empty list if there are no messages available in the + * backlog. The server may return `UNAVAILABLE` if there are too many concurrent pull requests + * pending for the given subscription. + * + *

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -904,12 +875,12 @@ public final PullResponse pull(PullRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Pulls messages from the server. Returns an empty list if there are no
-   * messages available in the backlog. The server may return `UNAVAILABLE` if
-   * there are too many concurrent pull requests pending for the given
-   * subscription.
+   * Pulls messages from the server. Returns an empty list if there are no messages available in the
+   * backlog. The server may return `UNAVAILABLE` if there are too many concurrent pull requests
+   * pending for the given subscription.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -932,12 +903,13 @@ public final ApiCallable pullCallable() {
   /**
    * Modifies the `PushConfig` for a specified subscription.
    *
-   * This may be used to change a push subscription to a pull one (signified by
-   * an empty `PushConfig`) or vice versa, or change the endpoint URL and other
-   * attributes of a push subscription. Messages will accumulate for delivery
-   * continuously through the call regardless of changes to the `PushConfig`.
+   * 

This may be used to change a push subscription to a pull one (signified by an empty + * `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push + * subscription. Messages will accumulate for delivery continuously through the call regardless of + * changes to the `PushConfig`. + * + *

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -948,11 +920,9 @@ public final ApiCallable pullCallable() {
    *
    * @param subscription The name of the subscription.
    * @param pushConfig The push configuration for future deliveries.
-   *
-   * An empty `pushConfig` indicates that the Pub/Sub system should
-   * stop pushing messages from the given subscription and allow
-   * messages to be pulled and acknowledged - effectively pausing
-   * the subscription if `Pull` is not called.
+   *     

An empty `pushConfig` indicates that the Pub/Sub system should stop pushing messages + * from the given subscription and allow messages to be pulled and acknowledged - effectively + * pausing the subscription if `Pull` is not called. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final void modifyPushConfig(String subscription, PushConfig pushConfig) { @@ -969,12 +939,13 @@ public final void modifyPushConfig(String subscription, PushConfig pushConfig) { /** * Modifies the `PushConfig` for a specified subscription. * - * This may be used to change a push subscription to a pull one (signified by - * an empty `PushConfig`) or vice versa, or change the endpoint URL and other - * attributes of a push subscription. Messages will accumulate for delivery - * continuously through the call regardless of changes to the `PushConfig`. + *

This may be used to change a push subscription to a pull one (signified by an empty + * `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push + * subscription. Messages will accumulate for delivery continuously through the call regardless of + * changes to the `PushConfig`. + * + *

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -998,12 +969,13 @@ public final void modifyPushConfig(ModifyPushConfigRequest request) {
   /**
    * Modifies the `PushConfig` for a specified subscription.
    *
-   * This may be used to change a push subscription to a pull one (signified by
-   * an empty `PushConfig`) or vice versa, or change the endpoint URL and other
-   * attributes of a push subscription. Messages will accumulate for delivery
-   * continuously through the call regardless of changes to the `PushConfig`.
+   * 

This may be used to change a push subscription to a pull one (signified by an empty + * `PushConfig`) or vice versa, or change the endpoint URL and other attributes of a push + * subscription. Messages will accumulate for delivery continuously through the call regardless of + * changes to the `PushConfig`. + * + *

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedSubscription = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -1024,10 +996,10 @@ public final ApiCallable modifyPushConfigCallabl
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Sets the access control policy on the specified resource. Replaces any
-   * existing policy.
+   * Sets the access control policy on the specified resource. Replaces any existing policy.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedResource = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -1036,12 +1008,11 @@ public final ApiCallable modifyPushConfigCallabl
    * }
    * 
* - * @param resource REQUIRED: The resource for which policy is being specified. - * Resource is usually specified as a path, such as, - * projects/{project}/zones/{zone}/disks/{disk}. - * @param policy REQUIRED: The complete policy to be applied to the 'resource'. The size of - * the policy is limited to a few 10s of KB. An empty policy is in general a - * valid policy but certain services (like Projects) might reject them. + * @param resource REQUIRED: The resource for which policy is being specified. Resource is usually + * specified as a path, such as, projects/{project}/zones/{zone}/disks/{disk}. + * @param policy REQUIRED: The complete policy to be applied to the 'resource'. The size of the + * policy is limited to a few 10s of KB. An empty policy is in general a valid policy but + * certain services (like Projects) might reject them. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final Policy setIamPolicy(String resource, Policy policy) { @@ -1053,10 +1024,10 @@ public final Policy setIamPolicy(String resource, Policy policy) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Sets the access control policy on the specified resource. Replaces any - * existing policy. + * Sets the access control policy on the specified resource. Replaces any existing policy. + * + *

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedResource = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -1078,10 +1049,10 @@ public final Policy setIamPolicy(SetIamPolicyRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Sets the access control policy on the specified resource. Replaces any
-   * existing policy.
+   * Sets the access control policy on the specified resource. Replaces any existing policy.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedResource = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -1102,10 +1073,11 @@ public final ApiCallable setIamPolicyCallable() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Gets the access control policy for a resource. Is empty if the
-   * policy or the resource does not exist.
+   * Gets the access control policy for a resource. Is empty if the policy or the resource does not
+   * exist.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedResource = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -1113,8 +1085,8 @@ public final ApiCallable setIamPolicyCallable() {
    * }
    * 
* - * @param resource REQUIRED: The resource for which policy is being requested. Resource - * is usually specified as a path, such as, projects/{project}. + * @param resource REQUIRED: The resource for which policy is being requested. Resource is usually + * specified as a path, such as, projects/{project}. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final Policy getIamPolicy(String resource) { @@ -1125,10 +1097,11 @@ public final Policy getIamPolicy(String resource) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets the access control policy for a resource. Is empty if the - * policy or the resource does not exist. + * Gets the access control policy for a resource. Is empty if the policy or the resource does not + * exist. + * + *

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedResource = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -1148,10 +1121,11 @@ private final Policy getIamPolicy(GetIamPolicyRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Gets the access control policy for a resource. Is empty if the
-   * policy or the resource does not exist.
+   * Gets the access control policy for a resource. Is empty if the policy or the resource does not
+   * exist.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedResource = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -1172,7 +1146,8 @@ public final ApiCallable getIamPolicyCallable() {
   /**
    * Returns permissions that a caller has on the specified resource.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedResource = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -1181,10 +1156,10 @@ public final ApiCallable getIamPolicyCallable() {
    * }
    * 
* - * @param resource REQUIRED: The resource for which policy detail is being requested. - * Resource is usually specified as a path, such as, projects/{project}. + * @param resource REQUIRED: The resource for which policy detail is being requested. Resource is + * usually specified as a path, such as, projects/{project}. * @param permissions The set of permissions to check for the 'resource'. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. + * wildcards (such as '*' or 'storage.*') are not allowed. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final TestIamPermissionsResponse testIamPermissions( @@ -1202,7 +1177,8 @@ public final TestIamPermissionsResponse testIamPermissions( /** * Returns permissions that a caller has on the specified resource. * - * Sample code: + *

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedResource = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
@@ -1226,7 +1202,8 @@ public final TestIamPermissionsResponse testIamPermissions(TestIamPermissionsReq
   /**
    * Returns permissions that a caller has on the specified resource.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
    *   String formattedResource = SubscriberApi.formatSubscriptionName("[PROJECT]", "[SUBSCRIPTION]");
diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberSettings.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberSettings.java
index d29209d5e860..4396e5b692f9 100644
--- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberSettings.java
+++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberSettings.java
@@ -14,7 +14,6 @@
 package com.google.cloud.pubsub.spi.v1;
 
 import com.google.api.gax.core.ConnectionSettings;
-import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -59,15 +58,14 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (pubsub.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (pubsub.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of createSubscription to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of createSubscription to 30 seconds: * *

  * 
@@ -81,28 +79,20 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class SubscriberSettings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "pubsub.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder()
           .add("https://www.googleapis.com/auth/cloud-platform")
           .add("https://www.googleapis.com/auth/pubsub")
           .build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -125,124 +115,90 @@ public class SubscriberSettings extends ServiceApiSettings {
   private final SimpleCallSettings
       testIamPermissionsSettings;
 
-  /**
-   * Returns the object with the settings used for calls to createSubscription.
-   */
+  /** Returns the object with the settings used for calls to createSubscription. */
   public SimpleCallSettings createSubscriptionSettings() {
     return createSubscriptionSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to getSubscription.
-   */
+  /** Returns the object with the settings used for calls to getSubscription. */
   public SimpleCallSettings getSubscriptionSettings() {
     return getSubscriptionSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to listSubscriptions.
-   */
+  /** Returns the object with the settings used for calls to listSubscriptions. */
   public PageStreamingCallSettings<
           ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription>
       listSubscriptionsSettings() {
     return listSubscriptionsSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to deleteSubscription.
-   */
+  /** Returns the object with the settings used for calls to deleteSubscription. */
   public SimpleCallSettings deleteSubscriptionSettings() {
     return deleteSubscriptionSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to modifyAckDeadline.
-   */
+  /** Returns the object with the settings used for calls to modifyAckDeadline. */
   public SimpleCallSettings modifyAckDeadlineSettings() {
     return modifyAckDeadlineSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to acknowledge.
-   */
+  /** Returns the object with the settings used for calls to acknowledge. */
   public SimpleCallSettings acknowledgeSettings() {
     return acknowledgeSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to pull.
-   */
+  /** Returns the object with the settings used for calls to pull. */
   public SimpleCallSettings pullSettings() {
     return pullSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to modifyPushConfig.
-   */
+  /** Returns the object with the settings used for calls to modifyPushConfig. */
   public SimpleCallSettings modifyPushConfigSettings() {
     return modifyPushConfigSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to setIamPolicy.
-   */
+  /** Returns the object with the settings used for calls to setIamPolicy. */
   public SimpleCallSettings setIamPolicySettings() {
     return setIamPolicySettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to getIamPolicy.
-   */
+  /** Returns the object with the settings used for calls to getIamPolicy. */
   public SimpleCallSettings getIamPolicySettings() {
     return getIamPolicySettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to testIamPermissions.
-   */
+  /** Returns the object with the settings used for calls to testIamPermissions. */
   public SimpleCallSettings
       testIamPermissionsSettings() {
     return testIamPermissionsSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -309,9 +265,7 @@ public Iterable extractResources(ListSubscriptionsResponse payload
             }
           };
 
-  /**
-   * Builder for SubscriberSettings.
-   */
+  /** Builder for SubscriberSettings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -562,92 +516,69 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to createSubscription.
-     */
+    /** Returns the builder for the settings used for calls to createSubscription. */
     public SimpleCallSettings.Builder createSubscriptionSettings() {
       return createSubscriptionSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to getSubscription.
-     */
+    /** Returns the builder for the settings used for calls to getSubscription. */
     public SimpleCallSettings.Builder
         getSubscriptionSettings() {
       return getSubscriptionSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listSubscriptions.
-     */
+    /** Returns the builder for the settings used for calls to listSubscriptions. */
     public PageStreamingCallSettings.Builder<
             ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription>
         listSubscriptionsSettings() {
       return listSubscriptionsSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to deleteSubscription.
-     */
+    /** Returns the builder for the settings used for calls to deleteSubscription. */
     public SimpleCallSettings.Builder
         deleteSubscriptionSettings() {
       return deleteSubscriptionSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to modifyAckDeadline.
-     */
+    /** Returns the builder for the settings used for calls to modifyAckDeadline. */
     public SimpleCallSettings.Builder modifyAckDeadlineSettings() {
       return modifyAckDeadlineSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to acknowledge.
-     */
+    /** Returns the builder for the settings used for calls to acknowledge. */
     public SimpleCallSettings.Builder acknowledgeSettings() {
       return acknowledgeSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to pull.
-     */
+    /** Returns the builder for the settings used for calls to pull. */
     public SimpleCallSettings.Builder pullSettings() {
       return pullSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to modifyPushConfig.
-     */
+    /** Returns the builder for the settings used for calls to modifyPushConfig. */
     public SimpleCallSettings.Builder modifyPushConfigSettings() {
       return modifyPushConfigSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to setIamPolicy.
-     */
+    /** Returns the builder for the settings used for calls to setIamPolicy. */
     public SimpleCallSettings.Builder setIamPolicySettings() {
       return setIamPolicySettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to getIamPolicy.
-     */
+    /** Returns the builder for the settings used for calls to getIamPolicy. */
     public SimpleCallSettings.Builder getIamPolicySettings() {
       return getIamPolicySettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to testIamPermissions.
-     */
+    /** Returns the builder for the settings used for calls to testIamPermissions. */
     public SimpleCallSettings.Builder
         testIamPermissionsSettings() {
       return testIamPermissionsSettings;
diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/package-info.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/package-info.java
index 1bac8a3590f9..99a7c0144671 100644
--- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/package-info.java
+++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/package-info.java
@@ -15,16 +15,15 @@
 /**
  * A client to Google Cloud Pub/Sub API.
  *
- * The interfaces provided are listed below, along with a usage sample
+ * 

The interfaces provided are listed below, along with a usage sample * - * ============ - * PublisherApi - * ============ + *

============ PublisherApi ============ * - * Service Description: The service that an application uses to manipulate topics, and to send + *

Service Description: The service that an application uses to manipulate topics, and to send * messages to a topic. * - * Sample for PublisherApi: + *

Sample for PublisherApi: + * *

  * 
  * try (PublisherApi publisherApi = PublisherApi.create()) {
@@ -34,14 +33,13 @@
  * 
  * 
* - * ============= - * SubscriberApi - * ============= + * ============= SubscriberApi ============= * - * Service Description: The service that an application uses to manipulate subscriptions and to + *

Service Description: The service that an application uses to manipulate subscriptions and to * consume messages from a subscription via the `Pull` method. * - * Sample for SubscriberApi: + *

Sample for SubscriberApi: + * *

  * 
  * try (SubscriberApi subscriberApi = SubscriberApi.create()) {
@@ -53,6 +51,5 @@
  * }
  * 
  * 
- * */ package com.google.cloud.pubsub.spi.v1; diff --git a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechApi.java b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechApi.java index 149793e08103..9ce5e2917edc 100644 --- a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechApi.java +++ b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechApi.java @@ -14,7 +14,6 @@ package com.google.cloud.speech.spi.v1beta1; import com.google.api.gax.grpc.ApiCallable; -import com.google.api.gax.protobuf.PathTemplate; import com.google.cloud.speech.v1beta1.AsyncRecognizeRequest; import com.google.cloud.speech.v1beta1.RecognitionAudio; import com.google.cloud.speech.v1beta1.RecognitionConfig; @@ -45,32 +44,31 @@ *
*
* - *

Note: close() needs to be called on the speechApi object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + *

Note: close() needs to be called on the speechApi object to clean up resources such as + * threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * - *

This class can be customized by passing in a custom instance of SpeechSettings to - * create(). For example: + *

This class can be customized by passing in a custom instance of SpeechSettings to create(). + * For example: * *

  * 
@@ -91,26 +89,22 @@ public class SpeechApi implements AutoCloseable {
   private final ApiCallable syncRecognizeCallable;
   private final ApiCallable asyncRecognizeCallable;
 
-  /**
-   * Constructs an instance of SpeechApi with default settings.
-   */
+  /** Constructs an instance of SpeechApi with default settings. */
   public static final SpeechApi create() throws IOException {
     return create(SpeechSettings.defaultBuilder().build());
   }
 
   /**
-   * Constructs an instance of SpeechApi, using the given settings.
-   * The channels are created based on the settings passed in, or defaults for any
-   * settings that are not set.
+   * Constructs an instance of SpeechApi, using the given settings. The channels are created based
+   * on the settings passed in, or defaults for any settings that are not set.
    */
   public static final SpeechApi create(SpeechSettings settings) throws IOException {
     return new SpeechApi(settings);
   }
 
   /**
-   * Constructs an instance of SpeechApi, using the given settings.
-   * This is protected so that it easy to make a subclass, but otherwise, the static
-   * factory methods should be preferred.
+   * Constructs an instance of SpeechApi, using the given settings. This is protected so that it
+   * easy to make a subclass, but otherwise, the static factory methods should be preferred.
    */
   protected SpeechApi(SpeechSettings settings) throws IOException {
     this.settings = settings;
@@ -148,10 +142,11 @@ public final SpeechSettings getSettings() {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Perform synchronous speech-recognition: receive results after all audio
-   * has been sent and processed.
+   * Perform synchronous speech-recognition: receive results after all audio has been sent and
+   * processed.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SpeechApi speechApi = SpeechApi.create()) {
    *   RecognitionConfig config = RecognitionConfig.newBuilder().build();
@@ -160,8 +155,8 @@ public final SpeechSettings getSettings() {
    * }
    * 
* - * @param config [Required] The `config` message provides information to the recognizer - * that specifies how to process the request. + * @param config [Required] The `config` message provides information to the recognizer that + * specifies how to process the request. * @param audio [Required] The audio data to be recognized. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ @@ -174,10 +169,11 @@ public final SyncRecognizeResponse syncRecognize( // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Perform synchronous speech-recognition: receive results after all audio - * has been sent and processed. + * Perform synchronous speech-recognition: receive results after all audio has been sent and + * processed. + * + *

Sample code: * - * Sample code: *


    * try (SpeechApi speechApi = SpeechApi.create()) {
    *   RecognitionConfig config = RecognitionConfig.newBuilder().build();
@@ -199,10 +195,11 @@ public final SyncRecognizeResponse syncRecognize(SyncRecognizeRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Perform synchronous speech-recognition: receive results after all audio
-   * has been sent and processed.
+   * Perform synchronous speech-recognition: receive results after all audio has been sent and
+   * processed.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SpeechApi speechApi = SpeechApi.create()) {
    *   RecognitionConfig config = RecognitionConfig.newBuilder().build();
@@ -223,12 +220,12 @@ public final ApiCallable syncRecogn
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Perform asynchronous speech-recognition: receive results via the
-   * google.longrunning.Operations interface. Returns either an
-   * `Operation.error` or an `Operation.response` which contains
-   * an `AsyncRecognizeResponse` message.
+   * Perform asynchronous speech-recognition: receive results via the google.longrunning.Operations
+   * interface. Returns either an `Operation.error` or an `Operation.response` which contains an
+   * `AsyncRecognizeResponse` message.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SpeechApi speechApi = SpeechApi.create()) {
    *   RecognitionConfig config = RecognitionConfig.newBuilder().build();
@@ -237,8 +234,8 @@ public final ApiCallable syncRecogn
    * }
    * 
* - * @param config [Required] The `config` message provides information to the recognizer - * that specifies how to process the request. + * @param config [Required] The `config` message provides information to the recognizer that + * specifies how to process the request. * @param audio [Required] The audio data to be recognized. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ @@ -250,12 +247,12 @@ public final Operation asyncRecognize(RecognitionConfig config, RecognitionAudio // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Perform asynchronous speech-recognition: receive results via the - * google.longrunning.Operations interface. Returns either an - * `Operation.error` or an `Operation.response` which contains - * an `AsyncRecognizeResponse` message. + * Perform asynchronous speech-recognition: receive results via the google.longrunning.Operations + * interface. Returns either an `Operation.error` or an `Operation.response` which contains an + * `AsyncRecognizeResponse` message. + * + *

Sample code: * - * Sample code: *


    * try (SpeechApi speechApi = SpeechApi.create()) {
    *   RecognitionConfig config = RecognitionConfig.newBuilder().build();
@@ -277,12 +274,12 @@ public final Operation asyncRecognize(AsyncRecognizeRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Perform asynchronous speech-recognition: receive results via the
-   * google.longrunning.Operations interface. Returns either an
-   * `Operation.error` or an `Operation.response` which contains
-   * an `AsyncRecognizeResponse` message.
+   * Perform asynchronous speech-recognition: receive results via the google.longrunning.Operations
+   * interface. Returns either an `Operation.error` or an `Operation.response` which contains an
+   * `AsyncRecognizeResponse` message.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (SpeechApi speechApi = SpeechApi.create()) {
    *   RecognitionConfig config = RecognitionConfig.newBuilder().build();
diff --git a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechSettings.java b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechSettings.java
index 6cffd44dac83..ed78555815e4 100644
--- a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechSettings.java
+++ b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechSettings.java
@@ -16,7 +16,6 @@
 import com.google.api.gax.core.ConnectionSettings;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
-import com.google.api.gax.grpc.PageStreamingDescriptor;
 import com.google.api.gax.grpc.ServiceApiSettings;
 import com.google.api.gax.grpc.SimpleCallSettings;
 import com.google.auth.Credentials;
@@ -44,15 +43,14 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (speech.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (speech.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of syncRecognize to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of syncRecognize to 30 seconds: * *

  * 
@@ -66,25 +64,17 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class SpeechSettings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "speech.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -96,58 +86,42 @@ public class SpeechSettings extends ServiceApiSettings {
       syncRecognizeSettings;
   private final SimpleCallSettings asyncRecognizeSettings;
 
-  /**
-   * Returns the object with the settings used for calls to syncRecognize.
-   */
+  /** Returns the object with the settings used for calls to syncRecognize. */
   public SimpleCallSettings syncRecognizeSettings() {
     return syncRecognizeSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to asyncRecognize.
-   */
+  /** Returns the object with the settings used for calls to asyncRecognize. */
   public SimpleCallSettings asyncRecognizeSettings() {
     return asyncRecognizeSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -165,9 +139,7 @@ private SpeechSettings(Builder settingsBuilder) throws IOException {
     asyncRecognizeSettings = settingsBuilder.asyncRecognizeSettings().build();
   }
 
-  /**
-   * Builder for SpeechSettings.
-   */
+  /** Builder for SpeechSettings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -292,26 +264,21 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to syncRecognize.
-     */
+    /** Returns the builder for the settings used for calls to syncRecognize. */
     public SimpleCallSettings.Builder
         syncRecognizeSettings() {
       return syncRecognizeSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to asyncRecognize.
-     */
+    /** Returns the builder for the settings used for calls to asyncRecognize. */
     public SimpleCallSettings.Builder asyncRecognizeSettings() {
       return asyncRecognizeSettings;
     }
diff --git a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/package-info.java b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/package-info.java
index 8ec07dd8e306..e7348c17639b 100644
--- a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/package-info.java
+++ b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/package-info.java
@@ -15,15 +15,14 @@
 /**
  * A client to Google Cloud Speech API.
  *
- * The interfaces provided are listed below, along with a usage sample
+ * 

The interfaces provided are listed below, along with a usage sample * - * ========= - * SpeechApi - * ========= + *

========= SpeechApi ========= * - * Service Description: Service that implements Google Cloud Speech API. + *

Service Description: Service that implements Google Cloud Speech API. + * + *

Sample for SpeechApi: * - * Sample for SpeechApi: *

  * 
  * try (SpeechApi speechApi = SpeechApi.create()) {
@@ -33,6 +32,5 @@
  * }
  * 
  * 
- * */ package com.google.cloud.speech.spi.v1beta1; diff --git a/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/SpeechTest.java b/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/SpeechTest.java index a41f6bf15dc7..c59e64f80ddc 100644 --- a/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/SpeechTest.java +++ b/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/SpeechTest.java @@ -14,7 +14,6 @@ package com.google.cloud.speech.spi.v1beta1; -import com.google.api.gax.core.PagedListResponse; import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; import com.google.cloud.speech.v1beta1.AsyncRecognizeRequest; @@ -22,7 +21,6 @@ import com.google.cloud.speech.v1beta1.RecognitionConfig; import com.google.cloud.speech.v1beta1.SyncRecognizeRequest; import com.google.cloud.speech.v1beta1.SyncRecognizeResponse; -import com.google.common.collect.Lists; import com.google.longrunning.Operation; import com.google.protobuf.GeneratedMessageV3; import java.io.IOException; diff --git a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceApi.java b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceApi.java index 0342aa225dba..d990e788a3b6 100644 --- a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceApi.java +++ b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceApi.java @@ -15,7 +15,6 @@ import com.google.api.gax.core.PagedListResponse; import com.google.api.gax.grpc.ApiCallable; -import com.google.api.gax.protobuf.PathTemplate; import com.google.devtools.cloudtrace.v1.GetTraceRequest; import com.google.devtools.cloudtrace.v1.ListTracesRequest; import com.google.devtools.cloudtrace.v1.ListTracesResponse; @@ -33,10 +32,9 @@ // AUTO-GENERATED DOCUMENTATION AND SERVICE /** * Service Description: This file describes an API for collecting and viewing traces and spans - * within a trace. A Trace is a collection of spans corresponding to a single - * operation or set of operations for an application. A span is an individual - * timed event which forms a node of the trace tree. Spans for a single trace - * may span multiple services. + * within a trace. A Trace is a collection of spans corresponding to a single operation or set of + * operations for an application. A span is an individual timed event which forms a node of the + * trace tree. Spans for a single trace may span multiple services. * *

This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: @@ -51,29 +49,28 @@ * *

* - *

Note: close() needs to be called on the traceServiceApi object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + *

Note: close() needs to be called on the traceServiceApi object to clean up resources such as + * threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * *

This class can be customized by passing in a custom instance of TraceServiceSettings to * create(). For example: @@ -101,26 +98,22 @@ public class TraceServiceApi implements AutoCloseable { ListTracesRequest, PagedListResponse> listTracesPagedCallable; - /** - * Constructs an instance of TraceServiceApi with default settings. - */ + /** Constructs an instance of TraceServiceApi with default settings. */ public static final TraceServiceApi create() throws IOException { return create(TraceServiceSettings.defaultBuilder().build()); } /** - * Constructs an instance of TraceServiceApi, using the given settings. - * The channels are created based on the settings passed in, or defaults for any - * settings that are not set. + * Constructs an instance of TraceServiceApi, using the given settings. The channels are created + * based on the settings passed in, or defaults for any settings that are not set. */ public static final TraceServiceApi create(TraceServiceSettings settings) throws IOException { return new TraceServiceApi(settings); } /** - * Constructs an instance of TraceServiceApi, using the given settings. - * This is protected so that it easy to make a subclass, but otherwise, the static - * factory methods should be preferred. + * Constructs an instance of TraceServiceApi, using the given settings. This is protected so that + * it easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected TraceServiceApi(TraceServiceSettings settings) throws IOException { this.settings = settings; @@ -162,13 +155,13 @@ public final TraceServiceSettings getSettings() { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Sends new traces to Cloud Trace or updates existing traces. If the ID of - * a trace that you send matches that of an existing trace, any fields - * in the existing trace and its spans are overwritten by the provided values, - * and any new fields provided are merged with the existing trace data. If the - * ID does not match, a new trace is created. + * Sends new traces to Cloud Trace or updates existing traces. If the ID of a trace that you send + * matches that of an existing trace, any fields in the existing trace and its spans are + * overwritten by the provided values, and any new fields provided are merged with the existing + * trace data. If the ID does not match, a new trace is created. + * + *

Sample code: * - * Sample code: *


    * try (TraceServiceApi traceServiceApi = TraceServiceApi.create()) {
    *   String projectId = "";
@@ -189,13 +182,13 @@ public final void patchTraces(String projectId, Traces traces) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Sends new traces to Cloud Trace or updates existing traces. If the ID of
-   * a trace that you send matches that of an existing trace, any fields
-   * in the existing trace and its spans are overwritten by the provided values,
-   * and any new fields provided are merged with the existing trace data. If the
-   * ID does not match, a new trace is created.
+   * Sends new traces to Cloud Trace or updates existing traces. If the ID of a trace that you send
+   * matches that of an existing trace, any fields in the existing trace and its spans are
+   * overwritten by the provided values, and any new fields provided are merged with the existing
+   * trace data. If the ID does not match, a new trace is created.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (TraceServiceApi traceServiceApi = TraceServiceApi.create()) {
    *   String projectId = "";
@@ -217,13 +210,13 @@ public final void patchTraces(PatchTracesRequest request) {
 
   // AUTO-GENERATED DOCUMENTATION AND METHOD
   /**
-   * Sends new traces to Cloud Trace or updates existing traces. If the ID of
-   * a trace that you send matches that of an existing trace, any fields
-   * in the existing trace and its spans are overwritten by the provided values,
-   * and any new fields provided are merged with the existing trace data. If the
-   * ID does not match, a new trace is created.
+   * Sends new traces to Cloud Trace or updates existing traces. If the ID of a trace that you send
+   * matches that of an existing trace, any fields in the existing trace and its spans are
+   * overwritten by the provided values, and any new fields provided are merged with the existing
+   * trace data. If the ID does not match, a new trace is created.
+   *
+   * 

Sample code: * - * Sample code: *


    * try (TraceServiceApi traceServiceApi = TraceServiceApi.create()) {
    *   String projectId = "";
@@ -246,7 +239,8 @@ public final ApiCallable patchTracesCallable() {
   /**
    * Gets a single trace by its ID.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (TraceServiceApi traceServiceApi = TraceServiceApi.create()) {
    *   String projectId = "";
@@ -269,7 +263,8 @@ public final Trace getTrace(String projectId, String traceId) {
   /**
    * Gets a single trace by its ID.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (TraceServiceApi traceServiceApi = TraceServiceApi.create()) {
    *   String projectId = "";
@@ -293,7 +288,8 @@ private final Trace getTrace(GetTraceRequest request) {
   /**
    * Gets a single trace by its ID.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (TraceServiceApi traceServiceApi = TraceServiceApi.create()) {
    *   String projectId = "";
@@ -316,7 +312,8 @@ public final ApiCallable getTraceCallable() {
   /**
    * Returns of a list of traces that match the specified filter conditions.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (TraceServiceApi traceServiceApi = TraceServiceApi.create()) {
    *   String projectId = "";
@@ -339,7 +336,8 @@ public final PagedListResponse lis
   /**
    * Returns of a list of traces that match the specified filter conditions.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (TraceServiceApi traceServiceApi = TraceServiceApi.create()) {
    *   String projectId = "";
@@ -364,7 +362,8 @@ public final PagedListResponse lis
   /**
    * Returns of a list of traces that match the specified filter conditions.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (TraceServiceApi traceServiceApi = TraceServiceApi.create()) {
    *   String projectId = "";
@@ -389,7 +388,8 @@ public final PagedListResponse lis
   /**
    * Returns of a list of traces that match the specified filter conditions.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (TraceServiceApi traceServiceApi = TraceServiceApi.create()) {
    *   String projectId = "";
diff --git a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java
index 39445d3c148b..698295f4b86b 100644
--- a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java
+++ b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java
@@ -14,7 +14,6 @@
 package com.google.cloud.trace.spi.v1;
 
 import com.google.api.gax.core.ConnectionSettings;
-import com.google.api.gax.core.PagedListResponse;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
 import com.google.api.gax.grpc.PageStreamingCallSettings;
@@ -48,15 +47,14 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (cloudtrace.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (cloudtrace.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of patchTraces to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of patchTraces to 30 seconds: * *

  * 
@@ -70,19 +68,13 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class TraceServiceSettings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "cloudtrace.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder()
           .add("https://www.googleapis.com/auth/cloud-platform")
@@ -90,9 +82,7 @@ public class TraceServiceSettings extends ServiceApiSettings {
           .add("https://www.googleapis.com/auth/trace.readonly")
           .build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -105,66 +95,48 @@ public class TraceServiceSettings extends ServiceApiSettings {
   private final PageStreamingCallSettings
       listTracesSettings;
 
-  /**
-   * Returns the object with the settings used for calls to patchTraces.
-   */
+  /** Returns the object with the settings used for calls to patchTraces. */
   public SimpleCallSettings patchTracesSettings() {
     return patchTracesSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to getTrace.
-   */
+  /** Returns the object with the settings used for calls to getTrace. */
   public SimpleCallSettings getTraceSettings() {
     return getTraceSettings;
   }
 
-  /**
-   * Returns the object with the settings used for calls to listTraces.
-   */
+  /** Returns the object with the settings used for calls to listTraces. */
   public PageStreamingCallSettings
       listTracesSettings() {
     return listTracesSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -219,9 +191,7 @@ public Iterable extractResources(ListTracesResponse payload) {
             }
           };
 
-  /**
-   * Builder for TraceServiceSettings.
-   */
+  /** Builder for TraceServiceSettings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -358,32 +328,25 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to patchTraces.
-     */
+    /** Returns the builder for the settings used for calls to patchTraces. */
     public SimpleCallSettings.Builder patchTracesSettings() {
       return patchTracesSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to getTrace.
-     */
+    /** Returns the builder for the settings used for calls to getTrace. */
     public SimpleCallSettings.Builder getTraceSettings() {
       return getTraceSettings;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to listTraces.
-     */
+    /** Returns the builder for the settings used for calls to listTraces. */
     public PageStreamingCallSettings.Builder
         listTracesSettings() {
       return listTracesSettings;
diff --git a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/package-info.java b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/package-info.java
index 0d89aecc3319..ade6ff07dc7a 100644
--- a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/package-info.java
+++ b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/package-info.java
@@ -15,19 +15,17 @@
 /**
  * A client to Stackdriver Trace API.
  *
- * The interfaces provided are listed below, along with a usage sample
+ * 

The interfaces provided are listed below, along with a usage sample * - * =============== - * TraceServiceApi - * =============== + *

=============== TraceServiceApi =============== * - * Service Description: This file describes an API for collecting and viewing traces and spans - * within a trace. A Trace is a collection of spans corresponding to a single - * operation or set of operations for an application. A span is an individual - * timed event which forms a node of the trace tree. Spans for a single trace - * may span multiple services. + *

Service Description: This file describes an API for collecting and viewing traces and spans + * within a trace. A Trace is a collection of spans corresponding to a single operation or set of + * operations for an application. A span is an individual timed event which forms a node of the + * trace tree. Spans for a single trace may span multiple services. + * + *

Sample for TraceServiceApi: * - * Sample for TraceServiceApi: *

  * 
  * try (TraceServiceApi traceServiceApi = TraceServiceApi.create()) {
@@ -37,6 +35,5 @@
  * }
  * 
  * 
- * */ package com.google.cloud.trace.spi.v1; diff --git a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorApi.java b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorApi.java index 461f37be77af..58672211034a 100644 --- a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorApi.java +++ b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorApi.java @@ -14,7 +14,6 @@ package com.google.cloud.vision.spi.v1; import com.google.api.gax.grpc.ApiCallable; -import com.google.api.gax.protobuf.PathTemplate; import com.google.cloud.vision.v1.AnnotateImageRequest; import com.google.cloud.vision.v1.BatchAnnotateImagesRequest; import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; @@ -28,8 +27,8 @@ // AUTO-GENERATED DOCUMENTATION AND SERVICE /** * Service Description: Service that performs Google Cloud Vision API detection tasks, such as face, - * landmark, logo, label, and text detection, over client images, and returns - * detected entities from the images. + * landmark, logo, label, and text detection, over client images, and returns detected entities from + * the images. * *

This class provides the ability to make remote calls to the backing service through method * calls that map to API methods. Sample code to get started: @@ -43,29 +42,28 @@ * *

* - *

Note: close() needs to be called on the imageAnnotatorApi object to clean up resources such - * as threads. In the example above, try-with-resources is used, which automatically calls - * close(). + *

Note: close() needs to be called on the imageAnnotatorApi object to clean up resources such as + * threads. In the example above, try-with-resources is used, which automatically calls close(). * - *

The surface of this class includes several types of Java methods for each of the API's methods: + *

The surface of this class includes several types of Java methods for each of the API's + * methods: * *

    - *
  1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available - * as parameters, and not every API method will have a flattened method entry point. - *
  2. A "request object" method. This type of method only takes one parameter, a request - * object, which must be constructed before the call. Not every API method will have a request - * object method. - *
  3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  4. A "flattened" method. With this type of method, the fields of the request type have been + * converted into function parameters. It may be the case that not all fields are available as + * parameters, and not every API method will have a flattened method entry point. + *
  5. A "request object" method. This type of method only takes one parameter, a request object, + * which must be constructed before the call. Not every API method will have a request object + * method. + *
  6. A "callable" method. This type of method takes no parameters and returns an immutable + * ApiCallable object, which can be used to initiate calls to the service. *
* *

See the individual methods for example code. * - *

Many parameters require resource names to be formatted in a particular way. To assist - * with these names, this class includes a format method for each type of name, and additionally - * a parse method to extract the individual identifiers contained within names that are - * returned. + *

Many parameters require resource names to be formatted in a particular way. To assist with + * these names, this class includes a format method for each type of name, and additionally a parse + * method to extract the individual identifiers contained within names that are returned. * *

This class can be customized by passing in a custom instance of ImageAnnotatorSettings to * create(). For example: @@ -89,26 +87,22 @@ public class ImageAnnotatorApi implements AutoCloseable { private final ApiCallable batchAnnotateImagesCallable; - /** - * Constructs an instance of ImageAnnotatorApi with default settings. - */ + /** Constructs an instance of ImageAnnotatorApi with default settings. */ public static final ImageAnnotatorApi create() throws IOException { return create(ImageAnnotatorSettings.defaultBuilder().build()); } /** - * Constructs an instance of ImageAnnotatorApi, using the given settings. - * The channels are created based on the settings passed in, or defaults for any - * settings that are not set. + * Constructs an instance of ImageAnnotatorApi, using the given settings. The channels are created + * based on the settings passed in, or defaults for any settings that are not set. */ public static final ImageAnnotatorApi create(ImageAnnotatorSettings settings) throws IOException { return new ImageAnnotatorApi(settings); } /** - * Constructs an instance of ImageAnnotatorApi, using the given settings. - * This is protected so that it easy to make a subclass, but otherwise, the static - * factory methods should be preferred. + * Constructs an instance of ImageAnnotatorApi, using the given settings. This is protected so + * that it easy to make a subclass, but otherwise, the static factory methods should be preferred. */ protected ImageAnnotatorApi(ImageAnnotatorSettings settings) throws IOException { this.settings = settings; @@ -146,7 +140,8 @@ public final ImageAnnotatorSettings getSettings() { /** * Run image detection and annotation for a batch of images. * - * Sample code: + *

Sample code: + * *


    * try (ImageAnnotatorApi imageAnnotatorApi = ImageAnnotatorApi.create()) {
    *   List<AnnotateImageRequest> requests = new ArrayList<>();
@@ -168,7 +163,8 @@ public final BatchAnnotateImagesResponse batchAnnotateImages(
   /**
    * Run image detection and annotation for a batch of images.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ImageAnnotatorApi imageAnnotatorApi = ImageAnnotatorApi.create()) {
    *   List<AnnotateImageRequest> requests = new ArrayList<>();
@@ -191,7 +187,8 @@ private final BatchAnnotateImagesResponse batchAnnotateImages(
   /**
    * Run image detection and annotation for a batch of images.
    *
-   * Sample code:
+   * 

Sample code: + * *


    * try (ImageAnnotatorApi imageAnnotatorApi = ImageAnnotatorApi.create()) {
    *   List<AnnotateImageRequest> requests = new ArrayList<>();
diff --git a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorSettings.java b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorSettings.java
index cb742141e4e0..e23eb9a78f52 100644
--- a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorSettings.java
+++ b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorSettings.java
@@ -16,7 +16,6 @@
 import com.google.api.gax.core.ConnectionSettings;
 import com.google.api.gax.core.RetrySettings;
 import com.google.api.gax.grpc.ApiCallSettings;
-import com.google.api.gax.grpc.PageStreamingDescriptor;
 import com.google.api.gax.grpc.ServiceApiSettings;
 import com.google.api.gax.grpc.SimpleCallSettings;
 import com.google.auth.Credentials;
@@ -42,15 +41,14 @@
  * 

The default instance has everything set to sensible defaults: * *

    - *
  • The default service address (vision.googleapis.com) and default port (443) - * are used. - *
  • Credentials are acquired automatically through Application Default Credentials. - *
  • Retries are configured for idempotent methods but not for non-idempotent methods. + *
  • The default service address (vision.googleapis.com) and default port (443) are used. + *
  • Credentials are acquired automatically through Application Default Credentials. + *
  • Retries are configured for idempotent methods but not for non-idempotent methods. *
* - *

The builder of this class is recursive, so contained classes are themselves builders. - * When build() is called, the tree of builders is called to create the complete settings - * object. For example, to set the total timeout of batchAnnotateImages to 30 seconds: + *

The builder of this class is recursive, so contained classes are themselves builders. When + * build() is called, the tree of builders is called to create the complete settings object. For + * example, to set the total timeout of batchAnnotateImages to 30 seconds: * *

  * 
@@ -64,25 +62,17 @@
  */
 @javax.annotation.Generated("by GAPIC")
 public class ImageAnnotatorSettings extends ServiceApiSettings {
-  /**
-   * The default address of the service.
-   */
+  /** The default address of the service. */
   private static final String DEFAULT_SERVICE_ADDRESS = "vision.googleapis.com";
 
-  /**
-   * The default port of the service.
-   */
+  /** The default port of the service. */
   private static final int DEFAULT_SERVICE_PORT = 443;
 
-  /**
-   * The default scopes of the service.
-   */
+  /** The default scopes of the service. */
   private static final ImmutableList DEFAULT_SERVICE_SCOPES =
       ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build();
 
-  /**
-   * The default connection settings of the service.
-   */
+  /** The default connection settings of the service. */
   public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS =
       ConnectionSettings.newBuilder()
           .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
@@ -93,52 +83,38 @@ public class ImageAnnotatorSettings extends ServiceApiSettings {
   private final SimpleCallSettings
       batchAnnotateImagesSettings;
 
-  /**
-   * Returns the object with the settings used for calls to batchAnnotateImages.
-   */
+  /** Returns the object with the settings used for calls to batchAnnotateImages. */
   public SimpleCallSettings
       batchAnnotateImagesSettings() {
     return batchAnnotateImagesSettings;
   }
 
-  /**
-   * Returns the default service address.
-   */
+  /** Returns the default service address. */
   public static String getDefaultServiceAddress() {
     return DEFAULT_SERVICE_ADDRESS;
   }
 
-  /**
-   * Returns the default service port.
-   */
+  /** Returns the default service port. */
   public static int getDefaultServicePort() {
     return DEFAULT_SERVICE_PORT;
   }
 
-  /**
-   * Returns the default service scopes.
-   */
+  /** Returns the default service scopes. */
   public static ImmutableList getDefaultServiceScopes() {
     return DEFAULT_SERVICE_SCOPES;
   }
 
-  /**
-   * Returns a builder for this class with recommended defaults.
-   */
+  /** Returns a builder for this class with recommended defaults. */
   public static Builder defaultBuilder() {
     return Builder.createDefault();
   }
 
-  /**
-   * Returns a new builder for this class.
-   */
+  /** Returns a new builder for this class. */
   public static Builder newBuilder() {
     return new Builder();
   }
 
-  /**
-   * Returns a builder containing all the values of this settings class.
-   */
+  /** Returns a builder containing all the values of this settings class. */
   public Builder toBuilder() {
     return new Builder(this);
   }
@@ -155,9 +131,7 @@ private ImageAnnotatorSettings(Builder settingsBuilder) throws IOException {
     batchAnnotateImagesSettings = settingsBuilder.batchAnnotateImagesSettings().build();
   }
 
-  /**
-   * Builder for ImageAnnotatorSettings.
-   */
+  /** Builder for ImageAnnotatorSettings. */
   public static class Builder extends ServiceApiSettings.Builder {
     private final ImmutableList methodSettingsBuilders;
 
@@ -274,18 +248,15 @@ public Builder setClientLibHeader(String name, String version) {
     }
 
     /**
-     * Applies the given settings to all of the API methods in this service. Only
-     * values that are non-null will be applied, so this method is not capable
-     * of un-setting any values.
+     * Applies the given settings to all of the API methods in this service. Only values that are
+     * non-null will be applied, so this method is not capable of un-setting any values.
      */
     public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception {
       super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings);
       return this;
     }
 
-    /**
-     * Returns the builder for the settings used for calls to batchAnnotateImages.
-     */
+    /** Returns the builder for the settings used for calls to batchAnnotateImages. */
     public SimpleCallSettings.Builder
         batchAnnotateImagesSettings() {
       return batchAnnotateImagesSettings;
diff --git a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/package-info.java b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/package-info.java
index 99f77552a7b2..96458058a2f6 100644
--- a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/package-info.java
+++ b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/package-info.java
@@ -15,17 +15,16 @@
 /**
  * A client to Google Cloud Vision API.
  *
- * The interfaces provided are listed below, along with a usage sample
+ * 

The interfaces provided are listed below, along with a usage sample * - * ================= - * ImageAnnotatorApi - * ================= + *

================= ImageAnnotatorApi ================= * - * Service Description: Service that performs Google Cloud Vision API detection tasks, such as face, - * landmark, logo, label, and text detection, over client images, and returns - * detected entities from the images. + *

Service Description: Service that performs Google Cloud Vision API detection tasks, such as + * face, landmark, logo, label, and text detection, over client images, and returns detected + * entities from the images. + * + *

Sample for ImageAnnotatorApi: * - * Sample for ImageAnnotatorApi: *

  * 
  * try (ImageAnnotatorApi imageAnnotatorApi = ImageAnnotatorApi.create()) {
@@ -34,6 +33,5 @@
  * }
  * 
  * 
- * */ package com.google.cloud.vision.spi.v1; diff --git a/google-cloud-vision/src/test/java/com/google/cloud/vision/spi/v1/ImageAnnotatorTest.java b/google-cloud-vision/src/test/java/com/google/cloud/vision/spi/v1/ImageAnnotatorTest.java index c9afa9f00c43..c617612031f9 100644 --- a/google-cloud-vision/src/test/java/com/google/cloud/vision/spi/v1/ImageAnnotatorTest.java +++ b/google-cloud-vision/src/test/java/com/google/cloud/vision/spi/v1/ImageAnnotatorTest.java @@ -14,13 +14,11 @@ package com.google.cloud.vision.spi.v1; -import com.google.api.gax.core.PagedListResponse; import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; import com.google.cloud.vision.v1.AnnotateImageRequest; import com.google.cloud.vision.v1.BatchAnnotateImagesRequest; import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; -import com.google.common.collect.Lists; import com.google.protobuf.GeneratedMessageV3; import java.io.IOException; import java.util.ArrayList; From 46f808b39c0f73dfd8fa9dd3903a59584b47e33c Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Wed, 5 Oct 2016 08:17:56 +0200 Subject: [PATCH 07/32] Support using more recent datastore emulator versions via gcloud emulators (#1303) --- .../testing/LocalDatastoreHelper.java | 67 +++++++++++++++++-- 1 file changed, 61 insertions(+), 6 deletions(-) diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java index 35e1d0593641..eab79e949989 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java @@ -55,9 +55,11 @@ import java.util.Arrays; import java.util.List; import java.util.Locale; +import java.util.Objects; import java.util.UUID; import java.util.logging.Level; import java.util.logging.Logger; +import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; @@ -67,7 +69,7 @@ */ public class LocalDatastoreHelper { private static final Logger log = Logger.getLogger(LocalDatastoreHelper.class.getName()); - private static final String GCD_VERSION = "1.2.0"; + private static final Version GCD_VERSION = Version.fromString("1.2.0"); private static final double DEFAULT_CONSISTENCY = 0.9; private static final String GCD_BASENAME = "cloud-datastore-emulator-" + GCD_VERSION; private static final String GCD_FILENAME = GCD_BASENAME + ".zip"; @@ -120,8 +122,8 @@ private static Path installedGcdPath() { Path installedGcdPath = gcloudPath.resolve("platform").resolve("cloud-datastore-emulator"); if (Files.exists(installedGcdPath)) { try { - String installedVersion = installedGcdVersion(); - if (installedVersion != null && installedVersion.startsWith(GCD_VERSION)) { + Version installedVersion = installedGcdVersion(); + if (installedVersion != null && installedVersion.compareTo(GCD_VERSION) >= 0) { if (log.isLoggable(Level.FINE)) { log.fine("SDK datastore emulator found"); } @@ -131,14 +133,14 @@ private static Path installedGcdPath() { log.fine("SDK datastore emulator found but version mismatch"); } } - } catch (IOException | InterruptedException ignore) { + } catch (IOException | InterruptedException | IllegalArgumentException ignore) { // ignore } } return null; } - private static String installedGcdVersion() throws IOException, InterruptedException { + private static Version installedGcdVersion() throws IOException, InterruptedException { Process process = CommandWrapper.create().command("gcloud", "version").redirectErrorStream().start(); process.waitFor(); @@ -148,7 +150,7 @@ private static String installedGcdVersion() throws IOException, InterruptedExcep if (line.startsWith(GCD_VERSION_PREFIX)) { String[] lineComponents = line.split(" "); if (lineComponents.length > 1) { - return lineComponents[1]; + return Version.fromString(lineComponents[1]); } } } @@ -171,6 +173,59 @@ private static Path executablePath(String cmd) { return null; } + private static class Version implements Comparable { + + private static final Pattern VERSION_PATTERN = Pattern.compile("(\\d+).(\\d+).(\\d+)"); + + final int major; + final int minor; + final int patch; + + Version(int major, int minor, int patch) { + this.major = major; + this.minor = minor; + this.patch = patch; + } + + @Override + public int compareTo(Version version) { + int result = major - version.major; + if (result == 0) { + result = minor - version.minor; + if (result == 0) { + result = patch - version.patch; + } + } + return result; + } + + @Override + public String toString() { + return String.format("%d.%d.%d", major, minor, patch); + } + + @Override + public boolean equals(Object other) { + return this == other || other instanceof Version && compareTo((Version) other) == 0; + } + + @Override + public int hashCode() { + return Objects.hash(major, minor, patch); + } + + static Version fromString(String version) { + Matcher matcher = VERSION_PATTERN.matcher(version); + if (matcher.matches()) { + return new Version( + Integer.valueOf(matcher.group(1)), + Integer.valueOf(matcher.group(2)), + Integer.valueOf(matcher.group(3))); + } + throw new IllegalArgumentException("Invalid version format"); + } + } + private static class ProcessStreamReader extends Thread { private final BufferedReader reader; private volatile boolean terminated; From 513ca7034aca5395ab4e1b7a36899ffa56566af8 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Fri, 7 Oct 2016 16:23:25 +0200 Subject: [PATCH 08/32] Update datastore dependency, fix LocalDatastoreHelper version regex (#1311) --- google-cloud-datastore/pom.xml | 4 ++-- .../google/cloud/datastore/testing/LocalDatastoreHelper.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/google-cloud-datastore/pom.xml b/google-cloud-datastore/pom.xml index 7c80588b70ff..67aff1bd2ef3 100644 --- a/google-cloud-datastore/pom.xml +++ b/google-cloud-datastore/pom.xml @@ -25,12 +25,12 @@ com.google.cloud.datastore datastore-v1-protos - 1.2.0 + 1.3.0 com.google.cloud.datastore datastore-v1-proto-client - 1.2.0 + 1.3.0 guava-jdk5 diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java index eab79e949989..b8dbb6008fb0 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java @@ -175,7 +175,7 @@ private static Path executablePath(String cmd) { private static class Version implements Comparable { - private static final Pattern VERSION_PATTERN = Pattern.compile("(\\d+).(\\d+).(\\d+)"); + private static final Pattern VERSION_PATTERN = Pattern.compile("^(\\d+)\\.(\\d+)\\.(\\d+)$"); final int major; final int minor; From 8c9aca409f98f910569adba836be3f83e6dd0430 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Wed, 19 Oct 2016 13:03:19 +0200 Subject: [PATCH 09/32] Add support for PubSub emulator host variable (#1317) --- .../src/main/java/com/google/cloud/pubsub/PubSubOptions.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubOptions.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubOptions.java index c504a46292a6..e1693ee3cd38 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubOptions.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubOptions.java @@ -32,6 +32,7 @@ public class PubSubOptions extends GrpcServiceOptions SCOPES = ImmutableSet.of(PUBSUB_SCOPE); + private static final String EMULATOR_HOST_ENV_VAR = "PUBSUB_EMULATOR_HOST"; private static final String DEFAULT_HOST = PublisherSettings.getDefaultServiceAddress() + ':' + PublisherSettings.getDefaultServicePort(); @@ -66,7 +67,8 @@ public PubSubRpc create(PubSubOptions options) { @Override protected String defaultHost() { - return DEFAULT_HOST; + String host = System.getProperty(EMULATOR_HOST_ENV_VAR, System.getenv(EMULATOR_HOST_ENV_VAR)); + return host != null ? host : DEFAULT_HOST; } public static class Builder extends From 0f4a178fd44232c5c48a09b763592b31ec72c2f0 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Thu, 20 Oct 2016 08:54:41 +0200 Subject: [PATCH 10/32] Fix resource descriptor integration tests for Logging (#1323) --- .../cloud/examples/logging/snippets/ITLoggingSnippets.java | 3 +-- .../src/test/java/com/google/cloud/logging/BaseSystemTest.java | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITLoggingSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITLoggingSnippets.java index 7bcd543eb32e..b8737784ee06 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITLoggingSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITLoggingSnippets.java @@ -49,8 +49,7 @@ public class ITLoggingSnippets { "app_script_function", "dataproc_cluster", "ml_job", "bigquery_resource", "container", "gke_cluster", "cloud_debugger_resource", "http_load_balancer", "aws_ec2_instance", "client_auth_config_brand", "client_auth_config_client", "logging_log", "logging_sink", - "metric", "project", "testservice_matrix", "service_account", "deployment", - "dns_managed_zone"); + "metric", "project", "testservice_matrix", "service_account", "deployment"); private static Logging logging; private static LoggingSnippets loggingSnippets; diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java index f5693dedbc36..2d1dff31026c 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java @@ -65,8 +65,7 @@ public abstract class BaseSystemTest { "app_script_function", "dataproc_cluster", "ml_job", "bigquery_resource", "container", "gke_cluster", "cloud_debugger_resource", "http_load_balancer", "aws_ec2_instance", "client_auth_config_brand", "client_auth_config_client", "logging_log", "logging_sink", - "metric", "project", "testservice_matrix", "service_account", "deployment", - "dns_managed_zone"); + "metric", "project", "testservice_matrix", "service_account", "deployment"); @Rule public ExpectedException thrown = ExpectedException.none(); From 7bcfe3e9f95cc13ed21ecf38c7c3f44ad88cab96 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Thu, 20 Oct 2016 13:43:49 +0200 Subject: [PATCH 11/32] Rename setters/getters/builders for Datastore classes to meet proto conventions (#1315) * Rename setters/getters/builders for Datastore classes to meet proto conventions * Update Datastore examples, snippets and READMEs to use renamed getters/setters/builders * Make deprecated methods call renamed ones --- README.md | 8 +- TESTING.md | 2 +- google-cloud-datastore/README.md | 8 +- .../datastore/BaseDatastoreBatchWriter.java | 41 ++- .../google/cloud/datastore/BaseEntity.java | 52 ++- .../com/google/cloud/datastore/BaseKey.java | 135 +++++++- .../com/google/cloud/datastore/Batch.java | 21 +- .../com/google/cloud/datastore/BatchImpl.java | 18 ++ .../java/com/google/cloud/datastore/Blob.java | 12 +- .../com/google/cloud/datastore/BlobValue.java | 11 +- .../google/cloud/datastore/BooleanValue.java | 9 +- .../com/google/cloud/datastore/Cursor.java | 2 +- .../com/google/cloud/datastore/Datastore.java | 52 +-- .../cloud/datastore/DatastoreBatchWriter.java | 6 + .../cloud/datastore/DatastoreHelper.java | 4 +- .../google/cloud/datastore/DatastoreImpl.java | 22 +- .../com/google/cloud/datastore/DateTime.java | 28 +- .../google/cloud/datastore/DateTimeValue.java | 11 +- .../google/cloud/datastore/DoubleValue.java | 9 +- .../com/google/cloud/datastore/Entity.java | 29 +- .../google/cloud/datastore/EntityValue.java | 9 +- .../google/cloud/datastore/FullEntity.java | 15 + .../com/google/cloud/datastore/GqlQuery.java | 84 ++++- .../google/cloud/datastore/IncompleteKey.java | 42 ++- .../java/com/google/cloud/datastore/Key.java | 112 ++++++- .../google/cloud/datastore/KeyFactory.java | 6 +- .../com/google/cloud/datastore/KeyQuery.java | 4 +- .../com/google/cloud/datastore/KeyValue.java | 9 +- .../com/google/cloud/datastore/LatLng.java | 22 ++ .../google/cloud/datastore/LatLngValue.java | 9 +- .../com/google/cloud/datastore/ListValue.java | 32 +- .../com/google/cloud/datastore/LongValue.java | 9 +- .../com/google/cloud/datastore/NullValue.java | 9 +- .../google/cloud/datastore/PathElement.java | 46 +++ .../cloud/datastore/ProjectionEntity.java | 5 + .../datastore/ProjectionEntityQuery.java | 24 +- .../com/google/cloud/datastore/Query.java | 103 +++++- .../google/cloud/datastore/QueryResults.java | 34 +- .../cloud/datastore/QueryResultsImpl.java | 12 + .../com/google/cloud/datastore/RawValue.java | 10 +- .../google/cloud/datastore/StringValue.java | 9 +- .../cloud/datastore/StructuredQuery.java | 297 ++++++++++++++++-- .../google/cloud/datastore/Transaction.java | 80 ++++- .../cloud/datastore/TransactionImpl.java | 18 ++ .../com/google/cloud/datastore/Value.java | 43 ++- .../google/cloud/datastore/ValueBuilder.java | 12 + .../google/cloud/datastore/package-info.java | 8 +- .../testing/LocalDatastoreHelper.java | 34 ++ .../testing/RemoteDatastoreHelper.java | 13 +- .../cloud/datastore/testing/package-info.java | 2 +- .../BaseDatastoreBatchWriterTest.java | 56 ++-- .../cloud/datastore/BaseEntityTest.java | 41 ++- .../google/cloud/datastore/BaseKeyTest.java | 62 +++- .../com/google/cloud/datastore/BlobTest.java | 6 + .../google/cloud/datastore/BlobValueTest.java | 10 +- .../cloud/datastore/BooleanValueTest.java | 10 +- .../cloud/datastore/DatastoreHelperTest.java | 68 ++-- .../google/cloud/datastore/DatastoreTest.java | 288 ++++++++--------- .../google/cloud/datastore/DateTimeTest.java | 19 +- .../cloud/datastore/DateTimeValueTest.java | 10 +- .../cloud/datastore/DoubleValueTest.java | 9 + .../google/cloud/datastore/EntityTest.java | 42 ++- .../cloud/datastore/EntityValueTest.java | 13 +- .../cloud/datastore/FullEntityTest.java | 40 ++- .../cloud/datastore/IncompleteKeyTest.java | 71 +++-- .../cloud/datastore/KeyFactoryTest.java | 108 +++++-- .../com/google/cloud/datastore/KeyTest.java | 47 ++- .../google/cloud/datastore/KeyValueTest.java | 13 +- .../google/cloud/datastore/LatLngTest.java | 13 +- .../cloud/datastore/LatLngValueTest.java | 9 + .../google/cloud/datastore/ListValueTest.java | 31 +- .../google/cloud/datastore/LongValueTest.java | 9 + .../google/cloud/datastore/NullValueTest.java | 9 + .../cloud/datastore/PathElementTest.java | 28 ++ .../cloud/datastore/ProjectionEntityTest.java | 12 +- .../google/cloud/datastore/RawValueTest.java | 6 +- .../cloud/datastore/SerializationTest.java | 68 ++-- .../cloud/datastore/StringValueTest.java | 9 + .../cloud/datastore/StructuredQueryTest.java | 108 +++++-- .../com/google/cloud/datastore/ValueTest.java | 34 +- .../cloud/datastore/it/ITDatastoreTest.java | 263 ++++++++-------- .../testing/LocalDatastoreHelperTest.java | 20 +- .../examples/datastore/DatastoreExample.java | 52 +-- .../snippets/AddEntitiesAndRunQuery.java | 14 +- .../datastore/snippets/CreateEntity.java | 4 +- .../datastore/snippets/DatastoreSnippets.java | 52 +-- .../datastore/snippets/QuerySnippets.java | 97 +++++- .../snippets/TransactionSnippets.java | 68 ++-- .../datastore/snippets/UpdateEntity.java | 4 +- .../snippets/ITDatastoreSnippets.java | 10 +- .../datastore/snippets/ITQuerySnippets.java | 59 +++- .../snippets/ITTransactionSnippets.java | 46 +-- 92 files changed, 2678 insertions(+), 852 deletions(-) diff --git a/README.md b/README.md index c2eea2a7da6a..28b7b9a91848 100644 --- a/README.md +++ b/README.md @@ -282,9 +282,9 @@ import com.google.cloud.datastore.Key; import com.google.cloud.datastore.KeyFactory; Datastore datastore = DatastoreOptions.defaultInstance().service(); -KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind"); +KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind"); Key key = keyFactory.newKey("keyName"); -Entity entity = Entity.builder(key) +Entity entity = Entity.newBuilder(key) .set("name", "John Doe") .set("age", 30) .set("access_time", DateTime.now()) @@ -303,12 +303,12 @@ import com.google.cloud.datastore.Key; import com.google.cloud.datastore.KeyFactory; Datastore datastore = DatastoreOptions.defaultInstance().service(); -KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind"); +KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind"); Key key = keyFactory.newKey("keyName"); Entity entity = datastore.get(key); if (entity != null) { System.out.println("Updating access_time for " + entity.getString("name")); - entity = Entity.builder(entity) + entity = Entity.newBuilder(entity) .set("access_time", DateTime.now()) .build(); datastore.update(entity); diff --git a/TESTING.md b/TESTING.md index 830f2b72ca78..a2439fdb04f1 100644 --- a/TESTING.md +++ b/TESTING.md @@ -84,7 +84,7 @@ You can test against a temporary local Datastore by following these steps: 2. Create and use a `Datastore` object with the options given by the `LocalDatastoreHelper` instance. For example: ```java - Datastore localDatastore = helper.options().service(); + Datastore localDatastore = helper.getOptions().service(); ``` 3. Run your tests. diff --git a/google-cloud-datastore/README.md b/google-cloud-datastore/README.md index b974fb7adff4..f4bd23333540 100644 --- a/google-cloud-datastore/README.md +++ b/google-cloud-datastore/README.md @@ -92,7 +92,7 @@ Then add the following code to put an entity in Datastore. ```java KeyFactory keyFactory = datastore.newKeyFactory().kind("Person"); Key key = keyFactory.newKey("john.doe@gmail.com"); -Entity entity = Entity.builder(key) +Entity entity = Entity.newBuilder(key) .set("name", "John Doe") .set("age", 51) .set("favorite_food", "pizza") @@ -126,9 +126,9 @@ import com.google.cloud.datastore.StructuredQuery.PropertyFilter; Then add the following code to your program: ```java -Query query = Query.entityQueryBuilder() - .kind("Person") - .filter(PropertyFilter.eq("favorite_food", "pizza")) +Query query = Query.newEntityQueryBuilder() + .setKind("Person") + .setFilter(PropertyFilter.eq("favorite_food", "pizza")) .build(); QueryResults results = datastore.run(query); while (results.hasNext()) { diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BaseDatastoreBatchWriter.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BaseDatastoreBatchWriter.java index e91bef5842d0..6a69e271fc32 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BaseDatastoreBatchWriter.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BaseDatastoreBatchWriter.java @@ -52,7 +52,7 @@ protected BaseDatastoreBatchWriter(String name) { public final void addWithDeferredIdAllocation(FullEntity... entities) { validateActive(); for (FullEntity entity : entities) { - IncompleteKey key = entity.key(); + IncompleteKey key = entity.getKey(); Preconditions.checkArgument(key != null, "Entity must have a key"); if (key instanceof Key) { addInternal((FullEntity) entity); @@ -63,10 +63,10 @@ public final void addWithDeferredIdAllocation(FullEntity... entities) { } private void addInternal(FullEntity entity) { - Key key = entity.key(); + Key key = entity.getKey(); if (toAdd.containsKey(key) || toUpdate.containsKey(key) || toPut.containsKey(key)) { throw newInvalidRequest("Entity with the key %s was already added or updated in this %s", - entity.key(), name); + entity.getKey(), name); } if (toDelete.remove(key)) { toPut.put(key, entity); @@ -86,7 +86,7 @@ public final List add(FullEntity... entities) { validateActive(); List incompleteKeys = Lists.newArrayListWithExpectedSize(entities.length); for (FullEntity entity : entities) { - IncompleteKey key = entity.key(); + IncompleteKey key = entity.getKey(); Preconditions.checkArgument(key != null, "Entity must have a key"); if (!(key instanceof Key)) { incompleteKeys.add(key); @@ -95,17 +95,17 @@ public final List add(FullEntity... entities) { Iterator allocated; if (!incompleteKeys.isEmpty()) { IncompleteKey[] toAllocate = Iterables.toArray(incompleteKeys, IncompleteKey.class); - allocated = datastore().allocateId(toAllocate).iterator(); + allocated = getDatastore().allocateId(toAllocate).iterator(); } else { allocated = Collections.emptyIterator(); } List answer = Lists.newArrayListWithExpectedSize(entities.length); for (FullEntity entity : entities) { - if (entity.key() instanceof Key) { + if (entity.getKey() instanceof Key) { addInternal((FullEntity) entity); answer.add(Entity.convert((FullEntity) entity)); } else { - Entity entityWithAllocatedId = Entity.builder(allocated.next(), entity).build(); + Entity entityWithAllocatedId = Entity.newBuilder(allocated.next(), entity).build(); addInternal(entityWithAllocatedId); answer.add(entityWithAllocatedId); } @@ -118,10 +118,10 @@ public final List add(FullEntity... entities) { public final void update(Entity... entities) { validateActive(); for (Entity entity : entities) { - Key key = entity.key(); + Key key = entity.getKey(); if (toDelete.contains(key)) { throw newInvalidRequest("Entity with the key %s was already deleted in this %s", - entity.key(), name); + entity.getKey(), name); } if (toAdd.remove(key) != null || toPut.containsKey(key)) { toPut.put(key, entity); @@ -132,7 +132,7 @@ public final void update(Entity... entities) { } private void putInternal(FullEntity entity) { - Key key = entity.key(); + Key key = entity.getKey(); toAdd.remove(key); toUpdate.remove(key); toDelete.remove(key); @@ -149,7 +149,7 @@ public final Entity put(FullEntity entity) { public final void putWithDeferredIdAllocation(FullEntity... entities) { validateActive(); for (FullEntity entity : entities) { - IncompleteKey key = entity.key(); + IncompleteKey key = entity.getKey(); Preconditions.checkArgument(key != null, "Entity must have a key"); if (key instanceof Key) { putInternal(Entity.convert((FullEntity) entity)); @@ -165,7 +165,7 @@ public final List put(FullEntity... entities) { validateActive(); List incompleteKeys = Lists.newArrayListWithExpectedSize(entities.length); for (FullEntity entity : entities) { - IncompleteKey key = entity.key(); + IncompleteKey key = entity.getKey(); Preconditions.checkArgument(key != null, "Entity must have a key"); if (!(key instanceof Key)) { incompleteKeys.add(key); @@ -174,17 +174,17 @@ public final List put(FullEntity... entities) { Iterator allocated; if (!incompleteKeys.isEmpty()) { IncompleteKey[] toAllocate = Iterables.toArray(incompleteKeys, IncompleteKey.class); - allocated = datastore().allocateId(toAllocate).iterator(); + allocated = getDatastore().allocateId(toAllocate).iterator(); } else { allocated = Collections.emptyIterator(); } List answer = Lists.newArrayListWithExpectedSize(entities.length); for (FullEntity entity : entities) { - if (entity.key() instanceof Key) { + if (entity.getKey() instanceof Key) { putInternal((FullEntity) entity); answer.add(Entity.convert((FullEntity) entity)); } else { - Entity entityWithAllocatedId = Entity.builder(allocated.next(), entity).build(); + Entity entityWithAllocatedId = Entity.newBuilder(allocated.next(), entity).build(); putInternal(entityWithAllocatedId); answer.add(entityWithAllocatedId); } @@ -204,11 +204,17 @@ public final void delete(Key... keys) { } @Override + @Deprecated public boolean active() { + return isActive(); + } + + @Override + public boolean isActive() { return active; } - protected String name() { + protected String getName() { return name; } @@ -270,5 +276,8 @@ protected List toMutationPbList() { return mutationsPb; } + @Deprecated protected abstract Datastore datastore(); + + protected abstract Datastore getDatastore(); } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BaseEntity.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BaseEntity.java index b4aa57efec7a..b41507158bba 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BaseEntity.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BaseEntity.java @@ -65,7 +65,7 @@ public abstract static class Builder entity) { @@ -73,15 +73,15 @@ public abstract static class Builder entity) { - key(key); - properties(entity.properties); + setKey(key); + setProperties(entity.properties); } protected K key() { return key; } - protected Map> properties() { + protected Map> setProperties() { return properties; } @@ -94,22 +94,33 @@ private B self() { B fill(com.google.datastore.v1.Entity entityPb) { Map> copiedProperties = Maps.newHashMap(); for (Map.Entry entry : - entityPb.getProperties().entrySet()) { + entityPb.getPropertiesMap().entrySet()) { copiedProperties.put(entry.getKey(), Value.fromPb(entry.getValue())); } - properties(copiedProperties); + setProperties(copiedProperties); if (entityPb.hasKey()) { - key((K) IncompleteKey.fromPb(entityPb.getKey())); + setKey((K) IncompleteKey.fromPb(entityPb.getKey())); } return self(); } - protected B properties(Map> properties) { + protected B setProperties(Map> properties) { this.properties.putAll(properties); return self(); } + /** + * Sets the key for the entity. + */ + @Deprecated public B key(K key) { + return setKey(key); + } + + /** + * Sets the key for the entity. + */ + public B setKey(K key) { this.key = key; return self(); } @@ -401,7 +412,7 @@ public B set(String name, List> values) { * @param others other values in the list */ public B set(String name, Value first, Value second, Value... others) { - properties.put(name, ListValue.builder().addValue(first).addValue(second, others).build()); + properties.put(name, ListValue.newBuilder().addValue(first).addValue(second, others).build()); return self(); } @@ -454,7 +465,7 @@ public B setNull(String name) { } BaseEntity(BaseEntity from) { - this.key = from.key(); + this.key = from.getKey(); this.properties = from.properties; } @@ -494,7 +505,15 @@ public boolean hasKey() { /** * Returns the associated key or null if it does not have one. */ + @Deprecated public K key() { + return getKey(); + } + + /** + * Returns the associated key or null if it does not have one. + */ + public K getKey() { return key; } @@ -642,19 +661,26 @@ public Blob getBlob(String name) { /** * Returns the properties name. */ + @Deprecated public Set names() { + return getNames(); + } + + /** + * Returns the properties name. + */ + public Set getNames() { return properties.keySet(); } - ImmutableSortedMap> properties() { + ImmutableSortedMap> getProperties() { return properties; } final com.google.datastore.v1.Entity toPb() { com.google.datastore.v1.Entity.Builder entityPb = com.google.datastore.v1.Entity.newBuilder(); - Map propertiesPb = entityPb.getMutableProperties(); for (Map.Entry> entry : properties.entrySet()) { - propertiesPb.put(entry.getKey(), entry.getValue().toPb()); + entityPb.putProperties(entry.getKey(), entry.getValue().toPb()); } if (key != null) { entityPb.setKey(key.toPb()); diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BaseKey.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BaseKey.java index 9623c46b7c63..7736660b56a5 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BaseKey.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BaseKey.java @@ -65,10 +65,10 @@ protected abstract static class Builder> { } Builder(BaseKey copyFrom) { - projectId = copyFrom.projectId(); - namespace = copyFrom.namespace(); - ancestors = new LinkedList<>(copyFrom.ancestors()); - kind = copyFrom.kind(); + projectId = copyFrom.getProjectId(); + namespace = copyFrom.getNamespace(); + ancestors = new LinkedList<>(copyFrom.getAncestors()); + kind = copyFrom.getKind(); } @SuppressWarnings("unchecked") @@ -76,17 +76,50 @@ B self() { return (B) this; } + /** + * Adds an ancestor for this key. + */ + @Deprecated public B ancestors(PathElement ancestor) { + return addAncestor(ancestor); + } + + /** + * Adds an ancestor for this key. + */ + public B addAncestor(PathElement ancestor) { Preconditions.checkState(ancestors.size() < MAX_PATH, "path can have at most 100 elements"); ancestors.add(ancestor); return self(); } + /** + * Adds an ancestor to the key. + */ + @Deprecated public B ancestors(PathElement ancestor, PathElement... other) { - return ancestors(ImmutableList.builder().add(ancestor).add(other).build()); + return addAncestors(ancestor, other); } + /** + * Adds the provided ancestors to the key. + */ + public B addAncestors(PathElement ancestor, PathElement... other) { + return addAncestors(ImmutableList.builder().add(ancestor).add(other).build()); + } + + /** + * Adds the provided ancestors to the key. + */ + @Deprecated public B ancestors(Iterable ancestors) { + return addAncestors(ancestors); + } + + /** + * Adds the provided ancestors to the key. + */ + public B addAncestors(Iterable ancestors) { ImmutableList list = ImmutableList.copyOf(ancestors); Preconditions.checkState(this.ancestors.size() + list.size() < MAX_PATH, "path can have at most 100 elements"); @@ -94,17 +127,50 @@ public B ancestors(Iterable ancestors) { return self(); } + /** + * Sets the kind of the key. + */ + @Deprecated public B kind(String kind) { + return setKind(kind); + } + + /** + * Sets the kind of the key. + */ + public B setKind(String kind) { this.kind = validateKind(kind); return self(); } + /** + * Sets the project ID of the key. + */ + @Deprecated public B projectId(String projectId) { + return setProjectId(projectId); + } + + /** + * Sets the project ID of the key. + */ + public B setProjectId(String projectId) { this.projectId = validateDatabase(projectId); return self(); } + /** + * Sets the namespace of the key. + */ + @Deprecated public B namespace(String namespace) { + return setNamespace(namespace); + } + + /** + * Sets the namespace of the key. + */ + public B setNamespace(String namespace) { this.namespace = validateNamespace(namespace); return self(); } @@ -122,44 +188,87 @@ public B namespace(String namespace) { /** * Returns the key's projectId. */ + @Deprecated public String projectId() { + return getProjectId(); + } + + /** + * Returns the key's projectId. + */ + public String getProjectId() { return projectId; } /** * Returns the key's namespace or {@code null} if not provided. */ + @Deprecated public String namespace() { + return getNamespace(); + } + + /** + * Returns the key's namespace or {@code null} if not provided. + */ + public String getNamespace() { return namespace; } /** * Returns an immutable list with the key's ancestors. */ + @Deprecated public List ancestors() { - return path().subList(0, path().size() - 1); + return getAncestors(); + } + + /** + * Returns an immutable list with the key's ancestors. + */ + public List getAncestors() { + return getPath().subList(0, getPath().size() - 1); } /** * Returns an immutable list of the key's path (ancestors + self). */ + @Deprecated List path() { + return getPath(); + } + + /** + * Returns an immutable list of the key's path (ancestors + self). + */ + List getPath() { return path; } - PathElement leaf() { - return path().get(path().size() - 1); + PathElement getLeaf() { + return getPath().get(getPath().size() - 1); } /** * Returns the key's kind. */ + @Deprecated public String kind() { - return leaf().kind(); + return getKind(); } + /** + * Returns the key's kind. + */ + public String getKind() { + return getLeaf().getKind(); + } + + @Deprecated abstract BaseKey parent(); + abstract BaseKey getParent(); + @Override public String toString() { return MoreObjects.toStringHelper(this) @@ -171,7 +280,7 @@ public String toString() { @Override public int hashCode() { - return Objects.hash(projectId(), namespace(), path()); + return Objects.hash(getProjectId(), getNamespace(), getPath()); } @Override @@ -183,9 +292,9 @@ public boolean equals(Object obj) { return false; } BaseKey other = (BaseKey) obj; - return Objects.equals(projectId(), other.projectId()) - && Objects.equals(namespace(), other.namespace()) - && Objects.equals(path(), other.path()); + return Objects.equals(getProjectId(), other.getProjectId()) + && Objects.equals(getNamespace(), other.getNamespace()) + && Objects.equals(getPath(), other.getPath()); } com.google.datastore.v1.Key toPb() { diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Batch.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Batch.java index dbe6f86c4b99..184fd0831cc9 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Batch.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Batch.java @@ -26,9 +26,9 @@ *
 {@code
  * Entity entity1 = datastore.get(key1);
  * Batch batch = datastore.newBatch();
- * Entity entity2 = Entity.builder(key2).set("name", "John").build();
- * entity1 = Entity.builder(entity1).clear().setNull("bla").build();
- * Entity entity3 = Entity.builder(key3).set("title", "title").build();
+ * Entity entity2 = Entity.newBuilder(key2).set("name", "John").build();
+ * entity1 = Entity.newBuilder(entity1).clear().setNull("bla").build();
+ * Entity entity3 = Entity.newBuilder(key3).set("title", "title").build();
  * batch.update(entity1);
  * batch.add(entity2, entity3);
  * batch.submit();
@@ -37,7 +37,16 @@
 public interface Batch extends DatastoreBatchWriter {
 
   interface Response {
+    /**
+     * Returns a list of keys generated by a batch.
+     */
+    @Deprecated
     List generatedKeys();
+
+    /**
+     * Returns a list of keys generated by a batch.
+     */
+    List getGeneratedKeys();
   }
 
   /**
@@ -50,5 +59,11 @@ interface Response {
   /**
    * Returns the batch associated {@link Datastore}.
    */
+  @Deprecated
   Datastore datastore();
+
+  /**
+   * Returns the batch associated {@link Datastore}.
+   */
+  Datastore getDatastore();
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BatchImpl.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BatchImpl.java
index f61c0ae846d4..e979b54f4d20 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BatchImpl.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BatchImpl.java
@@ -35,6 +35,7 @@ static class ResponseImpl implements Batch.Response {
     }
 
     @Override
+    @Deprecated
     public List generatedKeys() {
       Iterator results =
           response.getMutationResultsList().iterator();
@@ -44,6 +45,17 @@ public List generatedKeys() {
       }
       return generated;
     }
+
+    @Override
+    public List getGeneratedKeys() {
+      Iterator results =
+          response.getMutationResultsList().iterator();
+      List generated = new ArrayList<>(numAutoAllocatedIds);
+      for (int i = 0; i < numAutoAllocatedIds; i++) {
+        generated.add(Key.fromPb(results.next().getKey()));
+      }
+      return generated;
+    }
   }
 
   BatchImpl(DatastoreImpl datastore) {
@@ -65,7 +77,13 @@ public Batch.Response submit() {
   }
 
   @Override
+  @Deprecated
   public Datastore datastore() {
+    return getDatastore();
+  }
+
+  @Override
+  public Datastore getDatastore() {
     return datastore;
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Blob.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Blob.java
index 22fac0a5d09f..3d5ad6ff374b 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Blob.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Blob.java
@@ -72,7 +72,15 @@ public boolean equals(Object obj) {
   /**
    * Returns the size of this blob.
    */
+  @Deprecated
   public int length() {
+    return getLength();
+  }
+
+  /**
+   * Returns the size of this blob.
+   */
+  public int getLength() {
     return byteString.size();
   }
 
@@ -119,10 +127,10 @@ public void copyTo(ByteBuffer target) {
    * @throws IndexOutOfBoundsException if an offset or size is negative or too large
    */
   public void copyTo(byte[] target) {
-    byteString.copyTo(target, 0, 0, length());
+    byteString.copyTo(target, 0, 0, getLength());
   }
 
-  ByteString byteString() {
+  ByteString getByteString() {
     return byteString;
   }
 
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BlobValue.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BlobValue.java
index 5f2243e36447..1023ddfbee29 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BlobValue.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BlobValue.java
@@ -34,7 +34,7 @@ public int getProtoFieldId() {
 
         @Override
         public Builder newBuilder(Blob value) {
-          return builder(value);
+          return BlobValue.newBuilder(value);
         }
 
         @Override
@@ -44,7 +44,7 @@ protected Blob getValue(com.google.datastore.v1.Value from) {
 
         @Override
         protected void setValue(BlobValue from, com.google.datastore.v1.Value.Builder to) {
-          to.setBlobValue(from.get().byteString());
+          to.setBlobValue(from.get().getByteString());
         }
       };
 
@@ -61,7 +61,7 @@ public BlobValue build() {
   }
 
   public BlobValue(Blob blob) {
-    this(builder(blob));
+    this(newBuilder(blob));
   }
 
   private BlobValue(Builder builder) {
@@ -77,7 +77,12 @@ public static BlobValue of(Blob blob) {
     return new BlobValue(blob);
   }
 
+  @Deprecated
   public static Builder builder(Blob blob) {
+    return newBuilder(blob);
+  }
+
+  public static Builder newBuilder(Blob blob) {
     return new Builder().set(blob);
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BooleanValue.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BooleanValue.java
index 9fb930e6d5a5..c0339df6ab17 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BooleanValue.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/BooleanValue.java
@@ -34,7 +34,7 @@ public int getProtoFieldId() {
 
         @Override
         public Builder newBuilder(Boolean value) {
-          return builder(value);
+          return BooleanValue.newBuilder(value);
         }
 
         @Override
@@ -61,7 +61,7 @@ public BooleanValue build() {
   }
 
   public BooleanValue(boolean value) {
-    this(builder(value));
+    this(newBuilder(value));
   }
 
   private BooleanValue(Builder builder) {
@@ -77,7 +77,12 @@ public static BooleanValue of(boolean value) {
     return new BooleanValue(value);
   }
 
+  @Deprecated
   public static Builder builder(boolean value) {
+    return newBuilder(value);
+  }
+
+  public static Builder newBuilder(boolean value) {
     return new Builder().set(value);
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Cursor.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Cursor.java
index f0fdf0e07212..9a60cb83944a 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Cursor.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Cursor.java
@@ -59,7 +59,7 @@ public String toString() {
     return toStringHelper.add("bytes", stBuilder.toString()).toString();
   }
 
-  ByteString byteString() {
+  ByteString getByteString() {
     return byteString;
   }
 
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Datastore.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Datastore.java
index 2d590bdaa730..afb0058c7fae 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Datastore.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Datastore.java
@@ -76,11 +76,11 @@ interface TransactionCallable {
    * 
 {@code
    * String keyName1 = "my_key_name_1";
    * String keyName2 = "my_key_name_2";
-   * Key key1 = datastore.newKeyFactory().kind("MyKind").newKey(keyName1);
-   * Key key2 = datastore.newKeyFactory().kind("MyKind").newKey(keyName2);
+   * Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
+   * Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
    * Batch batch = datastore.newBatch();
-   * Entity entity1 = Entity.builder(key1).set("name", "John").build();
-   * Entity entity2 = Entity.builder(key2).set("title", "title").build();
+   * Entity entity1 = Entity.newBuilder(key1).set("name", "John").build();
+   * Entity entity2 = Entity.newBuilder(key2).set("title", "title").build();
    * batch.add(entity1);
    * batch.add(entity2);
    * batch.submit();
@@ -96,7 +96,7 @@ interface TransactionCallable {
    *
    * 

Example of allocating an id. *

 {@code
-   * KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind");
+   * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
    * IncompleteKey incompleteKey = keyFactory.newKey();
    * 
    * // let cloud datastore automatically assign an id
@@ -112,7 +112,7 @@ interface TransactionCallable {
    *
    * 

Example of allocating multiple ids in a single batch. *

 {@code
-   * KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind");
+   * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
    * IncompleteKey incompleteKey1 = keyFactory.newKey();
    * IncompleteKey incompleteKey2 = keyFactory.newKey();
    * 
@@ -132,13 +132,13 @@ interface TransactionCallable {
    * 
 {@code
    * String keyName1 = "my_key_name_1";
    * String keyName2 = "my_key_name_2";
-   * Key key1 = datastore.newKeyFactory().kind("MyKind").newKey(keyName1);
-   * Entity.Builder entityBuilder1 = Entity.builder(key1);
+   * Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
+   * Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
    * entityBuilder1.set("propertyName", "updatedValue1");
    * Entity entity1 = entityBuilder1.build();
    * 
-   * Key key2 = datastore.newKeyFactory().kind("MyKind").newKey(keyName2);
-   * Entity.Builder entityBuilder2 = Entity.builder(key2);
+   * Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
+   * Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
    * entityBuilder2.set("propertyName", "updatedValue2");
    * Entity entity2 = entityBuilder2.build();
    * 
@@ -156,8 +156,8 @@ interface TransactionCallable {
    * 

Example of putting a single entity. *

 {@code
    * String keyName = "my_key_name";
-   * Key key = datastore.newKeyFactory().kind("MyKind").newKey(keyName);
-   * Entity.Builder entityBuilder = Entity.builder(key);
+   * Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
+   * Entity.Builder entityBuilder = Entity.newBuilder(key);
    * entityBuilder.set("propertyName", "value");
    * Entity entity = entityBuilder.build();
    * datastore.put(entity);
@@ -175,13 +175,13 @@ interface TransactionCallable {
    * 
 {@code
    * String keyName1 = "my_key_name1";
    * String keyName2 = "my_key_name2";
-   * Key key1 = datastore.newKeyFactory().kind("MyKind").newKey(keyName1);
-   * Entity.Builder entityBuilder1 = Entity.builder(key1);
+   * Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
+   * Entity.Builder entityBuilder1 = Entity.newBuilder(key1);
    * entityBuilder1.set("propertyName", "value1");
    * Entity entity1 = entityBuilder1.build();
    * 
-   * Key key2 = datastore.newKeyFactory().kind("MyKind").newKey(keyName2);
-   * Entity.Builder entityBuilder2 = Entity.builder(key2);
+   * Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
+   * Entity.Builder entityBuilder2 = Entity.newBuilder(key2);
    * entityBuilder2.set("propertyName", "value2");
    * Entity entity2 = entityBuilder2.build();
    * 
@@ -200,8 +200,8 @@ interface TransactionCallable {
    * 
 {@code
    * String keyName1 = "my_key_name1";
    * String keyName2 = "my_key_name2";
-   * Key key1 = datastore.newKeyFactory().kind("MyKind").newKey(keyName1);
-   * Key key2 = datastore.newKeyFactory().kind("MyKind").newKey(keyName2);
+   * Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1);
+   * Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2);
    * datastore.delete(key1, key2);
    * }
* @@ -228,7 +228,7 @@ interface TransactionCallable { *

Example of getting an entity. *

 {@code
    * String keyName = "my_key_name";
-   * Key key = datastore.newKeyFactory().kind("MyKind").newKey(keyName);
+   * Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
    * Entity entity = datastore.get(key);
    * // Do something with the entity
    * }
@@ -248,7 +248,7 @@ interface TransactionCallable { *
 {@code
    * String firstKeyName = "my_first_key_name";
    * String secondKeyName = "my_second_key_name";
-   * KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind");
+   * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
    * Key firstKey = keyFactory.newKey(firstKeyName);
    * Key secondKey = keyFactory.newKey(secondKeyName);
    * Iterator entitiesIterator = datastore.get(Lists.newArrayList(firstKey, secondKey));
@@ -274,7 +274,7 @@ interface TransactionCallable {
    * 
 {@code
    * String firstKeyName = "my_first_key_name";
    * String secondKeyName = "my_second_key_name";
-   * KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind");
+   * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
    * Key firstKey = keyFactory.newKey(firstKeyName);
    * Key secondKey = keyFactory.newKey(secondKeyName);
    * List entities = datastore.fetch(Lists.newArrayList(firstKey, secondKey));
@@ -293,8 +293,8 @@ interface TransactionCallable {
    * 

Example of running a query to find all entities of one kind. *

 {@code
    * String kind = "my_kind";
-   * StructuredQuery query = Query.entityQueryBuilder()
-   *     .kind(kind)
+   * StructuredQuery query = Query.newEntityQueryBuilder()
+   *     .setKind(kind)
    *     .build();
    * QueryResults results = datastore.run(query);
    * List entities = Lists.newArrayList();
@@ -310,9 +310,9 @@ interface TransactionCallable {
    * String kind = "my_kind";
    * String property = "my_property";
    * String value = "my_value";
-   * StructuredQuery query = Query.entityQueryBuilder()
-   *     .kind(kind)
-   *     .filter(PropertyFilter.eq(property, value))
+   * StructuredQuery query = Query.newEntityQueryBuilder()
+   *     .setKind(kind)
+   *     .setFilter(PropertyFilter.eq(property, value))
    *     .build();
    * QueryResults results = datastore.run(query);
    * List entities = Lists.newArrayList();
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreBatchWriter.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreBatchWriter.java
index 32559ebb58d0..0900243569e8 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreBatchWriter.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreBatchWriter.java
@@ -89,5 +89,11 @@ interface DatastoreBatchWriter extends DatastoreWriter {
   /**
    * Returns {@code true} if still active (write operations were not sent to the Datastore).
    */
+  @Deprecated
   boolean active();
+
+  /**
+   * Returns {@code true} if still active (write operations were not sent to the Datastore).
+   */
+  boolean isActive();
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreHelper.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreHelper.java
index 655b1722b1ca..957839cf4301 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreHelper.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreHelper.java
@@ -79,7 +79,7 @@ private static List compileEntities(Key[] keys, Iterator entitie
     Map map = Maps.newHashMapWithExpectedSize(keys.length);
     while (entities.hasNext()) {
       Entity entity = entities.next();
-      map.put(entity.key(), entity);
+      map.put(entity.getKey(), entity);
     }
     List list = new ArrayList<>(keys.length);
     for (Key key : keys) {
@@ -99,7 +99,7 @@ static  T runInTransaction(Datastore datastore, Datastore.TransactionCallable
       transaction.rollback();
       throw DatastoreException.propagateUserException(ex);
     } finally {
-      if (transaction.active()) {
+      if (transaction.isActive()) {
         transaction.rollback();
       }
     }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreImpl.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreImpl.java
index 842e5f2eb5c3..892d397935df 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreImpl.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreImpl.java
@@ -139,7 +139,7 @@ public com.google.datastore.v1.AllocateIdsResponse call()
 
   private IncompleteKey trimNameOrId(IncompleteKey key) {
     if (key instanceof Key) {
-      return IncompleteKey.builder(key).build();
+      return IncompleteKey.newBuilder(key).build();
     }
     return key;
   }
@@ -159,13 +159,13 @@ public List add(FullEntity... entities) {
     Map completeEntities = new LinkedHashMap<>();
     for (FullEntity entity : entities) {
       Entity completeEntity = null;
-      if (entity.key() instanceof Key) {
+      if (entity.getKey() instanceof Key) {
         completeEntity = Entity.convert((FullEntity) entity);
       }
       if (completeEntity != null) {
-        if (completeEntities.put(completeEntity.key(), completeEntity) != null) {
+        if (completeEntities.put(completeEntity.getKey(), completeEntity) != null) {
           throw DatastoreException.throwInvalidRequest(
-            "Duplicate entity with the key %s", entity.key());
+            "Duplicate entity with the key %s", entity.getKey());
         }
       } else {
         Preconditions.checkArgument(entity.hasKey(), "Entity %s is missing a key", entity);
@@ -178,13 +178,13 @@ public List add(FullEntity... entities) {
         commitResponse.getMutationResultsList().iterator();
     ImmutableList.Builder responseBuilder = ImmutableList.builder();
     for (FullEntity entity : entities) {
-      Entity completeEntity = completeEntities.get(entity.key());
+      Entity completeEntity = completeEntities.get(entity.getKey());
       if (completeEntity != null) {
         responseBuilder.add(completeEntity);
         mutationResults.next();
       } else {
         responseBuilder.add(
-            Entity.builder(Key.fromPb(mutationResults.next().getKey()), entity).build());
+            Entity.newBuilder(Key.fromPb(mutationResults.next().getKey()), entity).build());
       }
     }
     return responseBuilder.build();
@@ -300,7 +300,7 @@ public void update(Entity... entities) {
       List mutationsPb = new ArrayList<>();
       Map dedupEntities = new LinkedHashMap<>();
       for (Entity entity : entities) {
-        dedupEntities.put(entity.key(), entity);
+        dedupEntities.put(entity.getKey(), entity);
       }
       for (Entity entity : dedupEntities.values()) {
         mutationsPb.add(
@@ -325,9 +325,9 @@ public List put(FullEntity... entities) {
     Map dedupEntities = new LinkedHashMap<>();
     for (FullEntity entity : entities) {
       Preconditions.checkArgument(entity.hasKey(), "Entity %s is missing a key", entity);
-      if (entity.key() instanceof Key) {
+      if (entity.getKey() instanceof Key) {
         Entity completeEntity = Entity.convert((FullEntity) entity);
-        dedupEntities.put(completeEntity.key(), completeEntity);
+        dedupEntities.put(completeEntity.getKey(), completeEntity);
       } else {
         mutationsPb.add(
             com.google.datastore.v1.Mutation.newBuilder().setUpsert(entity.toPb()).build());
@@ -342,12 +342,12 @@ public List put(FullEntity... entities) {
         commitResponse.getMutationResultsList().iterator();
     ImmutableList.Builder responseBuilder = ImmutableList.builder();
     for (FullEntity entity : entities) {
-      Entity completeEntity = dedupEntities.get(entity.key());
+      Entity completeEntity = dedupEntities.get(entity.getKey());
       if (completeEntity != null) {
         responseBuilder.add(completeEntity);
       } else {
         responseBuilder.add(
-            Entity.builder(Key.fromPb(mutationResults.next().getKey()), entity).build());
+            Entity.newBuilder(Key.fromPb(mutationResults.next().getKey()), entity).build());
       }
     }
     return responseBuilder.build();
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DateTime.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DateTime.java
index dee2558275bb..666b4b948ae5 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DateTime.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DateTime.java
@@ -43,7 +43,7 @@ public final class DateTime implements Comparable, Serializable {
 
   @Override
   public String toString() {
-    return ISODateTimeFormat.dateTime().print(timestampMillis());
+    return ISODateTimeFormat.dateTime().print(getTimestampMillis());
   }
 
   @Override
@@ -63,21 +63,43 @@ public boolean equals(Object obj) {
             && timestampMicroseconds == ((DateTime) obj).timestampMicroseconds);
   }
 
+  /**
+   * Returns the value of this timestamp in microseconds.
+   */
+  @Deprecated
   public long timestampMicroseconds() {
+    return getTimestampMicroseconds();
+  }
+
+  /**
+   * Returns the value of this timestamp in microseconds.
+   */
+  public long getTimestampMicroseconds() {
     return timestampMicroseconds;
   }
 
+  /**
+   * Returns the value of this timestamp in milliseconds.
+   */
+  @Deprecated
   public long timestampMillis() {
+    return getTimestampMillis();
+  }
+
+  /**
+   * Returns the value of this timestamp in milliseconds.
+   */
+  public long getTimestampMillis() {
     return timestampMicroseconds / 1000L;
   }
 
   public Date toDate() {
-    return new Date(timestampMillis());
+    return new Date(getTimestampMillis());
   }
 
   public Calendar toCalendar() {
     Calendar cal = Calendar.getInstance();
-    cal.setTimeInMillis(timestampMillis());
+    cal.setTimeInMillis(getTimestampMillis());
     return cal;
   }
 
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DateTimeValue.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DateTimeValue.java
index 534328f6c0d5..04226cc1e638 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DateTimeValue.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DateTimeValue.java
@@ -34,7 +34,7 @@ public int getProtoFieldId() {
 
         @Override
         public Builder newBuilder(DateTime value) {
-          return builder(value);
+          return DateTimeValue.newBuilder(value);
         }
 
         @Override
@@ -45,7 +45,7 @@ protected DateTime getValue(com.google.datastore.v1.Value from) {
         @Override
         protected void setValue(DateTimeValue from, com.google.datastore.v1.Value.Builder to) {
           to.setTimestampValue(DateTime.microsecondsToTimestampPb(from.get()
-              .timestampMicroseconds()));
+              .getTimestampMicroseconds()));
         }
       };
 
@@ -62,7 +62,7 @@ public DateTimeValue build() {
   }
 
   public DateTimeValue(DateTime dateTime) {
-    this(builder(dateTime));
+    this(newBuilder(dateTime));
   }
 
   private DateTimeValue(Builder builder) {
@@ -78,7 +78,12 @@ public static DateTimeValue of(DateTime dateTime) {
     return new DateTimeValue(dateTime);
   }
 
+  @Deprecated
   public static Builder builder(DateTime dateTime) {
+    return newBuilder(dateTime);
+  }
+
+  public static Builder newBuilder(DateTime dateTime) {
     return new Builder().set(dateTime);
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DoubleValue.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DoubleValue.java
index d2afa2e2ccc5..4d94be69190c 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DoubleValue.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DoubleValue.java
@@ -34,7 +34,7 @@ public int getProtoFieldId() {
 
         @Override
         public Builder newBuilder(Double value) {
-          return builder(value);
+          return DoubleValue.newBuilder(value);
         }
 
         @Override
@@ -61,7 +61,7 @@ public DoubleValue build() {
   }
 
   public DoubleValue(double value) {
-    this(builder(value));
+    this(newBuilder(value));
   }
 
   private DoubleValue(Builder builder) {
@@ -77,7 +77,12 @@ public static DoubleValue of(double value) {
     return new DoubleValue(value);
   }
 
+  @Deprecated
   public static Builder builder(double value) {
+    return newBuilder(value);
+  }
+
+  public static Builder newBuilder(double value) {
     return new Builder().set(value);
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Entity.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Entity.java
index 25e71541115c..2fa562794e3f 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Entity.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Entity.java
@@ -42,13 +42,19 @@ private Builder(Entity entity) {
     }
 
     private Builder(Key key, FullEntity entity) {
-      properties(entity.properties());
-      key(key);
+      setProperties(entity.getProperties());
+      setKey(key);
     }
 
     @Override
+    @Deprecated
     public Builder key(Key key) {
-      super.key(checkNotNull(key));
+      return setKey(key);
+    }
+
+    @Override
+    public Builder setKey(Key key) {
+      super.setKey(checkNotNull(key));
       return this;
     }
 
@@ -65,7 +71,7 @@ public Entity build() {
 
   Entity(FullEntity from) {
     super(from);
-    Preconditions.checkArgument(from.key() != null);
+    Preconditions.checkArgument(from.getKey() != null);
   }
 
   static Entity convert(FullEntity from) {
@@ -75,15 +81,30 @@ static Entity convert(FullEntity from) {
     return new Entity(from);
   }
 
+  @Deprecated
   public static Builder builder(Key key) {
+    return newBuilder(key);
+  }
+
+  public static Builder newBuilder(Key key) {
     return new Builder(key);
   }
 
+  @Deprecated
   public static Builder builder(Entity copyFrom) {
+    return newBuilder(copyFrom);
+  }
+
+  public static Builder newBuilder(Entity copyFrom) {
     return new Builder(copyFrom);
   }
 
+  @Deprecated
   public static Builder builder(Key key, FullEntity copyFrom) {
+    return newBuilder(key, copyFrom);
+  }
+
+  public static Builder newBuilder(Key key, FullEntity copyFrom) {
     return new Builder(key, copyFrom);
   }
 
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/EntityValue.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/EntityValue.java
index be7daace342e..b6d0e560e5bd 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/EntityValue.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/EntityValue.java
@@ -34,7 +34,7 @@ public int getProtoFieldId() {
 
         @Override
         public Builder newBuilder(FullEntity value) {
-          return builder(value);
+          return EntityValue.newBuilder(value);
         }
 
         @Override
@@ -61,7 +61,7 @@ public EntityValue build() {
   }
 
   public EntityValue(FullEntity entity) {
-    this(builder(entity));
+    this(newBuilder(entity));
   }
 
   private EntityValue(Builder builder) {
@@ -77,7 +77,12 @@ public static EntityValue of(FullEntity entity) {
     return new EntityValue(entity);
   }
 
+  @Deprecated
   public static Builder builder(FullEntity entity) {
+    return newBuilder(entity);
+  }
+
+  public static Builder newBuilder(FullEntity entity) {
     return new Builder().set(entity);
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/FullEntity.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/FullEntity.java
index a2871876a775..49793c13538e 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/FullEntity.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/FullEntity.java
@@ -51,15 +51,30 @@ public FullEntity build() {
     super(from);
   }
 
+  @Deprecated
   public static Builder builder() {
+    return newBuilder();
+  }
+
+  public static Builder newBuilder() {
     return new Builder<>();
   }
 
+  @Deprecated
   public static  Builder builder(K key) {
+    return newBuilder(key);
+  }
+
+  public static  Builder newBuilder(K key) {
     return new Builder<>(key);
   }
 
+  @Deprecated
   public static  Builder builder(FullEntity copyFrom) {
+    return newBuilder(copyFrom);
+  }
+
+  public static  Builder newBuilder(FullEntity copyFrom) {
     return new Builder<>(copyFrom);
   }
 
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/GqlQuery.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/GqlQuery.java
index 6409356cf33e..0dd482e086b4 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/GqlQuery.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/GqlQuery.java
@@ -44,7 +44,7 @@
  * 

When the type of the results is known the preferred usage would be: *

 {@code
  * Query query =
- *     Query.gqlQueryBuilder(Query.ResultType.ENTITY, "select * from kind").build();
+ *     Query.newGqlQueryBuilder(Query.ResultType.ENTITY, "select * from kind").build();
  * QueryResults results = datastore.run(query);
  * while (results.hasNext()) {
  *   Entity entity = results.next();
@@ -54,9 +54,9 @@
  *
  * 

When the type of the results is unknown you can use this approach: *

 {@code
- * Query query = Query.gqlQueryBuilder("select __key__ from kind").build();
+ * Query query = Query.newGqlQueryBuilder("select __key__ from kind").build();
  * QueryResults results = datastore.run(query);
- * if (Key.class.isAssignableFrom(results.resultClass())) {
+ * if (Key.class.isAssignableFrom(results.getResultClass())) {
  *   QueryResults keys = (QueryResults) results;
  *   while (keys.hasNext()) {
  *     Key key = keys.next();
@@ -94,7 +94,7 @@ static final class Binding implements Serializable {
       cursor = null;
     }
 
-    Object cursorOrValue() {
+    Object getCursorOrValue() {
       return MoreObjects.firstNonNull(cursor, value);
     }
 
@@ -124,7 +124,7 @@ com.google.datastore.v1.GqlQueryParameter toPb() {
       com.google.datastore.v1.GqlQueryParameter.Builder argPb =
           com.google.datastore.v1.GqlQueryParameter.newBuilder();
       if (cursor != null) {
-        argPb.setCursor(cursor.byteString());
+        argPb.setCursor(cursor.getByteString());
       }
       if (value != null) {
         argPb.setValue(value.toPb());
@@ -161,17 +161,52 @@ public static final class Builder {
       queryString = checkNotNull(query);
     }
 
+    /**
+     * Sets the GQL query string.
+     */
+    @Deprecated
     public Builder query(String query) {
+      return setQuery(query);
+    }
+
+    /**
+     * Sets the GQL query.
+     */
+    public Builder setQuery(String query) {
       queryString = checkNotNull(query);
       return this;
     }
 
+    /**
+     * Sets the namespace for the GQL query.
+     */
+    @Deprecated
     public Builder namespace(String namespace) {
+      return setNamespace(namespace);
+    }
+
+    /**
+     * Sets the namespace for the GQL query.
+     */
+    public Builder setNamespace(String namespace) {
       this.namespace = validateNamespace(namespace);
       return this;
     }
 
+    /**
+     * Sets whether the query string can contain literals.  When {@code false}, the query string
+     * must not contain any literals and instead must bind all values.
+     */
+    @Deprecated
     public Builder allowLiteral(boolean allowLiteral) {
+      return setAllowLiteral(allowLiteral);
+    }
+
+    /**
+     * Sets whether the query string can contain literals.  When {@code false}, the query string
+     * must not contain any literals and instead must bind all values.
+     */
+    public Builder setAllowLiteral(boolean allowLiteral) {
       this.allowLiteral = allowLiteral;
       return this;
     }
@@ -304,10 +339,25 @@ private GqlQuery(Builder builder) {
     positionalBindings = ImmutableList.copyOf(builder.positionalBindings);
   }
 
+  /**
+   * Returns the query string for this query.
+   */
+  @Deprecated
   public String queryString() {
+    return getQueryString();
+  }
+
+  /**
+   * Returns the query string for this query.
+   */
+  public String getQueryString() {
     return queryString;
   }
 
+  /**
+   * Returns whether the query string can contain literals.  When {@code false}, the query string
+   * must not contain any literals and instead must bind all values.
+   */
   public boolean allowLiteral() {
     return allowLiteral;
   }
@@ -315,10 +365,18 @@ public boolean allowLiteral() {
   /**
    * Returns an immutable map of named bindings.
    */
+  @Deprecated
   public Map namedBindings() {
+    return getNamedBindings();
+  }
+
+  /**
+   * Returns an immutable map of named bindings.
+   */
+  public Map getNamedBindings() {
     ImmutableMap.Builder builder = ImmutableSortedMap.naturalOrder();
     for (Map.Entry binding : namedBindings.entrySet()) {
-      builder.put(binding.getKey(), binding.getValue().cursorOrValue());
+      builder.put(binding.getKey(), binding.getValue().getCursorOrValue());
     }
     return builder.build();
   }
@@ -326,10 +384,18 @@ public Map namedBindings() {
   /**
    * Returns an immutable list of positional bindings (using original order).
    */
+  @Deprecated
   public List numberArgs() {
+    return getNumberArgs();
+  }
+
+  /**
+   * Returns an immutable list of positional bindings (using original order).
+   */
+  public List getNumberArgs() {
     ImmutableList.Builder builder = ImmutableList.builder();
     for (Binding binding : positionalBindings) {
-      builder.add(binding.cursorOrValue());
+      builder.add(binding.getCursorOrValue());
     }
     return builder.build();
   }
@@ -370,10 +436,8 @@ com.google.datastore.v1.GqlQuery toPb() {
         com.google.datastore.v1.GqlQuery.newBuilder();
     queryPb.setQueryString(queryString);
     queryPb.setAllowLiterals(allowLiteral);
-    Map namedBindingsPb =
-        queryPb.getMutableNamedBindings();
     for (Map.Entry entry : namedBindings.entrySet()) {
-      namedBindingsPb.put(entry.getKey(), entry.getValue().toPb());
+      queryPb.putNamedBindings(entry.getKey(), entry.getValue().toPb());
     }
     for (Binding argument : positionalBindings) {
       queryPb.addPositionalBindings(argument.toPb());
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/IncompleteKey.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/IncompleteKey.java
index 53039f77aea5..332642b4846a 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/IncompleteKey.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/IncompleteKey.java
@@ -67,7 +67,7 @@ static IncompleteKey fromPb(com.google.datastore.v1.Key keyPb) {
     }
     ImmutableList path = pathBuilder.build();
     PathElement leaf = path.get(path.size() - 1);
-    if (leaf.nameOrId() != null) {
+    if (leaf.getNameOrId() != null) {
       return new Key(projectId, namespace, path);
     }
     return new IncompleteKey(projectId, namespace, path);
@@ -77,34 +77,60 @@ static IncompleteKey fromPb(com.google.datastore.v1.Key keyPb) {
    * Returns the key's parent.
    */
   @Override
+  @Deprecated
   public Key parent() {
-    List ancestors = ancestors();
+    return getParent();
+  }
+
+  /**
+   * Returns the key's parent.
+   */
+  @Override
+  public Key getParent() {
+    List ancestors = getAncestors();
     if (ancestors.isEmpty()) {
       return null;
     }
     PathElement parent = ancestors.get(ancestors.size() - 1);
     Key.Builder keyBuilder;
     if (parent.hasName()) {
-      keyBuilder = Key.builder(projectId(), parent.kind(), parent.name());
+      keyBuilder = Key.newBuilder(getProjectId(), parent.getKind(), parent.getName());
     } else {
-      keyBuilder = Key.builder(projectId(), parent.kind(), parent.id());
+      keyBuilder = Key.newBuilder(getProjectId(), parent.getKind(), parent.getId());
     }
-    String namespace = namespace();
+    String namespace = getNamespace();
     if (namespace != null) {
-      keyBuilder.namespace(namespace);
+      keyBuilder.setNamespace(namespace);
     }
-    return keyBuilder.ancestors(ancestors.subList(0, ancestors.size() - 1)).build();
+    return keyBuilder.addAncestors(ancestors.subList(0, ancestors.size() - 1)).build();
   }
 
+  @Deprecated
   public static Builder builder(String projectId, String kind) {
+    return newBuilder(projectId, kind);
+  }
+
+  public static Builder newBuilder(String projectId, String kind) {
     return new Builder(projectId, kind);
   }
 
+  @Deprecated
   public static Builder builder(IncompleteKey copyFrom) {
+    return newBuilder(copyFrom);
+  }
+
+  public static Builder newBuilder(IncompleteKey copyFrom) {
     return new Builder(copyFrom);
   }
 
+  @Deprecated
   public static Builder builder(Key parent, String kind) {
-    return builder(parent.projectId(), kind).namespace(parent.namespace()).ancestors(parent.path());
+    return newBuilder(parent, kind);
+  }
+
+  public static Builder newBuilder(Key parent, String kind) {
+    return newBuilder(parent.getProjectId(), kind)
+        .setNamespace(parent.getNamespace())
+        .addAncestors(parent.getPath());
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Key.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Key.java
index 9f7e5d602070..4bc216d88581 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Key.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Key.java
@@ -66,19 +66,41 @@ private Builder(IncompleteKey copyFrom, long id) {
     private Builder(Key copyFrom) {
       super(copyFrom);
       if (copyFrom.hasId()) {
-        id = copyFrom.id();
+        id = copyFrom.getId();
       } else {
-        name = copyFrom.name();
+        name = copyFrom.getName();
       }
     }
 
+    /**
+     * Sets the name of this key.
+     */
+    @Deprecated
     public Builder name(String name) {
+      return setName(name);
+    }
+
+    /**
+     * Sets the name of this key.
+     */
+    public Builder setName(String name) {
       this.name = name;
       id = null;
       return this;
     }
 
+    /**
+     * Sets the ID of this key.
+     */
+    @Deprecated
     public Builder id(long id) {
+      return setId(id);
+    }
+
+    /**
+     * Sets the ID of this key.
+     */
+    public Builder setId(long id) {
       this.id = id;
       name = null;
       return this;
@@ -99,37 +121,60 @@ public Key build() {
 
   Key(String projectId, String namespace, ImmutableList path) {
     super(projectId, namespace, path);
-    Preconditions.checkArgument(nameOrId() != null);
+    Preconditions.checkArgument(getNameOrId() != null);
   }
 
   public boolean hasId() {
-    return leaf().hasId();
+    return getLeaf().hasId();
   }
 
   /**
    * Returns the key's id or {@code null} if it has a name instead.
    */
+  @Deprecated
   public Long id() {
-    return leaf().id();
+    return getId();
+  }
+
+  /**
+   * Returns the key's id or {@code null} if it has a name instead.
+   */
+  public Long getId() {
+    return getLeaf().getId();
   }
 
   public boolean hasName() {
-    return leaf().hasName();
+    return getLeaf().hasName();
   }
 
   /**
    * Returns the key's name or {@code null} if it has an id instead.
    */
+  @Deprecated
   public String name() {
-    return leaf().name();
+    return getName();
+  }
+
+  /**
+   * Returns the key's name or {@code null} if it has an id instead.
+   */
+  public String getName() {
+    return getLeaf().getName();
   }
 
   /**
-   * Returns the key's id (as {@link Long}) or name (as {@link String}).
-   * Never {@code null}.
+   * Returns the key's ID (as {@link Long}) or name (as {@link String}). Never {@code null}.
    */
+  @Deprecated
   public Object nameOrId() {
-    return leaf().nameOrId();
+    return getLeaf().getNameOrId();
+  }
+
+  /**
+   * Returns the key's ID (as {@link Long}) or name (as {@link String}). Never {@code null}.
+   */
+  public Object getNameOrId() {
+    return getLeaf().getNameOrId();
   }
 
   /**
@@ -167,45 +212,80 @@ static Key fromPb(com.google.datastore.v1.Key keyPb) {
     return (Key) key;
   }
 
+  @Deprecated
   public static Builder builder(String projectId, String kind, String name) {
+    return newBuilder(projectId, kind, name);
+  }
+
+  public static Builder newBuilder(String projectId, String kind, String name) {
     return new Builder(projectId, kind, name);
   }
 
+  @Deprecated
   public static Builder builder(String projectId, String kind, long id) {
+    return newBuilder(projectId, kind, id);
+  }
+
+  public static Builder newBuilder(String projectId, String kind, long id) {
     return new Builder(projectId, kind, id);
   }
 
+  @Deprecated
   public static Builder builder(Key copyFrom) {
+    return newBuilder(copyFrom);
+  }
+
+  public static Builder newBuilder(Key copyFrom) {
     return new Builder(copyFrom);
   }
 
+  @Deprecated
   public static Builder builder(IncompleteKey copyFrom, String name) {
+    return newBuilder(copyFrom, name);
+  }
+
+  public static Builder newBuilder(IncompleteKey copyFrom, String name) {
     return new Builder(copyFrom, name);
   }
 
+  @Deprecated
   public static Builder builder(IncompleteKey copyFrom, long id) {
+    return newBuilder(copyFrom, id);
+  }
+
+  public static Builder newBuilder(IncompleteKey copyFrom, long id) {
     return new Builder(copyFrom, id);
   }
 
+  @Deprecated
   public static Builder builder(Key parent, String kind, String name) {
-    Builder builder = builder(parent.projectId(), kind, name);
+    return newBuilder(parent, kind, name);
+  }
+
+  public static Builder newBuilder(Key parent, String kind, String name) {
+    Builder builder = newBuilder(parent.getProjectId(), kind, name);
     addParentToBuilder(parent, builder);
     return builder;
   }
 
+  @Deprecated
   public static Builder builder(Key parent, String kind, long id) {
-    Builder builder = builder(parent.projectId(), kind, id);
+    return newBuilder(parent, kind, id);
+  }
+
+  public static Builder newBuilder(Key parent, String kind, long id) {
+    Builder builder = newBuilder(parent.getProjectId(), kind, id);
     addParentToBuilder(parent, builder);
     return builder;
   }
 
   private static void addParentToBuilder(Key parent, Builder builder) {
-    builder.namespace(parent.namespace());
-    builder.ancestors(parent.ancestors());
+    builder.setNamespace(parent.getNamespace());
+    builder.addAncestors(parent.getAncestors());
     if (parent.hasId()) {
-      builder.ancestors(PathElement.of(parent.kind(), parent.id()));
+      builder.addAncestors(PathElement.of(parent.getKind(), parent.getId()));
     } else {
-      builder.ancestors(PathElement.of(parent.kind(), parent.name()));
+      builder.addAncestors(PathElement.of(parent.getKind(), parent.getName()));
     }
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/KeyFactory.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/KeyFactory.java
index f7fc17448a6d..80d48ca3bf37 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/KeyFactory.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/KeyFactory.java
@@ -33,7 +33,7 @@ public KeyFactory(String projectId) {
 
   public KeyFactory(String projectId, String namespace) {
     super(projectId);
-    namespace(namespace);
+    setNamespace(namespace);
     this.pi = projectId;
     this.ns = namespace;
   }
@@ -61,8 +61,8 @@ public Key newKey(long id) {
    * @return {@code this} for chaining
    */
   public KeyFactory reset() {
-    projectId(pi);
-    namespace(ns);
+    setProjectId(pi);
+    setNamespace(ns);
     kind = null;
     ancestors.clear();
     return this;
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/KeyQuery.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/KeyQuery.java
index ec21397cc7ae..266c1e952812 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/KeyQuery.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/KeyQuery.java
@@ -38,13 +38,13 @@ public static final class Builder extends StructuredQuery.BuilderImpl> values) {
-          return builder().set(values);
+          return ListValue.newBuilder().set(values);
         }
 
         @Override
@@ -77,7 +77,7 @@ private Builder() {
 
     private void addValueHelper(Value value) {
       // see datastore.proto definition for list_value
-      Preconditions.checkArgument(value.type() != ValueType.LIST, "Cannot contain another list");
+      Preconditions.checkArgument(value.getType() != ValueType.LIST, "Cannot contain another list");
       listBuilder.add(value);
     }
 
@@ -221,7 +221,7 @@ public ListValue build() {
   }
 
   public ListValue(List> values) {
-    this(builder().set(values));
+    this(newBuilder().set(values));
   }
 
   public ListValue(Value first, Value... other) {
@@ -258,69 +258,77 @@ public static ListValue of(Value first, Value... other) {
    * Creates a {@code ListValue} object given a number of string values.
    */
   public static ListValue of(String first, String... other) {
-    return builder().addValue(first, other).build();
+    return newBuilder().addValue(first, other).build();
   }
 
   /**
    * Creates a {@code ListValue} object given a number of long values.
    */
   public static ListValue of(long first, long... other) {
-    return builder().addValue(first, other).build();
+    return newBuilder().addValue(first, other).build();
   }
 
   /**
    * Creates a {@code ListValue} object given a number of double values.
    */
   public static ListValue of(double first, double... other) {
-    return builder().addValue(first, other).build();
+    return newBuilder().addValue(first, other).build();
   }
 
   /**
    * Creates a {@code ListValue} object given a number of boolean values.
    */
   public static ListValue of(boolean first, boolean... other) {
-    return builder().addValue(first, other).build();
+    return newBuilder().addValue(first, other).build();
   }
 
   /**
    * Creates a {@code ListValue} object given a number of {@code DateTime} values.
    */
   public static ListValue of(DateTime first, DateTime... other) {
-    return builder().addValue(first, other).build();
+    return newBuilder().addValue(first, other).build();
   }
 
   /**
    * Creates a {@code ListValue} object given a number of {@code LatLng} values.
    */
   public static ListValue of(LatLng first, LatLng... other) {
-    return builder().addValue(first, other).build();
+    return newBuilder().addValue(first, other).build();
   }
 
   /**
    * Creates a {@code ListValue} object given a number of {@code Key} values.
    */
   public static ListValue of(Key first, Key... other) {
-    return builder().addValue(first, other).build();
+    return newBuilder().addValue(first, other).build();
   }
 
   /**
    * Creates a {@code ListValue} object given a number of {@code FullEntity} values.
    */
   public static ListValue of(FullEntity first, FullEntity... other) {
-    return builder().addValue(first, other).build();
+    return newBuilder().addValue(first, other).build();
   }
 
   /**
    * Creates a {@code ListValue} object given a number of {@code Blob} values.
    */
   public static ListValue of(Blob first, Blob... other) {
-    return builder().addValue(first, other).build();
+    return newBuilder().addValue(first, other).build();
   }
 
   /**
    * Returns a builder for {@code ListValue} objects.
    */
+  @Deprecated
   public static Builder builder() {
+    return newBuilder();
+  }
+
+  /**
+   * Returns a builder for {@code ListValue} objects.
+   */
+  public static Builder newBuilder() {
     return new Builder();
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/LongValue.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/LongValue.java
index 1a1011f5f1b1..236f1c4f734a 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/LongValue.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/LongValue.java
@@ -34,7 +34,7 @@ public int getProtoFieldId() {
 
         @Override
         public Builder newBuilder(Long value) {
-          return builder(value);
+          return LongValue.newBuilder(value);
         }
 
         @Override
@@ -61,7 +61,7 @@ public LongValue build() {
   }
 
   public LongValue(long value) {
-    this(builder(value));
+    this(newBuilder(value));
   }
 
   private LongValue(Builder builder) {
@@ -77,7 +77,12 @@ public static LongValue of(long value) {
     return new LongValue(value);
   }
 
+  @Deprecated
   public static Builder builder(long value) {
+    return newBuilder(value);
+  }
+
+  public static Builder newBuilder(long value) {
     return new Builder().set(value);
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/NullValue.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/NullValue.java
index b94415b74736..fe47e122b54b 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/NullValue.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/NullValue.java
@@ -30,7 +30,7 @@ public final class NullValue extends Value {
 
         @Override
         public Builder newBuilder(Void value) {
-          return builder();
+          return NullValue.newBuilder();
         }
 
         @Override
@@ -69,7 +69,7 @@ public Builder set(Void value) {
   }
 
   public NullValue() {
-    this(builder());
+    this(newBuilder());
   }
 
   private NullValue(Builder builder) {
@@ -85,7 +85,12 @@ public static NullValue of() {
     return new NullValue();
   }
 
+  @Deprecated
   public static Builder builder() {
+    return newBuilder();
+  }
+
+  public static Builder newBuilder() {
     return new Builder();
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/PathElement.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/PathElement.java
index da564d6e868e..34a5bfce227f 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/PathElement.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/PathElement.java
@@ -42,7 +42,18 @@ private PathElement(String kind, String name, Long id) {
     this.id = id;
   }
 
+  /**
+   * Returns the kind of this path element.
+   */
+  @Deprecated
   public String kind() {
+    return getKind();
+  }
+
+  /**
+   * Returns the kind of this path element.
+   */
+  public String getKind() {
     return kind;
   }
 
@@ -50,7 +61,18 @@ public boolean hasId() {
     return id != null;
   }
 
+  /**
+   * Returns the ID of this path element.
+   */
+  @Deprecated
   public Long id() {
+    return getId();
+  }
+
+  /**
+   * Returns the ID of this path element.
+   */
+  public Long getId() {
     return id;
   }
 
@@ -58,11 +80,35 @@ public boolean hasName() {
     return name != null;
   }
 
+  /**
+   * Returns the name of this path element.
+   */
+  @Deprecated
   public String name() {
+    return getName();
+  }
+
+  /**
+   * Returns the name of this path element.
+   */
+  public String getName() {
     return name;
   }
 
+  /**
+   * Returns the path element's ID (as {@link Long}) or name (as {@link String}). Never
+   * {@code null}.
+   */
+  @Deprecated
   public Object nameOrId() {
+    return getNameOrId();
+  }
+
+  /**
+   * Returns the path element's ID (as {@link Long}) or name (as {@link String}). Never
+   * {@code null}.
+   */
+  public Object getNameOrId() {
     return id == null ? name : id;
   }
 
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/ProjectionEntity.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/ProjectionEntity.java
index 2468fc837c8a..6538770085fb 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/ProjectionEntity.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/ProjectionEntity.java
@@ -75,7 +75,12 @@ static ProjectionEntity fromPb(com.google.datastore.v1.Entity entityPb) {
     return new Builder().fill(entityPb).build();
   }
 
+  @Deprecated
   public static Builder builder(ProjectionEntity copyFrom) {
+    return newBuilder(copyFrom);
+  }
+
+  public static Builder newBuilder(ProjectionEntity copyFrom) {
     return new Builder(copyFrom);
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/ProjectionEntityQuery.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/ProjectionEntityQuery.java
index e28fcf3a0b4b..e5d32d2bc333 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/ProjectionEntityQuery.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/ProjectionEntityQuery.java
@@ -54,8 +54,17 @@ public Builder clearProjection() {
      * Sets the query's projection clause (clearing any previously specified Projection settings).
      */
     @Override
+    @Deprecated
     public Builder projection(String projection, String... others) {
-      super.projection(projection, others);
+      return setProjection(projection, others);
+    }
+
+    /**
+     * Sets the query's projection clause (clearing any previously specified Projection settings).
+     */
+    @Override
+    public Builder setProjection(String projection, String... others) {
+      super.setProjection(projection, others);
       return this;
     }
 
@@ -78,11 +87,20 @@ public Builder clearDistinctOn() {
     }
 
     /**
-     * Sets the query's group by clause (clearing any previously specified GroupBy settings).
+     * Sets the query's distinct on clause (clearing any previously specified distinct on settings).
      */
     @Override
+    @Deprecated
     public Builder distinctOn(String property, String... others) {
-      super.distinctOn(property, others);
+      return setDistinctOn(property, others);
+    }
+
+    /**
+     * Sets the query's distinct on clause (clearing any previously specified distinct on settings).
+     */
+    @Override
+    public Builder setDistinctOn(String property, String... others) {
+      super.setDistinctOn(property, others);
       return this;
     }
 
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Query.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Query.java
index 02197684928a..0e140b18f672 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Query.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Query.java
@@ -62,7 +62,7 @@ public abstract static class ResultType implements Serializable {
 
       @Override
       Object convert(com.google.datastore.v1.Entity entityPb) {
-        if (entityPb.getProperties().isEmpty()) {
+        if (entityPb.getPropertiesMap().isEmpty()) {
           if (!entityPb.hasKey()) {
             return null;
           }
@@ -193,8 +193,27 @@ ToStringHelper toStringHelper() {
    *
    * @see GQL Reference
    */
+  @Deprecated
   public static GqlQuery.Builder gqlQueryBuilder(String gql) {
-    return gqlQueryBuilder(ResultType.UNKNOWN, gql);
+    return newGqlQueryBuilder(ResultType.UNKNOWN, gql);
+  }
+
+  /**
+   * Returns a new {@link GqlQuery} builder.
+   *
+   * 

Example of creating and running a GQL query. + *

 {@code
+   * String kind = "my_kind";
+   * String gqlQuery = "select * from " + kind;
+   * Query query = Query.newGqlQueryBuilder(gqlQuery).build();
+   * QueryResults results = datastore.run(query);
+   * // Use results
+   * }
+ * + * @see GQL Reference + */ + public static GqlQuery.Builder newGqlQueryBuilder(String gql) { + return newGqlQueryBuilder(ResultType.UNKNOWN, gql); } /** @@ -211,42 +230,95 @@ public static GqlQuery.Builder gqlQueryBuilder(String gql) { * * @see GQL Reference */ + @Deprecated public static GqlQuery.Builder gqlQueryBuilder(ResultType resultType, String gql) { return new GqlQuery.Builder<>(resultType, gql); } + /** + * Returns a new {@link GqlQuery} builder. + * + *

Example of creating and running a typed GQL query. + *

 {@code
+   * String kind = "my_kind";
+   * String gqlQuery = "select * from " + kind;
+   * Query query = Query.newGqlQueryBuilder(Query.ResultType.ENTITY, gqlQuery).build();
+   * QueryResults results = datastore.run(query);
+   * // Use results
+   * }
+ * + * @see GQL Reference + */ + public static GqlQuery.Builder newGqlQueryBuilder(ResultType resultType, String gql) { + return new GqlQuery.Builder<>(resultType, gql); + } + /** * Returns a new {@link StructuredQuery} builder for full (complete entities) queries. * *

Example of creating and running an entity query. *

 {@code
    * String kind = "my_kind";
-   * Query query = Query.entityQueryBuilder().kind(kind).build();
+   * Query query = Query.entityQueryBuilder().setKind(kind).build();
    * QueryResults results = datastore.run(query);
    * // Use results
    * }
* */ + @Deprecated public static EntityQuery.Builder entityQueryBuilder() { return new EntityQuery.Builder(); } + /** + * Returns a new {@link StructuredQuery} builder for full (complete entities) queries. + * + *

Example of creating and running an entity query. + *

 {@code
+   * String kind = "my_kind";
+   * Query query = Query.newEntityQueryBuilder().setKind(kind).build();
+   * QueryResults results = datastore.run(query);
+   * // Use results
+   * }
+ * + */ + public static EntityQuery.Builder newEntityQueryBuilder() { + return new EntityQuery.Builder(); + } + /** * Returns a new {@link StructuredQuery} builder for key only queries. * *

Example of creating and running a key query. *

 {@code
    * String kind = "my_kind";
-   * Query query = Query.keyQueryBuilder().kind(kind).build();
+   * Query query = Query.keyQueryBuilder().setKind(kind).build();
    * QueryResults results = datastore.run(query);
    * // Use results
    * }
* */ + @Deprecated public static KeyQuery.Builder keyQueryBuilder() { return new KeyQuery.Builder(); } + /** + * Returns a new {@link StructuredQuery} builder for key only queries. + * + *

Example of creating and running a key query. + *

 {@code
+   * String kind = "my_kind";
+   * Query query = Query.newKeyQueryBuilder().setKind(kind).build();
+   * QueryResults results = datastore.run(query);
+   * // Use results
+   * }
+ * + */ + public static KeyQuery.Builder newKeyQueryBuilder() { + return new KeyQuery.Builder(); + } + /** * Returns a new {@link StructuredQuery} builder for projection queries. * @@ -255,7 +327,7 @@ public static KeyQuery.Builder keyQueryBuilder() { * String kind = "my_kind"; * String property = "my_property"; * Query query = Query.projectionEntityQueryBuilder() - * .kind(kind) + * .setKind(kind) * .addProjection(property) * .build(); * QueryResults results = datastore.run(query); @@ -263,7 +335,28 @@ public static KeyQuery.Builder keyQueryBuilder() { * } * */ + @Deprecated public static ProjectionEntityQuery.Builder projectionEntityQueryBuilder() { return new ProjectionEntityQuery.Builder(); } + + /** + * Returns a new {@link StructuredQuery} builder for projection queries. + * + *

Example of creating and running a projection entity query. + *

 {@code
+   * String kind = "my_kind";
+   * String property = "my_property";
+   * Query query = Query.newProjectionEntityQueryBuilder()
+   *     .setKind(kind)
+   *     .addProjection(property)
+   *     .build();
+   * QueryResults results = datastore.run(query);
+   * // Use results
+   * }
+ * + */ + public static ProjectionEntityQuery.Builder newProjectionEntityQueryBuilder() { + return new ProjectionEntityQuery.Builder(); + } } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/QueryResults.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/QueryResults.java index a907ddcad6b9..9e50dc464abe 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/QueryResults.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/QueryResults.java @@ -33,8 +33,14 @@ public interface QueryResults extends Iterator { /** * Returns the actual class of the result's values. */ + @Deprecated Class resultClass(); + /** + * Returns the actual class of the result's values. + */ + Class getResultClass(); + /** * Returns the Cursor for the point after the value returned in the last {@link #next} call. This * cursor can be used to issue subsequent queries (with the same constraints) that may return @@ -42,15 +48,35 @@ public interface QueryResults extends Iterator { * *

A simple use case: *

 {@code
-   * Query query = Query.entityQueryBuilder()
-   *     .kind("Person")
-   *     .filter(PropertyFilter.eq("favoriteFood", "pizza"))
+   * Query query = Query.newEntityQueryBuilder()
+   *     .setKind("Person")
+   *     .setFilter(PropertyFilter.eq("favoriteFood", "pizza"))
    *     .build();
    * QueryResults results = datastore.run(query);
    * // Consume some results (using results.next()) and do any other actions as necessary.
-   * query = query.toBuilder().startCursor(results.cursorAfter()).build();
+   * query = query.toBuilder().setStartCursor(results.getCursorAfter()).build();
    * results = datastore.run(query); // now we will iterate over all entities not yet consumed
    * }
*/ + @Deprecated Cursor cursorAfter(); + + /** + * Returns the Cursor for the point after the value returned in the last {@link #next} call. This + * cursor can be used to issue subsequent queries (with the same constraints) that may return + * additional results. + * + *

A simple use case: + *

 {@code
+   * Query query = Query.newEntityQueryBuilder()
+   *     .setKind("Person")
+   *     .setFilter(PropertyFilter.eq("favoriteFood", "pizza"))
+   *     .build();
+   * QueryResults results = datastore.run(query);
+   * // Consume some results (using results.next()) and do any other actions as necessary.
+   * query = query.toBuilder().setStartCursor(results.getCursorAfter()).build();
+   * results = datastore.run(query); // now we will iterate over all entities not yet consumed
+   * }
+ */ + Cursor getCursorAfter(); } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/QueryResultsImpl.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/QueryResultsImpl.java index f23ff846a652..14124094f04f 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/QueryResultsImpl.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/QueryResultsImpl.java @@ -104,12 +104,24 @@ protected T computeNext() { } @Override + @Deprecated public Class resultClass() { + return getResultClass(); + } + + @Override + public Class getResultClass() { return actualResultType.resultClass(); } @Override + @Deprecated public Cursor cursorAfter() { + return getCursorAfter(); + } + + @Override + public Cursor getCursorAfter() { return new Cursor(cursor); } } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/RawValue.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/RawValue.java index 35510df76d10..01c762323767 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/RawValue.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/RawValue.java @@ -27,7 +27,7 @@ public final class RawValue extends Value { @Override public Builder newBuilder(com.google.datastore.v1.Value value) { - return builder(value); + return RawValue.newBuilder(value); } @Override @@ -65,7 +65,7 @@ private RawValue(Builder builder) { } RawValue(com.google.datastore.v1.Value valuePb) { - this(builder(valuePb)); + this(newBuilder(valuePb)); } @Override @@ -77,10 +77,10 @@ static RawValue of(com.google.datastore.v1.Value valuePb) { return new RawValue(valuePb); } - static Builder builder(com.google.datastore.v1.Value valuePb) { + static Builder newBuilder(com.google.datastore.v1.Value valuePb) { Builder builder = new Builder(); - builder.excludeFromIndexes(valuePb.getExcludeFromIndexes()); - builder.meaning(valuePb.getMeaning()); + builder.setExcludeFromIndexes(valuePb.getExcludeFromIndexes()); + builder.setMeaning(valuePb.getMeaning()); builder.set(valuePb); return builder; } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/StringValue.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/StringValue.java index bb90aada37f3..92dc0e981e7e 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/StringValue.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/StringValue.java @@ -34,7 +34,7 @@ public int getProtoFieldId() { @Override public Builder newBuilder(String value) { - return builder(value); + return StringValue.newBuilder(value); } @Override @@ -61,7 +61,7 @@ public StringValue build() { } public StringValue(String value) { - this(builder(value)); + this(newBuilder(value)); } private StringValue(Builder builder) { @@ -77,7 +77,12 @@ public static StringValue of(String value) { return new StringValue(value); } + @Deprecated public static Builder builder(String value) { + return newBuilder(value); + } + + public static Builder newBuilder(String value) { return new Builder().set(value); } } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/StructuredQuery.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/StructuredQuery.java index 6d3c6fd19e83..988a0326d4e2 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/StructuredQuery.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/StructuredQuery.java @@ -45,7 +45,7 @@ * *

A simple query that returns all entities for a specific kind *

 {@code
- * Query query = Query.entityQueryBuilder().kind(kind).build();
+ * Query query = Query.newEntityQueryBuilder().setKind(kind).build();
  * QueryResults results = datastore.run(query);
  * while (results.hasNext()) {
  *   Entity entity = results.next();
@@ -55,7 +55,7 @@
  *
  * 

A simple key-only query of all entities for a specific kind *

 {@code
- * Query keyOnlyQuery =  Query.keyQueryBuilder().kind(KIND1).build();
+ * Query keyOnlyQuery =  Query.newKeyQueryBuilder().setKind(KIND1).build();
  * QueryResults results = datastore.run(keyOnlyQuery);
  * ...
  * }
@@ -63,13 +63,13 @@ *

A less trivial example of a projection query that returns the first 10 results * of "age" and "name" properties (sorted and grouped by "age") with an age greater than 18 *

 {@code
- * Query query = Query.projectionEntityQueryBuilder()
- *     .kind(kind)
- *     .projection(Projection.property("age"), Projection.first("name"))
- *     .filter(PropertyFilter.gt("age", 18))
- *     .groupBy("age")
- *     .orderBy(OrderBy.asc("age"))
- *     .limit(10)
+ * Query query = Query.newProjectionEntityQueryBuilder()
+ *     .setKind(kind)
+ *     .setProjection(Projection.property("age"), Projection.first("name"))
+ *     .setFilter(PropertyFilter.gt("age", 18))
+ *     .setGroupBy("age")
+ *     .setOrderBy(OrderBy.asc("age"))
+ *     .setLimit(10)
  *     .build();
  * QueryResults results = datastore.run(query);
  * ...
@@ -497,11 +497,33 @@ public boolean equals(Object obj) {
           && direction == other.direction;
     }
 
+    /**
+     * Returns the property according to which the query result should be ordered.
+     */
+    @Deprecated
     public String property() {
+      return getProperty();
+    }
+
+    /**
+     * Returns the property according to which the query result should be ordered.
+     */
+    public String getProperty() {
       return property;
     }
 
+    /**
+     * Returns the order's direction.
+     */
+    @Deprecated
     public Direction direction() {
+      return getDirection();
+    }
+
+    /**
+     * Returns the order's direction.
+     */
+    public Direction getDirection() {
       return direction;
     }
 
@@ -534,27 +556,97 @@ static OrderBy fromPb(com.google.datastore.v1.PropertyOrder propertyOrderPb) {
    * @param  the type of result the query returns.
    */
   public interface Builder {
+
+    /**
+     * Sets the namespace for the query.
+     */
+    @Deprecated
     Builder namespace(String namespace);
 
+    /**
+     * Sets the namespace for the query.
+     */
+    Builder setNamespace(String namespace);
+
+    /**
+     * Sets the kind for the query.
+     */
+    @Deprecated
     Builder kind(String kind);
 
+    /**
+     * Sets the kind for the query.
+     */
+    Builder setKind(String kind);
+
+    /**
+     * Sets the start cursor for the query.
+     */
+    @Deprecated
     Builder startCursor(Cursor startCursor);
 
+    /**
+     * Sets the start cursor for the query.
+     */
+    Builder setStartCursor(Cursor startCursor);
+
+    /**
+     * Sets the end cursor for the query.
+     */
+    @Deprecated
     Builder endCursor(Cursor endCursor);
 
+    /**
+     * Sets the end cursor for the query.
+     */
+    Builder setEndCursor(Cursor endCursor);
+
+    /**
+     * Sets the offset for the query.
+     */
+    @Deprecated
     Builder offset(int offset);
 
+    /**
+     * Sets the offset for the query.
+     */
+    Builder setOffset(int offset);
+
+    /**
+     * Sets the limit for the query.
+     */
+    @Deprecated
     Builder limit(Integer limit);
 
+    /**
+     * Sets the limit for the query.
+     */
+    Builder setLimit(Integer limit);
+
+    /**
+     * Sets a filter for the query.
+     */
+    @Deprecated
     Builder filter(Filter filter);
 
+    Builder setFilter(Filter filter);
+
+    /**
+     * Clears any previously specified order by settings.
+     */
     Builder clearOrderBy();
 
     /**
-     * Sets the query's order by clause (clearing any previously specified OrderBy settings).
+     * Sets the query's order by clause (clearing any previously specified order by settings).
      */
+    @Deprecated
     Builder orderBy(OrderBy orderBy, OrderBy... others);
 
+    /**
+     * Sets the query's order by clause (clearing any previously specified order by settings).
+     */
+    Builder setOrderBy(OrderBy orderBy, OrderBy... others);
+
     /**
      * Adds settings to the existing order by clause.
      */
@@ -607,45 +699,87 @@ B self() {
     }
 
     @Override
+    @Deprecated
     public B namespace(String namespace) {
+      return setNamespace(namespace);
+    }
+
+    @Override
+    public B setNamespace(String namespace) {
       this.namespace = namespace;
       return self();
     }
 
     @Override
+    @Deprecated
     public B kind(String kind) {
+      return setKind(kind);
+    }
+
+    @Override
+    public B setKind(String kind) {
       this.kind = kind;
       return self();
     }
 
     @Override
+    @Deprecated
     public B startCursor(Cursor startCursor) {
+      return setStartCursor(startCursor);
+    }
+
+    @Override
+    public B setStartCursor(Cursor startCursor) {
       this.startCursor = startCursor;
       return self();
     }
 
     @Override
+    @Deprecated
     public B endCursor(Cursor endCursor) {
+      return setEndCursor(endCursor);
+    }
+
+    @Override
+    public B setEndCursor(Cursor endCursor) {
       this.endCursor = endCursor;
       return self();
     }
 
     @Override
+    @Deprecated
     public B offset(int offset) {
+      return setOffset(offset);
+    }
+
+    @Override
+    public B setOffset(int offset) {
       Preconditions.checkArgument(offset >= 0, "offset must not be negative");
       this.offset = offset;
       return self();
     }
 
     @Override
+    @Deprecated
     public B limit(Integer limit) {
+      return setLimit(limit);
+    }
+
+    @Override
+    public B setLimit(Integer limit) {
       Preconditions.checkArgument(limit == null || limit > 0, "limit must be positive");
       this.limit = limit;
       return self();
     }
 
     @Override
+    @Deprecated
     public B filter(Filter filter) {
+      return setFilter(filter);
+    }
+
+    @Override
+    public B setFilter(Filter filter) {
       this.filter = filter;
       return self();
     }
@@ -657,7 +791,13 @@ public B clearOrderBy() {
     }
 
     @Override
+    @Deprecated
     public B orderBy(OrderBy orderBy, OrderBy... others) {
+      return setOrderBy(orderBy, others);
+    }
+
+    @Override
+    public B setOrderBy(OrderBy orderBy, OrderBy... others) {
       clearOrderBy();
       addOrderBy(orderBy, others);
       return self();
@@ -675,7 +815,12 @@ B clearProjection() {
       return self();
     }
 
+    @Deprecated
     B projection(String projection, String... others) {
+      return setProjection(projection, others);
+    }
+
+    B setProjection(String projection, String... others) {
       clearProjection();
       addProjection(projection, others);
       return self();
@@ -692,7 +837,12 @@ B clearDistinctOn() {
       return self();
     }
 
+    @Deprecated
     B distinctOn(String property, String... others) {
+      return setDistinctOn(property, others);
+    }
+
+    B setDistinctOn(String property, String... others) {
       clearDistinctOn();
       addDistinctOn(property, others);
       return self();
@@ -706,22 +856,22 @@ B addDistinctOn(String property, String... others) {
 
     B mergeFrom(com.google.datastore.v1.Query queryPb) {
       if (queryPb.getKindCount() > 0) {
-        kind(queryPb.getKind(0).getName());
+        setKind(queryPb.getKind(0).getName());
       }
       if (!queryPb.getStartCursor().isEmpty()) {
-        startCursor(new Cursor(queryPb.getStartCursor()));
+        setStartCursor(new Cursor(queryPb.getStartCursor()));
       }
       if (!queryPb.getEndCursor().isEmpty()) {
-        endCursor(new Cursor(queryPb.getEndCursor()));
+        setEndCursor(new Cursor(queryPb.getEndCursor()));
       }
-      offset(queryPb.getOffset());
+      setOffset(queryPb.getOffset());
       if (queryPb.hasLimit()) {
-        limit(queryPb.getLimit().getValue());
+        setLimit(queryPb.getLimit().getValue());
       }
       if (queryPb.hasFilter()) {
         Filter currFilter = Filter.fromPb(queryPb.getFilter());
         if (currFilter != null) {
-          filter(currFilter);
+          setFilter(currFilter);
         }
       }
       for (com.google.datastore.v1.PropertyOrder orderByPb : queryPb.getOrderList()) {
@@ -793,43 +943,142 @@ public boolean equals(Object obj) {
 
   }
 
+  /**
+   * Returns the kind for this query.
+   */
+  @Deprecated
   public String kind() {
+    return getKind();
+  }
+
+  /**
+   * Returns the kind for this query.
+   */
+  public String getKind() {
     return kind;
   }
 
-  boolean keyOnly() {
+  boolean isKeyOnly() {
     return projection.size() == 1 && KEY_PROPERTY_NAME.equals(projection.get(0));
   }
 
+  /**
+   * Returns the projection for this query.
+   */
+  @Deprecated
   public List projection() {
+    return getProjection();
+  }
+
+  /**
+   * Returns the projection for this query.
+   */
+  public List getProjection() {
     return projection;
   }
 
+  /**
+   * Returns the filter for this query.
+   */
+  @Deprecated
   public Filter filter() {
+    return getFilter();
+  }
+
+  /**
+   * Returns the filter for this query.
+   */
+  public Filter getFilter() {
     return filter;
   }
 
+  /**
+   * Returns the distinct on clause for this query.
+   */
+  @Deprecated
   public List distinctOn() {
+    return getDistinctOn();
+  }
+
+  /**
+   * Returns the distinct on clause for this query.
+   */
+  public List getDistinctOn() {
     return distinctOn;
   }
 
+  /**
+   * Returns the order by clause for this query.
+   */
+  @Deprecated
   public ImmutableList orderBy() {
+    return getOrderBy();
+  }
+
+  /**
+   * Returns the order by clause for this query.
+   */
+  public ImmutableList getOrderBy() {
     return orderBy;
   }
 
+  /**
+   * Returns the start cursor for this query.
+   */
+  @Deprecated
   public Cursor startCursor() {
+    return getStartCursor();
+  }
+
+  /**
+   * Returns the start cursor for this query.
+   */
+  public Cursor getStartCursor() {
     return startCursor;
   }
 
+  /**
+   * Returns the end cursor for this query.
+   */
+  @Deprecated
   public Cursor endCursor() {
+    return getEndCursor();
+  }
+
+  /**
+   * Returns the end cursor for this query.
+   */
+  public Cursor getEndCursor() {
     return endCursor;
   }
 
+  /**
+   * Returns the offset for this query.
+   */
+  @Deprecated
   public int offset() {
+    return getOffset();
+  }
+
+  /**
+   * Returns the offset for this query.
+   */
+  public int getOffset() {
     return offset;
   }
 
+  /**
+   * Returns the limit for this query.
+   */
+  @Deprecated
   public Integer limit() {
+    return getLimit();
+  }
+
+  /**
+   * Returns the limit for this query.
+   */
+  public Integer getLimit() {
     return limit;
   }
 
@@ -843,13 +1092,13 @@ void populatePb(com.google.datastore.v1.RunQueryRequest.Builder requestPb) {
   @Override
   StructuredQuery nextQuery(com.google.datastore.v1.RunQueryResponse responsePb) {
     Builder builder = toBuilder();
-    builder.startCursor(new Cursor(responsePb.getBatch().getEndCursor()));
+    builder.setStartCursor(new Cursor(responsePb.getBatch().getEndCursor()));
     if (offset > 0 && responsePb.getBatch().getSkippedResults() < offset) {
-      builder.offset(offset - responsePb.getBatch().getSkippedResults());
+      builder.setOffset(offset - responsePb.getBatch().getSkippedResults());
     } else {
-      builder.offset(0);
+      builder.setOffset(0);
       if (limit != null) {
-        builder.limit(limit - responsePb.getBatch().getEntityResultsCount());
+        builder.setLimit(limit - responsePb.getBatch().getEntityResultsCount());
       }
     }
     return builder.build();
@@ -861,10 +1110,10 @@ com.google.datastore.v1.Query toPb() {
       queryPb.addKindBuilder().setName(kind);
     }
     if (startCursor != null) {
-      queryPb.setStartCursor(startCursor.byteString());
+      queryPb.setStartCursor(startCursor.getByteString());
     }
     if (endCursor != null) {
-      queryPb.setEndCursor(endCursor.byteString());
+      queryPb.setEndCursor(endCursor.getByteString());
     }
     if (offset > 0) {
       queryPb.setOffset(offset);
@@ -903,6 +1152,6 @@ static  StructuredQuery fromPb(ResultType resultType, String namespace,
     } else {
       builder = new ProjectionEntityQuery.Builder();
     }
-    return (StructuredQuery) builder.namespace(namespace).mergeFrom(queryPb).build();
+    return (StructuredQuery) builder.setNamespace(namespace).mergeFrom(queryPb).build();
   }
 }
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Transaction.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Transaction.java
index fd629bf0294b..02cd7cf63ed8 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Transaction.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Transaction.java
@@ -35,13 +35,16 @@
  *   Entity entity = transaction.get(key);
  *   if (!entity.contains("last_name") || entity.isNull("last_name")) {
  *     String[] name = entity.getString("name").split(" ");
- *     entity = Entity.builder(entity).remove("name").set("first_name", name[0])
- *         .set("last_name", name[1]).build();
+ *     entity = Entity.newBuilder(entity)
+ *         .remove("name")
+ *         .set("first_name", name[0])
+ *         .set("last_name", name[1])
+ *         .build();
  *     transaction.update(entity);
  *     transaction.commit();
  *   }
  * } finally {
- *   if (transaction.active()) {
+ *   if (transaction.isActive()) {
  *     transaction.rollback();
  *   }
  * }
@@ -54,7 +57,17 @@
 public interface Transaction extends DatastoreBatchWriter, DatastoreReaderWriter {
 
   interface Response {
+    /**
+     * Returns a list of keys generated by a transaction.
+     */
+    @Deprecated
     List generatedKeys();
+
+    /**
+     * Returns a list of keys generated by a transaction.
+     */
+    @Deprecated
+    List getGeneratedKeys();
   }
 
   /**
@@ -66,7 +79,7 @@ interface Response {
    * 

Example of getting an entity for a given key. *

 {@code
    * String keyName = "my_key_name";
-   * Key key = datastore.newKeyFactory().kind("MyKind").newKey(keyName);
+   * Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName);
    * Entity entity = transaction.get(key);
    * transaction.commit();
    * // Do something with the entity
@@ -87,7 +100,7 @@ interface Response {
    * 
 {@code
    * String firstKeyName = "my_first_key_name";
    * String secondKeyName = "my_second_key_name";
-   * KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind");
+   * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
    * Key firstKey = keyFactory.newKey(firstKeyName);
    * Key secondKey = keyFactory.newKey(secondKeyName);
    * Iterator entitiesIterator = transaction.get(firstKey, secondKey);
@@ -115,7 +128,7 @@ interface Response {
    * 
 {@code
    * String firstKeyName = "my_first_key_name";
    * String secondKeyName = "my_second_key_name";
-   * KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind");
+   * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
    * Key firstKey = keyFactory.newKey(firstKeyName);
    * Key secondKey = keyFactory.newKey(secondKeyName);
    * List entities = transaction.fetch(firstKey, secondKey);
@@ -140,12 +153,12 @@ interface Response {
    * 

Example of running a query to find all entities with an ancestor. *

 {@code
    * String parentKeyName = "my_parent_key_name";
-   * KeyFactory keyFactory = datastore.newKeyFactory().kind("ParentKind");
+   * KeyFactory keyFactory = datastore.newKeyFactory().setKind("ParentKind");
    * Key parentKey = keyFactory.newKey(parentKeyName);
    * // Build a query
-   * Query query = Query.entityQueryBuilder()
-   *     .kind("MyKind")
-   *     .filter(PropertyFilter.hasAncestor(parentKey))
+   * Query query = Query.newEntityQueryBuilder()
+   *     .setKind("MyKind")
+   *     .setFilter(PropertyFilter.hasAncestor(parentKey))
    *     .build();
    * QueryResults results = transaction.run(query);
    * List entities = Lists.newArrayList();
@@ -168,9 +181,9 @@ interface Response {
    * 

Example of committing a transaction. *

 {@code
    * // create an entity
-   * KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind");
+   * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
    * Key key = datastore.allocateId(keyFactory.newKey());
-   * Entity entity = Entity.builder(key).set("description", "commit()").build();
+   * Entity entity = Entity.newBuilder(key).set("description", "commit()").build();
    * 
    * // add the entity and commit
    * try {
@@ -191,9 +204,9 @@ interface Response {
    * 

Example of rolling back a transaction. *

 {@code
    * // create an entity
-   * KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind");
+   * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
    * Key key = datastore.allocateId(keyFactory.newKey());
-   * Entity entity = Entity.builder(key).set("description", "rollback()").build();
+   * Entity entity = Entity.newBuilder(key).set("description", "rollback()").build();
    * 
    * // add the entity and rollback
    * transaction.put(entity);
@@ -211,9 +224,9 @@ interface Response {
    * 

Example of verifying if a transaction is active. *

 {@code
    * // create an entity
-   * KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind");
+   * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
    * Key key = datastore.allocateId(keyFactory.newKey());
-   * Entity entity = Entity.builder(key).set("description", "active()").build();
+   * Entity entity = Entity.newBuilder(key).set("description", "active()").build();
    * // calling transaction.active() now would return true
    * try {
    *   // add the entity and commit
@@ -231,10 +244,45 @@ interface Response {
    *
    */
   @Override
+  @Deprecated
   boolean active();
 
+  /**
+   * Returns {@code true} if the transaction is still active (was not committed or rolledback).
+   *
+   * 

Example of verifying if a transaction is active. + *

 {@code
+   * // create an entity
+   * KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind");
+   * Key key = datastore.allocateId(keyFactory.newKey());
+   * Entity entity = Entity.newBuilder(key).set("description", "active()").build();
+   * // calling transaction.active() now would return true
+   * try {
+   *   // add the entity and commit
+   *   transaction.put(entity);
+   *   transaction.commit();
+   * } finally {
+   *   // if committing succeeded
+   *   // then transaction.active() will be false
+   *   if (transaction.isActive()) {
+   *     // otherwise it's true and we need to rollback
+   *     transaction.rollback();
+   *   }
+   * }
+   * }
+ * + */ + @Override + boolean isActive(); + /** * Returns the transaction associated {@link Datastore}. */ + @Deprecated Datastore datastore(); + + /** + * Returns the transaction associated {@link Datastore}. + */ + Datastore getDatastore(); } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/TransactionImpl.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/TransactionImpl.java index 8b398cb68cff..150799932591 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/TransactionImpl.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/TransactionImpl.java @@ -39,6 +39,7 @@ static class ResponseImpl implements Transaction.Response { } @Override + @Deprecated public List generatedKeys() { Iterator results = response.getMutationResultsList().iterator(); @@ -48,6 +49,17 @@ public List generatedKeys() { } return generated; } + + @Override + public List getGeneratedKeys() { + Iterator results = + response.getMutationResultsList().iterator(); + List generated = new ArrayList<>(numAutoAllocatedIds); + for (int i = 0; i < numAutoAllocatedIds; i++) { + generated.add(Key.fromPb(results.next().getKey())); + } + return generated; + } } TransactionImpl(DatastoreImpl datastore) { @@ -113,7 +125,13 @@ public void rollback() { } @Override + @Deprecated public Datastore datastore() { + return getDatastore(); + } + + @Override + public Datastore getDatastore() { return datastore; } } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Value.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Value.java index 00f2c2fa64ce..92543d9522c3 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Value.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Value.java @@ -95,18 +95,30 @@ public ValueType getValueType() { @Override public B mergeFrom(P other) { excludeFromIndexes = other.excludeFromIndexes(); - meaning = other.meaning(); + meaning = other.getMeaning(); set(other.get()); return self(); } @Override + @Deprecated public boolean getExcludeFromIndexes() { + return excludeFromIndexes(); + } + + @Override + public boolean excludeFromIndexes() { return excludeFromIndexes; } @Override + @Deprecated public B excludeFromIndexes(boolean excludeFromIndexes) { + return setExcludeFromIndexes(excludeFromIndexes); + } + + @Override + public B setExcludeFromIndexes(boolean excludeFromIndexes) { this.excludeFromIndexes = excludeFromIndexes; return self(); } @@ -120,6 +132,12 @@ public int getMeaning() { @Deprecated @Override public B meaning(int meaning) { + return setMeaning(meaning); + } + + @Deprecated + @Override + public B setMeaning(int meaning) { this.meaning = meaning; return self(); } @@ -147,21 +165,40 @@ private B self() { @SuppressWarnings("deprecation")

, B extends BaseBuilder> Value(ValueBuilder builder) { valueType = builder.getValueType(); - excludeFromIndexes = builder.getExcludeFromIndexes(); + excludeFromIndexes = builder.excludeFromIndexes(); meaning = builder.getMeaning(); value = builder.get(); } + /** + * Returns the type of this value. + */ + @Deprecated public final ValueType type() { + return getType(); + } + + /** + * Returns the type of this value. + */ + public final ValueType getType() { return valueType; } + /** + * Returns whether this value should be excluded from indexes. + */ public final boolean excludeFromIndexes() { return excludeFromIndexes; } @Deprecated final int meaning() { + return getMeaning(); + } + + @Deprecated + final int getMeaning() { return meaning; } @@ -204,7 +241,7 @@ public boolean equals(Object obj) { @SuppressWarnings("unchecked") com.google.datastore.v1.Value toPb() { - return type().getMarshaller().toProto(this); + return getType().getMarshaller().toProto(this); } static Value fromPb(com.google.datastore.v1.Value proto) { diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/ValueBuilder.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/ValueBuilder.java index 0328d4a0637b..7a8065b54523 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/ValueBuilder.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/ValueBuilder.java @@ -29,10 +29,16 @@ public interface ValueBuilder, B extends ValueBuilder, B extends ValueBuilder. *

 {@code
  * Datastore datastore = DatastoreOptions.defaultInstance().service();
- * KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind");
+ * KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind");
  * Key key = keyFactory.newKey("keyName");
- * Entity entity = Entity.builder(key)
+ * Entity entity = Entity.newBuilder(key)
  *     .set("name", "John Doe")
  *     .set("age", 30)
  *     .set("access_time", DateTime.now())
@@ -39,12 +39,12 @@
  * UpdateEntity.java.
  * 
 {@code
  * Datastore datastore = DatastoreOptions.defaultInstance().service();
- * KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind");
+ * KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind");
  * Key key = keyFactory.newKey("keyName");
  * Entity entity = datastore.get(key);
  * if (entity != null) {
  *   System.out.println("Updating access_time for " + entity.getString("name"));
- *   entity = Entity.builder(entity)
+ *   entity = Entity.newBuilder(entity)
  *       .set("access_time", DateTime.now())
  *       .build();
  *   datastore.update(entity);
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java
index b8dbb6008fb0..cf7f47b8c853 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java
@@ -648,7 +648,16 @@ private DatastoreOptions.Builder optionsBuilder() {
    * Returns a {@link DatastoreOptions} instance that sets the host to use the Datastore emulator on
    * localhost.
    */
+  @Deprecated
   public DatastoreOptions options() {
+    return getOptions();
+  }
+
+  /**
+   * Returns a {@link DatastoreOptions} instance that sets the host to use the Datastore emulator on
+   * localhost.
+   */
+  public DatastoreOptions getOptions() {
     return optionsBuilder().build();
   }
 
@@ -656,24 +665,49 @@ public DatastoreOptions options() {
    * Returns a {@link DatastoreOptions} instance that sets the host to use the Datastore emulator on
    * localhost. The default namespace is set to {@code namespace}.
    */
+  @Deprecated
   public DatastoreOptions options(String namespace) {
     return optionsBuilder().namespace(namespace).build();
   }
 
+  /**
+   * Returns a {@link DatastoreOptions} instance that sets the host to use the Datastore emulator on
+   * localhost. The default namespace is set to {@code namespace}.
+   */
+  public DatastoreOptions getOptions(String namespace) {
+    return optionsBuilder().namespace(namespace).build();
+  }
+
   /**
    * Returns the project ID associated with this local Datastore emulator.
    */
+  @Deprecated
   public String projectId() {
     return projectId;
   }
 
+  /**
+   * Returns the project ID associated with this local Datastore emulator.
+   */
+  public String getProjectId() {
+    return projectId;
+  }
+
   /**
    * Returns the consistency setting for the local Datastore emulator.
    */
+  @Deprecated
   public double consistency() {
     return consistency;
   }
 
+  /**
+   * Returns the consistency setting for the local Datastore emulator.
+   */
+  public double getConsistency() {
+    return consistency;
+  }
+
   /**
    * Creates a local Datastore helper with the specified settings for project ID and consistency.
    *
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/RemoteDatastoreHelper.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/RemoteDatastoreHelper.java
index dd55e1481577..8e4febcf4580 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/RemoteDatastoreHelper.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/RemoteDatastoreHelper.java
@@ -28,7 +28,7 @@
 
 /**
  * Utility to create a remote datastore configuration for testing. Datastore options can be obtained
- * via the {@link #options()} method. Returned options use a randomly generated namespace
+ * via the {@link #getOptions()} method. Returned options use a randomly generated namespace
  * ({@link DatastoreOptions#namespace()}) that can be used to run the tests. Once the tests are run,
  * all entities in the namespace can be deleted using {@link #deleteNamespace()}. Returned options
  * also have custom {@link DatastoreOptions#retryParams()}: {@link RetryParams#retryMaxAttempts()}
@@ -55,15 +55,24 @@ private RemoteDatastoreHelper(DatastoreOptions options) {
    * Returns a {@link DatastoreOptions} object to be used for testing. The options are associated
    * to a randomly generated namespace.
    */
+  @Deprecated
   public DatastoreOptions options() {
     return options;
   }
 
+  /**
+   * Returns a {@link DatastoreOptions} object to be used for testing. The options are associated
+   * to a randomly generated namespace.
+   */
+  public DatastoreOptions getOptions() {
+    return options;
+  }
+
   /**
    * Deletes all entities in the namespace associated with this {@link RemoteDatastoreHelper}.
    */
   public void deleteNamespace() {
-    StructuredQuery query = Query.keyQueryBuilder().namespace(namespace).build();
+    StructuredQuery query = Query.newKeyQueryBuilder().setNamespace(namespace).build();
     QueryResults keys = datastore.run(query);
     while (keys.hasNext()) {
       datastore.delete(keys.next());
diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/package-info.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/package-info.java
index ec4ae11e6a02..3000b96f3f4e 100644
--- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/package-info.java
+++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/package-info.java
@@ -22,7 +22,7 @@
  * 
 {@code
  * LocalDatastoreHelper helper = LocalDatastoreHelper.create();
  * helper.start();
- * Datastore localDatastore = helper.options().service();
+ * Datastore localDatastore = helper.getOptions().service();
  * } 
* *

After the test: diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BaseDatastoreBatchWriterTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BaseDatastoreBatchWriterTest.java index a1ae3f28dd5b..402085c4d5df 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BaseDatastoreBatchWriterTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BaseDatastoreBatchWriterTest.java @@ -33,17 +33,17 @@ public class BaseDatastoreBatchWriterTest { - private static final Key KEY1 = Key.builder("dataset1", "kind1", "name1").build(); - private static final Key KEY2 = Key.builder(KEY1, 1).build(); - private static final Key KEY3 = Key.builder(KEY1, 2).build(); - private static final IncompleteKey INCOMPLETE_KEY = IncompleteKey.builder(KEY1).build(); - private static final Entity ENTITY1 = Entity.builder(KEY1).build(); - private static final Entity ENTITY2 = Entity.builder(KEY2).set("bak", true).build(); - private static final Entity ENTITY3 = Entity.builder(KEY3).set("bak", true).build(); + private static final Key KEY1 = Key.newBuilder("dataset1", "kind1", "name1").build(); + private static final Key KEY2 = Key.newBuilder(KEY1, 1).build(); + private static final Key KEY3 = Key.newBuilder(KEY1, 2).build(); + private static final IncompleteKey INCOMPLETE_KEY = IncompleteKey.newBuilder(KEY1).build(); + private static final Entity ENTITY1 = Entity.newBuilder(KEY1).build(); + private static final Entity ENTITY2 = Entity.newBuilder(KEY2).set("bak", true).build(); + private static final Entity ENTITY3 = Entity.newBuilder(KEY3).set("bak", true).build(); private static final FullEntity INCOMPLETE_ENTITY_1 = - Entity.builder(INCOMPLETE_KEY).build(); + Entity.newBuilder(INCOMPLETE_KEY).build(); private static final FullEntity INCOMPLETE_ENTITY_2 = - Entity.builder(INCOMPLETE_KEY).set("name", "dan").build(); + Entity.newBuilder(INCOMPLETE_KEY).set("name", "dan").build(); private DatastoreBatchWriter batchWriter; @@ -61,10 +61,16 @@ protected DatastoreBatchWriter() { } @Override + @Deprecated protected Datastore datastore() { return datastore; } + @Override + protected Datastore getDatastore() { + return datastore; + } + void finish() { verify(datastore); } @@ -83,20 +89,20 @@ public void tearDown() { @Test public void testAdd() throws Exception { Entity entity2 = - Entity.builder(ENTITY2).key(Key.builder(KEY1).name("name2").build()).build(); + Entity.newBuilder(ENTITY2).setKey(Key.newBuilder(KEY1).setName("name2").build()).build(); List pbs = new LinkedList<>(); pbs.add(com.google.datastore.v1.Mutation.newBuilder().setInsert(ENTITY1.toPb()).build()); pbs.add(com.google.datastore.v1.Mutation.newBuilder() - .setInsert(Entity.builder(KEY2, INCOMPLETE_ENTITY_1).build().toPb()).build()); + .setInsert(Entity.newBuilder(KEY2, INCOMPLETE_ENTITY_1).build().toPb()).build()); pbs.add(com.google.datastore.v1.Mutation.newBuilder() - .setInsert(Entity.builder(KEY3, INCOMPLETE_ENTITY_2).build().toPb()).build()); + .setInsert(Entity.newBuilder(KEY3, INCOMPLETE_ENTITY_2).build().toPb()).build()); pbs.add(com.google.datastore.v1.Mutation.newBuilder().setInsert(entity2.toPb()).build()); List entities = batchWriter .add(ENTITY1, INCOMPLETE_ENTITY_1, INCOMPLETE_ENTITY_2, entity2); assertEquals(pbs, batchWriter.toMutationPbList()); assertEquals(ENTITY1, entities.get(0)); - assertEquals(Entity.builder(KEY2, INCOMPLETE_ENTITY_1).build(), entities.get(1)); - assertEquals(Entity.builder(KEY3, INCOMPLETE_ENTITY_2).build(), entities.get(2)); + assertEquals(Entity.newBuilder(KEY2, INCOMPLETE_ENTITY_1).build(), entities.get(1)); + assertEquals(Entity.newBuilder(KEY3, INCOMPLETE_ENTITY_2).build(), entities.get(2)); assertEquals(entity2, entities.get(3)); } @@ -165,7 +171,7 @@ public void testUpdate() throws Exception { @Test public void testUpdateAfterUpdate() throws Exception { - Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); + Entity entity = Entity.newBuilder(ENTITY1).set("foo", "bar").build(); List pbs = new LinkedList<>(); pbs.add(com.google.datastore.v1.Mutation.newBuilder().setUpdate(entity.toPb()).build()); batchWriter.update(ENTITY1); @@ -175,7 +181,7 @@ public void testUpdateAfterUpdate() throws Exception { @Test public void testUpdateAfterAdd() throws Exception { - Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); + Entity entity = Entity.newBuilder(ENTITY1).set("foo", "bar").build(); List pbs = new LinkedList<>(); pbs.add(com.google.datastore.v1.Mutation.newBuilder().setUpsert(entity.toPb()).build()); batchWriter.add(ENTITY1); @@ -185,7 +191,7 @@ public void testUpdateAfterAdd() throws Exception { @Test public void testUpdateAfterPut() throws Exception { - Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); + Entity entity = Entity.newBuilder(ENTITY1).set("foo", "bar").build(); List pbs = new LinkedList<>(); pbs.add(com.google.datastore.v1.Mutation.newBuilder().setUpsert(entity.toPb()).build()); batchWriter.put(ENTITY1); @@ -224,16 +230,16 @@ public void testPutIncompleteKey() throws Exception { List pbs = new LinkedList<>(); pbs.add(com.google.datastore.v1.Mutation.newBuilder().setUpsert(ENTITY1.toPb()).build()); pbs.add(com.google.datastore.v1.Mutation.newBuilder() - .setUpsert(Entity.builder(KEY2, INCOMPLETE_ENTITY_1).build().toPb()) + .setUpsert(Entity.newBuilder(KEY2, INCOMPLETE_ENTITY_1).build().toPb()) .build()); pbs.add(com.google.datastore.v1.Mutation.newBuilder() - .setUpsert(Entity.builder(KEY3, INCOMPLETE_ENTITY_2).build().toPb()) + .setUpsert(Entity.newBuilder(KEY3, INCOMPLETE_ENTITY_2).build().toPb()) .build()); Entity putEntity = batchWriter.put(ENTITY1); List putEntities = batchWriter.put(INCOMPLETE_ENTITY_1, INCOMPLETE_ENTITY_2); assertEquals(ENTITY1, putEntity); - assertEquals(Entity.builder(KEY2, INCOMPLETE_ENTITY_1).build(), putEntities.get(0)); - assertEquals(Entity.builder(KEY3, INCOMPLETE_ENTITY_2).build(), putEntities.get(1)); + assertEquals(Entity.newBuilder(KEY2, INCOMPLETE_ENTITY_1).build(), putEntities.get(0)); + assertEquals(Entity.newBuilder(KEY3, INCOMPLETE_ENTITY_2).build(), putEntities.get(1)); assertEquals(pbs, batchWriter.toMutationPbList()); } @@ -254,7 +260,7 @@ public void testPutWithDeferredAllocation() throws Exception { @Test public void testPutAfterPut() throws Exception { - Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); + Entity entity = Entity.newBuilder(ENTITY1).set("foo", "bar").build(); List pbs = new LinkedList<>(); pbs.add(com.google.datastore.v1.Mutation.newBuilder().setUpsert(entity.toPb()).build()); Entity putEntity1 = batchWriter.put(ENTITY1); @@ -266,7 +272,7 @@ public void testPutAfterPut() throws Exception { @Test public void testPutAfterAdd() throws Exception { - Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); + Entity entity = Entity.newBuilder(ENTITY1).set("foo", "bar").build(); List pbs = new LinkedList<>(); pbs.add(com.google.datastore.v1.Mutation.newBuilder().setUpsert(entity.toPb()).build()); batchWriter.add(ENTITY1); @@ -276,7 +282,7 @@ public void testPutAfterAdd() throws Exception { @Test public void testPutAfterUpdate() throws Exception { - Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); + Entity entity = Entity.newBuilder(ENTITY1).set("foo", "bar").build(); List pbs = new LinkedList<>(); pbs.add(com.google.datastore.v1.Mutation.newBuilder().setUpsert(entity.toPb()).build()); batchWriter.update(ENTITY1); @@ -287,7 +293,7 @@ public void testPutAfterUpdate() throws Exception { @Test public void testPutAfterDelete() throws Exception { - Entity entity = Entity.builder(ENTITY1).set("foo", "bar").build(); + Entity entity = Entity.newBuilder(ENTITY1).set("foo", "bar").build(); List pbs = new LinkedList<>(); pbs.add(com.google.datastore.v1.Mutation.newBuilder().setUpsert(entity.toPb()).build()); batchWriter.delete(KEY1); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BaseEntityTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BaseEntityTest.java index 08884a997bc0..598b6c2dde66 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BaseEntityTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BaseEntityTest.java @@ -36,11 +36,11 @@ public class BaseEntityTest { private static final Blob BLOB = Blob.copyFrom(new byte[]{1, 2}); private static final DateTime DATE_TIME = DateTime.now(); private static final LatLng LAT_LNG = new LatLng(37.422035, -122.084124); - private static final Key KEY = Key.builder("ds1", "k1", "n1").build(); - private static final Entity ENTITY = Entity.builder(KEY).set("name", "foo").build(); - private static final IncompleteKey INCOMPLETE_KEY = IncompleteKey.builder("ds1", "k1").build(); + private static final Key KEY = Key.newBuilder("ds1", "k1", "n1").build(); + private static final Entity ENTITY = Entity.newBuilder(KEY).set("name", "foo").build(); + private static final IncompleteKey INCOMPLETE_KEY = IncompleteKey.newBuilder("ds1", "k1").build(); private static final FullEntity PARTIAL_ENTITY = - Entity.builder(INCOMPLETE_KEY).build(); + Entity.newBuilder(INCOMPLETE_KEY).build(); private Builder builder; @@ -67,8 +67,8 @@ public void setUp() { builder.set("booleanList", true, false, true); builder.set("dateTimeList", DateTime.now(), DateTime.now(), DateTime.now()); builder.set("doubleList", 12.3, 4.56, .789); - builder.set("keyList", KEY, Key.builder("ds2", "k2", "n2").build(), - Key.builder("ds3", "k3", "n3").build()); + builder.set("keyList", KEY, Key.newBuilder("ds2", "k2", "n2").build(), + Key.newBuilder("ds3", "k3", "n3").build()); builder.set("entityList", ENTITY, PARTIAL_ENTITY); builder.set("stringList", "s1", "s2", "s3"); builder.set("longList", 1, 23, 456); @@ -165,7 +165,7 @@ public void testGetLatLng() throws Exception { public void testGetKey() throws Exception { BaseEntity entity = builder.build(); assertEquals(KEY, entity.getKey("key")); - Key key = Key.builder(KEY).name("BLA").build(); + Key key = Key.newBuilder(KEY).setName("BLA").build(); entity = builder.set("key", key).build(); assertEquals(key, entity.getKey("key")); } @@ -220,6 +220,19 @@ public void testGetBlob() throws Exception { @Test public void testNames() throws Exception { + Set names = + ImmutableSet.builder() + .add("string", "stringValue", "boolean", "double", "long", "list1", "list2", "list3") + .add("entity", "partialEntity", "null", "dateTime", "blob", "key", "blobList") + .add("booleanList", "dateTimeList", "doubleList", "keyList", "entityList", "stringList") + .add("longList", "latLng", "latLngList") + .build(); + BaseEntity entity = builder.build(); + assertEquals(names, entity.getNames()); + } + + @Test + public void testNamesDeprecated() throws Exception { Set names = ImmutableSet.builder() .add("string", "stringValue", "boolean", "double", "long", "list1", "list2", "list3") @@ -230,4 +243,18 @@ public void testNames() throws Exception { BaseEntity entity = builder.build(); assertEquals(names, entity.names()); } + + @Test + public void testKey() throws Exception { + builder.setKey(KEY); + BaseEntity entity = builder.build(); + assertEquals(KEY, entity.getKey()); + } + + @Test + public void testKeyDeprecated() throws Exception { + builder.key(KEY); + BaseEntity entity = builder.build(); + assertEquals(KEY, entity.key()); + } } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BaseKeyTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BaseKeyTest.java index 9d46c2eebb94..aa5302d15d62 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BaseKeyTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BaseKeyTest.java @@ -47,15 +47,30 @@ protected BaseKey build() { return new BaseKey(projectId, namespace, path.build()) { @Override + @Deprecated protected BaseKey parent() { return null; } + + @Override + protected BaseKey getParent() { + return null; + } }; } } @Test - public void testDataset() throws Exception { + public void testProjectId() throws Exception { + Builder builder = new Builder("ds1", "k"); + BaseKey key = builder.build(); + assertEquals("ds1", key.getProjectId()); + key = builder.setProjectId("ds2").build(); + assertEquals("ds2", key.getProjectId()); + } + + @Test + public void testProjectIdDeprecated() throws Exception { Builder builder = new Builder("ds1", "k"); BaseKey key = builder.build(); assertEquals("ds1", key.projectId()); @@ -70,12 +85,28 @@ public void testBadDatasetInConstructor() throws Exception { @Test(expected = IllegalArgumentException.class) public void testBadDatasetInSetter() throws Exception { + Builder builder = new Builder("d", "k"); + builder.setProjectId(" "); + } + + @Test(expected = IllegalArgumentException.class) + public void testBadDatasetInSetterDeprecated() throws Exception { Builder builder = new Builder("d", "k"); builder.projectId(" "); } @Test public void testNamespace() throws Exception { + Builder builder = new Builder("ds", "k"); + BaseKey key = builder.build(); + assertTrue(key.getNamespace() != null); + assertTrue(key.getNamespace().isEmpty()); + key = builder.setNamespace("ns").build(); + assertEquals("ns", key.getNamespace()); + } + + @Test + public void testNamespaceDeprecated() throws Exception { Builder builder = new Builder("ds", "k"); BaseKey key = builder.build(); assertTrue(key.namespace() != null); @@ -86,6 +117,15 @@ public void testNamespace() throws Exception { @Test public void testKind() throws Exception { + Builder builder = new Builder("ds", "k1"); + BaseKey key = builder.build(); + assertEquals("k1", key.getKind()); + key = builder.setKind("k2").build(); + assertEquals("k2", key.getKind()); + } + + @Test + public void testKindDeprecated() throws Exception { Builder builder = new Builder("ds", "k1"); BaseKey key = builder.build(); assertEquals("k1", key.kind()); @@ -106,12 +146,32 @@ public void testBadKindInConstructor() throws Exception { @Test(expected = IllegalArgumentException.class) public void testBadKindInSetter() throws Exception { + Builder builder = new Builder("ds", "k1"); + builder.setKind(""); + } + + @Test(expected = IllegalArgumentException.class) + public void testBadKindInSetterDeprecated() throws Exception { Builder builder = new Builder("ds", "k1"); builder.kind(""); } @Test public void testAncestors() throws Exception { + Builder builder = new Builder("ds", "k"); + BaseKey key = builder.build(); + assertTrue(key.getAncestors().isEmpty()); + List path = new ArrayList<>(); + path.add(PathElement.of("p1", "v1")); + key = builder.addAncestor(path.get(0)).build(); + assertEquals(path, key.getAncestors()); + path.add(PathElement.of("p2", "v2")); + key = builder.addAncestor(path.get(1)).build(); + assertEquals(path, key.getAncestors()); + } + + @Test + public void testAncestorsDeprecated() throws Exception { Builder builder = new Builder("ds", "k"); BaseKey key = builder.build(); assertTrue(key.ancestors().isEmpty()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BlobTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BlobTest.java index 009c1a31ee1e..2746880f7735 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BlobTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BlobTest.java @@ -55,6 +55,12 @@ public void testEquals() throws Exception { @Test public void testLength() throws Exception { + assertEquals(bytes1.length, blob1.getLength()); + assertEquals(bytes2.length, blob2.getLength()); + } + + @Test + public void testLengthDeprecated() throws Exception { assertEquals(bytes1.length, blob1.length()); assertEquals(bytes2.length, blob2.length()); } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BlobValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BlobValueTest.java index 3c6586939a54..2232cfb55a54 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BlobValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BlobValueTest.java @@ -32,7 +32,6 @@ public void testToBuilder() throws Exception { assertEquals(value, value.toBuilder().build()); } - @SuppressWarnings("deprecation") @Test public void testOf() throws Exception { BlobValue value = BlobValue.of(CONTENT); @@ -43,6 +42,15 @@ public void testOf() throws Exception { @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { + BlobValue.Builder builder = BlobValue.newBuilder(CONTENT); + BlobValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build(); + assertEquals(CONTENT, value.get()); + assertEquals(1, value.getMeaning()); + assertTrue(value.excludeFromIndexes()); + } + + @Test + public void testBuilderDeprecated() throws Exception { BlobValue.Builder builder = BlobValue.builder(CONTENT); BlobValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BooleanValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BooleanValueTest.java index 2750c70e992b..983be5db7a62 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BooleanValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/BooleanValueTest.java @@ -30,7 +30,6 @@ public void testToBuilder() throws Exception { assertEquals(value, value.toBuilder().build()); } - @SuppressWarnings("deprecation") @Test public void testOf() throws Exception { BooleanValue value = BooleanValue.of(false); @@ -41,6 +40,15 @@ public void testOf() throws Exception { @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { + BooleanValue.Builder builder = BooleanValue.newBuilder(true); + BooleanValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build(); + assertTrue(value.get()); + assertEquals(1, value.getMeaning()); + assertTrue(value.excludeFromIndexes()); + } + + @Test + public void testBuilderDeprecated() throws Exception { BooleanValue.Builder builder = BooleanValue.builder(true); BooleanValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertTrue(value.get()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreHelperTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreHelperTest.java index 2538a75847bd..95a61d47484f 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreHelperTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreHelperTest.java @@ -46,19 +46,19 @@ public void testNewKeyFactory() { expect(options.namespace()).andReturn("ns1").once(); replay(options); KeyFactory keyFactory = DatastoreHelper.newKeyFactory(options); - Key key = keyFactory.kind("k").newKey("bla"); - assertEquals("ds1", key.projectId()); - assertEquals("ns1", key.namespace()); - assertEquals("k", key.kind()); - assertEquals("bla", key.name()); + Key key = keyFactory.setKind("k").newKey("bla"); + assertEquals("ds1", key.getProjectId()); + assertEquals("ns1", key.getNamespace()); + assertEquals("k", key.getKind()); + assertEquals("bla", key.getName()); verify(options); } @Test public void testAllocateId() throws Exception { Datastore datastore = createStrictMock(Datastore.class); - IncompleteKey pKey1 = IncompleteKey.builder("ds", "k").build(); - Key key1 = Key.builder(pKey1, 1).build(); + IncompleteKey pKey1 = IncompleteKey.newBuilder("ds", "k").build(); + Key key1 = Key.newBuilder(pKey1, 1).build(); expect(datastore.allocateId(new IncompleteKey[] {pKey1})) .andReturn(Collections.singletonList(key1)); replay(datastore); @@ -69,10 +69,10 @@ public void testAllocateId() throws Exception { @Test public void testGetWithDatastore() throws Exception { Datastore datastore = createStrictMock(Datastore.class); - IncompleteKey pKey1 = IncompleteKey.builder("ds", "k").build(); - Key key1 = Key.builder(pKey1, 1).build(); - Entity entity1 = Entity.builder(key1).build(); - Key key2 = Key.builder(pKey1, 2).build(); + IncompleteKey pKey1 = IncompleteKey.newBuilder("ds", "k").build(); + Key key1 = Key.newBuilder(pKey1, 1).build(); + Entity entity1 = Entity.newBuilder(key1).build(); + Key key2 = Key.newBuilder(pKey1, 2).build(); ReadOption eventualConsistency = ReadOption.eventualConsistency(); expect(datastore.get(Collections.singletonList(key1))) .andReturn(Collections.singletonList(entity1).iterator()); @@ -90,10 +90,10 @@ public void testGetWithDatastore() throws Exception { @Test public void testGetWithTransaction() throws Exception { Transaction transaction = createStrictMock(Transaction.class); - IncompleteKey pKey1 = IncompleteKey.builder("ds", "k").build(); - Key key1 = Key.builder(pKey1, 1).build(); - Entity entity1 = Entity.builder(key1).build(); - Key key2 = Key.builder(pKey1, 2).build(); + IncompleteKey pKey1 = IncompleteKey.newBuilder("ds", "k").build(); + Key key1 = Key.newBuilder(pKey1, 1).build(); + Entity entity1 = Entity.newBuilder(key1).build(); + Key key2 = Key.newBuilder(pKey1, 2).build(); expect(transaction.get(new Key[] {key1})) .andReturn(Collections.singletonList(entity1).iterator()); expect(transaction.get(new Key[] {key2})).andReturn(Collections.emptyIterator()); @@ -106,9 +106,9 @@ public void testGetWithTransaction() throws Exception { @Test public void testAdd() throws Exception { Datastore datastore = createStrictMock(Datastore.class); - IncompleteKey pKey = IncompleteKey.builder("ds", "k").build(); - Key key = Key.builder(pKey, 1).build(); - Entity entity = Entity.builder(key).build(); + IncompleteKey pKey = IncompleteKey.newBuilder("ds", "k").build(); + Key key = Key.newBuilder(pKey, 1).build(); + Entity entity = Entity.newBuilder(key).build(); expect(datastore.add(new Entity[] {entity})).andReturn(Collections.singletonList(entity)); replay(datastore); assertEquals(entity, DatastoreHelper.add(datastore, entity)); @@ -118,11 +118,11 @@ public void testAdd() throws Exception { @Test public void testFetchWithDatastore() throws Exception { Datastore datastore = createStrictMock(Datastore.class); - IncompleteKey pKey1 = IncompleteKey.builder("ds", "k").build(); - Key key1 = Key.builder(pKey1, 1).build(); - Key key2 = Key.builder(pKey1, "a").build(); - Entity entity1 = Entity.builder(key1).build(); - Entity entity2 = Entity.builder(key2).build(); + IncompleteKey pKey1 = IncompleteKey.newBuilder("ds", "k").build(); + Key key1 = Key.newBuilder(pKey1, 1).build(); + Key key2 = Key.newBuilder(pKey1, "a").build(); + Entity entity1 = Entity.newBuilder(key1).build(); + Entity entity2 = Entity.newBuilder(key2).build(); ReadOption eventualConsistency = ReadOption.eventualConsistency(); expect(datastore.get(ImmutableList.of(key1, key2))) .andReturn(Iterators.forArray(entity1, entity2)) @@ -145,11 +145,11 @@ public void testFetchWithDatastore() throws Exception { @Test public void testFetchWithTransaction() throws Exception { Transaction transaction = createStrictMock(Transaction.class); - IncompleteKey pKey1 = IncompleteKey.builder("ds", "k").build(); - Key key1 = Key.builder(pKey1, 1).build(); - Key key2 = Key.builder(pKey1, "a").build(); - Entity entity1 = Entity.builder(key1).build(); - Entity entity2 = Entity.builder(key2).build(); + IncompleteKey pKey1 = IncompleteKey.newBuilder("ds", "k").build(); + Key key1 = Key.newBuilder(pKey1, 1).build(); + Key key2 = Key.newBuilder(pKey1, "a").build(); + Entity entity1 = Entity.newBuilder(key1).build(); + Entity entity2 = Entity.newBuilder(key2).build(); expect(transaction.get(new Key[] {key1, key2})) .andReturn(Iterators.forArray(entity1, entity2)) .once(); @@ -166,15 +166,15 @@ public void testRunInTransaction() throws Exception { final Datastore datastore = createStrictMock(Datastore.class); final Transaction transaction = createStrictMock(Transaction.class); expect(datastore.newTransaction()).andReturn(transaction).once(); - expect(transaction.active()).andReturn(true).once(); + expect(transaction.isActive()).andReturn(true).once(); expect(transaction.commit()).andReturn(null).once(); - expect(transaction.active()).andReturn(false).once(); + expect(transaction.isActive()).andReturn(false).once(); replay(datastore, transaction); String value = DatastoreHelper.runInTransaction(datastore, new TransactionCallable() { @Override public String run(DatastoreReaderWriter readerWriter) { - assertTrue(transaction.active()); + assertTrue(transaction.isActive()); assertSame(transaction, readerWriter); return "done"; } @@ -188,16 +188,16 @@ public void testRunInTransactionWithException() throws Exception { final Datastore datastore = createStrictMock(Datastore.class); final Transaction transaction = createStrictMock(Transaction.class); expect(datastore.newTransaction()).andReturn(transaction).once(); - expect(transaction.active()).andReturn(true).once(); + expect(transaction.isActive()).andReturn(true).once(); transaction.rollback(); EasyMock.expectLastCall().once(); - expect(transaction.active()).andReturn(false).once(); + expect(transaction.isActive()).andReturn(false).once(); replay(datastore, transaction); try { DatastoreHelper.runInTransaction(datastore, new TransactionCallable() { @Override public Void run(DatastoreReaderWriter readerWriter) throws Exception { - assertTrue(transaction.active()); + assertTrue(transaction.isActive()); assertSame(transaction, readerWriter); throw new Exception("Bla"); } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreTest.java index 8e8b52fce5ed..7b99f36abc4c 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreTest.java @@ -68,7 +68,7 @@ public class DatastoreTest { private static LocalDatastoreHelper helper = LocalDatastoreHelper.create(1.0); - private static final DatastoreOptions options = helper.options(); + private static final DatastoreOptions options = helper.getOptions(); private static final Datastore datastore = options.service(); private static final String PROJECT_ID = options.projectId(); private static final String KIND1 = "kind1"; @@ -76,19 +76,19 @@ public class DatastoreTest { private static final String KIND3 = "kind3"; private static final NullValue NULL_VALUE = NullValue.of(); private static final StringValue STR_VALUE = StringValue.of("str"); - private static final BooleanValue BOOL_VALUE = BooleanValue.builder(false) - .excludeFromIndexes(true).build(); + private static final BooleanValue BOOL_VALUE = BooleanValue.newBuilder(false) + .setExcludeFromIndexes(true).build(); private static final IncompleteKey INCOMPLETE_KEY1 = - IncompleteKey.builder(PROJECT_ID, KIND1).build(); + IncompleteKey.newBuilder(PROJECT_ID, KIND1).build(); private static final IncompleteKey INCOMPLETE_KEY2 = - IncompleteKey.builder(PROJECT_ID, KIND2).build(); - private static final Key KEY1 = Key.builder(INCOMPLETE_KEY1, "name").build(); - private static final Key KEY2 = Key.builder(KEY1, KIND2, 1).build(); - private static final Key KEY3 = Key.builder(KEY2).name("bla").build(); - private static final Key KEY4 = Key.builder(KEY2).name("newName1").build(); - private static final Key KEY5 = Key.builder(KEY2).name("newName2").build(); + IncompleteKey.newBuilder(PROJECT_ID, KIND2).build(); + private static final Key KEY1 = Key.newBuilder(INCOMPLETE_KEY1, "name").build(); + private static final Key KEY2 = Key.newBuilder(KEY1, KIND2, 1).build(); + private static final Key KEY3 = Key.newBuilder(KEY2).setName("bla").build(); + private static final Key KEY4 = Key.newBuilder(KEY2).setName("newName1").build(); + private static final Key KEY5 = Key.newBuilder(KEY2).setName("newName2").build(); private static final KeyValue KEY_VALUE = KeyValue.of(KEY1); - private static final ListValue LIST_VALUE1 = ListValue.builder() + private static final ListValue LIST_VALUE1 = ListValue.newBuilder() .addValue(NULL_VALUE) .addValue(STR_VALUE, BOOL_VALUE) .build(); @@ -98,15 +98,16 @@ public class DatastoreTest { private static final LatLngValue LAT_LNG_VALUE = new LatLngValue(new LatLng(37.422035, -122.084124)); private static final FullEntity PARTIAL_ENTITY1 = - FullEntity.builder(INCOMPLETE_KEY2).set("str", STR_VALUE).set("bool", BOOL_VALUE) + FullEntity.newBuilder(INCOMPLETE_KEY2).set("str", STR_VALUE).set("bool", BOOL_VALUE) .set("list", LIST_VALUE1).build(); private static final FullEntity PARTIAL_ENTITY2 = - FullEntity.builder(PARTIAL_ENTITY1).remove("str").set("bool", true) + FullEntity.newBuilder(PARTIAL_ENTITY1).remove("str").set("bool", true) .set("list", LIST_VALUE1.get()).build(); private static final FullEntity PARTIAL_ENTITY3 = - FullEntity.builder(PARTIAL_ENTITY1).key(IncompleteKey.builder(PROJECT_ID, KIND3).build()) + FullEntity.newBuilder(PARTIAL_ENTITY1) + .setKey(IncompleteKey.newBuilder(PROJECT_ID, KIND3).build()) .build(); - private static final Entity ENTITY1 = Entity.builder(KEY1) + private static final Entity ENTITY1 = Entity.newBuilder(KEY1) .set("str", STR_VALUE) .set("date", DATE_TIME_VALUE) .set("latLng", LAT_LNG_VALUE) @@ -115,9 +116,9 @@ public class DatastoreTest { .set("list", LIST_VALUE2) .set("emptyList", EMPTY_LIST_VALUE) .build(); - private static final Entity ENTITY2 = Entity.builder(ENTITY1).key(KEY2).remove("str") + private static final Entity ENTITY2 = Entity.newBuilder(ENTITY1).setKey(KEY2).remove("str") .set("name", "Dan").setNull("null").set("age", 20).build(); - private static final Entity ENTITY3 = Entity.builder(ENTITY1).key(KEY3).remove("str") + private static final Entity ENTITY3 = Entity.newBuilder(ENTITY1).setKey(KEY3).remove("str") .set("null", NULL_VALUE).set("partial1", PARTIAL_ENTITY2).set("partial2", ENTITY2).build(); private DatastoreOptions rpcMockOptions; @@ -142,7 +143,7 @@ public void setUp() { .serviceRpcFactory(rpcFactoryMock) .build(); EasyMock.expect(rpcFactoryMock.create(rpcMockOptions)).andReturn(rpcMock); - StructuredQuery query = Query.keyQueryBuilder().build(); + StructuredQuery query = Query.newKeyQueryBuilder().build(); QueryResults result = datastore.run(query); datastore.delete(Iterators.toArray(result, Key.class)); datastore.add(ENTITY1, ENTITY2); @@ -162,7 +163,7 @@ public void testGetOptions() { public void testNewTransactionCommit() { Transaction transaction = datastore.newTransaction(); transaction.add(ENTITY3); - Entity entity2 = Entity.builder(ENTITY2) + Entity entity2 = Entity.newBuilder(ENTITY2) .clear() .setNull("bla") .build(); @@ -204,7 +205,7 @@ public void testTransactionWithRead() { transaction = datastore.newTransaction(); assertEquals(ENTITY3, transaction.get(KEY3)); // update entity3 during the transaction - datastore.put(Entity.builder(ENTITY3).clear().build()); + datastore.put(Entity.newBuilder(ENTITY3).clear().build()); transaction.update(ENTITY2); try { transaction.commit(); @@ -216,9 +217,9 @@ public void testTransactionWithRead() { @Test public void testTransactionWithQuery() { - Query query = Query.entityQueryBuilder() - .kind(KIND2) - .filter(PropertyFilter.hasAncestor(KEY2)) + Query query = Query.newEntityQueryBuilder() + .setKind(KIND2) + .setFilter(PropertyFilter.hasAncestor(KEY2)) .build(); Transaction transaction = datastore.newTransaction(); QueryResults results = transaction.run(query); @@ -231,9 +232,9 @@ public void testTransactionWithQuery() { transaction = datastore.newTransaction(); results = transaction.run(query); assertEquals(ENTITY2, results.next()); - transaction.delete(ENTITY3.key()); + transaction.delete(ENTITY3.getKey()); // update entity2 during the transaction - datastore.put(Entity.builder(ENTITY2).clear().build()); + datastore.put(Entity.newBuilder(ENTITY2).clear().build()); try { transaction.commit(); fail("Expecting a failure"); @@ -246,8 +247,8 @@ public void testTransactionWithQuery() { public void testNewTransactionRollback() { Transaction transaction = datastore.newTransaction(); transaction.add(ENTITY3); - Entity entity2 = Entity.builder(ENTITY2).clear().setNull("bla") - .set("list3", StringValue.of("bla"), StringValue.builder("bla").build()).build(); + Entity entity2 = Entity.newBuilder(ENTITY2).clear().setNull("bla") + .set("list3", StringValue.of("bla"), StringValue.newBuilder("bla").build()).build(); transaction.update(entity2); transaction.delete(KEY1); transaction.rollback(); @@ -292,7 +293,7 @@ private void verifyNotUsable(DatastoreWriter writer) { } try { - writer.delete(ENTITY3.key()); + writer.delete(ENTITY3.getKey()); fail("Expecting a failure"); } catch (DatastoreException ex) { // expected to fail @@ -302,28 +303,29 @@ private void verifyNotUsable(DatastoreWriter writer) { @Test public void testNewBatch() { Batch batch = datastore.newBatch(); - Entity entity1 = Entity.builder(ENTITY1).clear().build(); - Entity entity2 = Entity.builder(ENTITY2).clear().setNull("bla").build(); - Entity entity4 = Entity.builder(KEY4).set("value", StringValue.of("value")).build(); - Entity entity5 = Entity.builder(KEY5).set("value", "value").build(); + Entity entity1 = Entity.newBuilder(ENTITY1).clear().build(); + Entity entity2 = Entity.newBuilder(ENTITY2).clear().setNull("bla").build(); + Entity entity4 = Entity.newBuilder(KEY4).set("value", StringValue.of("value")).build(); + Entity entity5 = Entity.newBuilder(KEY5).set("value", "value").build(); List entities = batch.add(entity4, PARTIAL_ENTITY2, entity5); Entity entity6 = entities.get(1); assertSame(entity4, entities.get(0)); - assertEquals(PARTIAL_ENTITY2.properties(), entity6.properties()); - assertEquals(PARTIAL_ENTITY2.key().projectId(), entity6.key().projectId()); - assertEquals(PARTIAL_ENTITY2.key().namespace(), entity6.key().namespace()); - assertEquals(PARTIAL_ENTITY2.key().ancestors(), entity6.key().ancestors()); - assertEquals(PARTIAL_ENTITY2.key().kind(), entity6.key().kind()); - assertEquals(PARTIAL_ENTITY2.key(), IncompleteKey.builder(entity6.key()).build()); - assertNotEquals(PARTIAL_ENTITY2.key().path(), entity6.key().path()); - assertNotEquals(PARTIAL_ENTITY2.key(), entity6.key()); + assertEquals(PARTIAL_ENTITY2.getProperties(), entity6.getProperties()); + assertEquals(PARTIAL_ENTITY2.getKey().getProjectId(), entity6.getKey().getProjectId()); + assertEquals(PARTIAL_ENTITY2.getKey().getNamespace(), entity6.getKey().getNamespace()); + assertEquals(PARTIAL_ENTITY2.getKey().getAncestors(), entity6.getKey().getAncestors()); + assertEquals(PARTIAL_ENTITY2.getKey().getKind(), entity6.getKey().getKind()); + assertEquals(PARTIAL_ENTITY2.getKey(), IncompleteKey.newBuilder(entity6.getKey()).build()); + assertNotEquals(PARTIAL_ENTITY2.getKey().getPath(), entity6.getKey().getPath()); + assertNotEquals(PARTIAL_ENTITY2.getKey(), entity6.getKey()); assertSame(entity5, entities.get(2)); batch.addWithDeferredIdAllocation(PARTIAL_ENTITY3); batch.put(ENTITY3, entity1, entity2); Batch.Response response = batch.submit(); - entities = datastore.fetch(KEY1, KEY2, KEY3, entity4.key(), entity5.key(), entity6.key()); + entities = + datastore.fetch(KEY1, KEY2, KEY3, entity4.getKey(), entity5.getKey(), entity6.getKey()); assertEquals(entity1, entities.get(0)); assertEquals(entity2, entities.get(1)); assertEquals(ENTITY3, entities.get(2)); @@ -331,10 +333,10 @@ public void testNewBatch() { assertEquals(entity5, entities.get(4)); assertEquals(entity6, entities.get(5)); assertEquals(6, entities.size()); - List generatedKeys = response.generatedKeys(); + List generatedKeys = response.getGeneratedKeys(); assertEquals(1, generatedKeys.size()); - assertEquals(PARTIAL_ENTITY3.properties(), datastore.get(generatedKeys.get(0)).properties()); - assertEquals(PARTIAL_ENTITY3.key(), IncompleteKey.builder(generatedKeys.get(0)).build()); + assertEquals(PARTIAL_ENTITY3.getProperties(), datastore.get(generatedKeys.get(0)).getProperties()); + assertEquals(PARTIAL_ENTITY3.getKey(), IncompleteKey.newBuilder(generatedKeys.get(0)).build()); try { batch.submit(); @@ -345,10 +347,10 @@ public void testNewBatch() { verifyNotUsable(batch); batch = datastore.newBatch(); - batch.delete(entity4.key(), entity5.key()); + batch.delete(entity4.getKey(), entity5.getKey()); batch.update(ENTITY1, ENTITY2, ENTITY3); batch.submit(); - entities = datastore.fetch(KEY1, KEY2, KEY3, entity4.key(), entity5.key()); + entities = datastore.fetch(KEY1, KEY2, KEY3, entity4.getKey(), entity5.getKey()); assertEquals(ENTITY1, entities.get(0)); assertEquals(ENTITY2, entities.get(1)); assertEquals(ENTITY3, entities.get(2)); @@ -360,14 +362,14 @@ public void testNewBatch() { @Test public void testRunGqlQueryNoCasting() { Query query1 = - Query.gqlQueryBuilder(ResultType.ENTITY, "select * from " + KIND1).build(); + Query.newGqlQueryBuilder(ResultType.ENTITY, "select * from " + KIND1).build(); QueryResults results1 = datastore.run(query1); assertTrue(results1.hasNext()); assertEquals(ENTITY1, results1.next()); assertFalse(results1.hasNext()); datastore.put(ENTITY3); - Query query2 = Query.gqlQueryBuilder( + Query query2 = Query.newGqlQueryBuilder( ResultType.ENTITY, "select * from " + KIND2 + " order by __key__").build(); QueryResults results2 = datastore.run(query2); assertTrue(results2.hasNext()); @@ -376,27 +378,27 @@ public void testRunGqlQueryNoCasting() { assertEquals(ENTITY3, results2.next()); assertFalse(results2.hasNext()); - query1 = Query.gqlQueryBuilder(ResultType.ENTITY, "select * from bla").build(); + query1 = Query.newGqlQueryBuilder(ResultType.ENTITY, "select * from bla").build(); results1 = datastore.run(query1); assertFalse(results1.hasNext()); Query keyOnlyQuery = - Query.gqlQueryBuilder(ResultType.KEY, "select __key__ from " + KIND1).build(); + Query.newGqlQueryBuilder(ResultType.KEY, "select __key__ from " + KIND1).build(); QueryResults keyOnlyResults = datastore.run(keyOnlyQuery); assertTrue(keyOnlyResults.hasNext()); assertEquals(KEY1, keyOnlyResults.next()); assertFalse(keyOnlyResults.hasNext()); - GqlQuery keyProjectionQuery = Query.gqlQueryBuilder( + GqlQuery keyProjectionQuery = Query.newGqlQueryBuilder( ResultType.PROJECTION_ENTITY, "select __key__ from " + KIND1).build(); QueryResults keyProjectionResult = datastore.run(keyProjectionQuery); assertTrue(keyProjectionResult.hasNext()); ProjectionEntity projectionEntity = keyProjectionResult.next(); - assertEquals(KEY1, projectionEntity.key()); - assertTrue(projectionEntity.properties().isEmpty()); + assertEquals(KEY1, projectionEntity.getKey()); + assertTrue(projectionEntity.getProperties().isEmpty()); assertFalse(keyProjectionResult.hasNext()); - GqlQuery projectionQuery = Query.gqlQueryBuilder( + GqlQuery projectionQuery = Query.newGqlQueryBuilder( ResultType.PROJECTION_ENTITY, "select str, date from " + KIND1).build(); QueryResults projectionResult = datastore.run(projectionQuery); @@ -404,9 +406,9 @@ public void testRunGqlQueryNoCasting() { projectionEntity = projectionResult.next(); assertEquals("str", projectionEntity.getString("str")); assertEquals(DATE_TIME_VALUE.get(), projectionEntity.getDateTime("date")); - assertEquals(DATE_TIME_VALUE.get().timestampMicroseconds(), + assertEquals(DATE_TIME_VALUE.get().getTimestampMicroseconds(), projectionEntity.getLong("date")); - assertEquals(2, projectionEntity.names().size()); + assertEquals(2, projectionEntity.getNames().size()); assertFalse(projectionResult.hasNext()); } @@ -414,15 +416,15 @@ public void testRunGqlQueryNoCasting() { public void testRunGqlQueryWithCasting() { @SuppressWarnings("unchecked") Query query1 = - (Query) Query.gqlQueryBuilder("select * from " + KIND1).build(); + (Query) Query.newGqlQueryBuilder("select * from " + KIND1).build(); QueryResults results1 = datastore.run(query1); assertTrue(results1.hasNext()); assertEquals(ENTITY1, results1.next()); assertFalse(results1.hasNext()); - Query query2 = Query.gqlQueryBuilder("select * from " + KIND1).build(); + Query query2 = Query.newGqlQueryBuilder("select * from " + KIND1).build(); QueryResults results2 = datastore.run(query2); - assertSame(Entity.class, results2.resultClass()); + assertSame(Entity.class, results2.getResultClass()); @SuppressWarnings("unchecked") QueryResults results3 = (QueryResults) results2; assertTrue(results3.hasNext()); @@ -440,7 +442,7 @@ public void testGqlQueryPagination() throws DatastoreException { EasyMock.replay(rpcFactoryMock, rpcMock); Datastore mockDatastore = rpcMockOptions.service(); QueryResults results = - mockDatastore.run(Query.gqlQueryBuilder(ResultType.KEY, "select __key__ from *").build()); + mockDatastore.run(Query.newGqlQueryBuilder(ResultType.KEY, "select __key__ from *").build()); int count = 0; while (results.hasNext()) { count += 1; @@ -453,43 +455,43 @@ public void testGqlQueryPagination() throws DatastoreException { @Test public void testRunStructuredQuery() { Query query = - Query.entityQueryBuilder().kind(KIND1).orderBy(OrderBy.asc("__key__")).build(); + Query.newEntityQueryBuilder().setKind(KIND1).setOrderBy(OrderBy.asc("__key__")).build(); QueryResults results1 = datastore.run(query); assertTrue(results1.hasNext()); assertEquals(ENTITY1, results1.next()); assertFalse(results1.hasNext()); - Query keyOnlyQuery = Query.keyQueryBuilder().kind(KIND1).build(); + Query keyOnlyQuery = Query.newKeyQueryBuilder().setKind(KIND1).build(); QueryResults results2 = datastore.run(keyOnlyQuery); assertTrue(results2.hasNext()); - assertEquals(ENTITY1.key(), results2.next()); + assertEquals(ENTITY1.getKey(), results2.next()); assertFalse(results2.hasNext()); StructuredQuery keyOnlyProjectionQuery = - Query.projectionEntityQueryBuilder() - .kind(KIND1).projection("__key__").build(); + Query.newProjectionEntityQueryBuilder() + .setKind(KIND1).setProjection("__key__").build(); QueryResults results3 = datastore.run(keyOnlyProjectionQuery); assertTrue(results3.hasNext()); ProjectionEntity projectionEntity = results3.next(); - assertEquals(ENTITY1.key(), projectionEntity.key()); - assertTrue(projectionEntity.names().isEmpty()); + assertEquals(ENTITY1.getKey(), projectionEntity.getKey()); + assertTrue(projectionEntity.getNames().isEmpty()); assertFalse(results2.hasNext()); - StructuredQuery projectionQuery = Query.projectionEntityQueryBuilder() - .kind(KIND2) - .projection("age") - .filter(PropertyFilter.gt("age", 18)) - .distinctOn("age") - .orderBy(OrderBy.asc("age")) - .limit(10) + StructuredQuery projectionQuery = Query.newProjectionEntityQueryBuilder() + .setKind(KIND2) + .setProjection("age") + .setFilter(PropertyFilter.gt("age", 18)) + .setDistinctOn("age") + .setOrderBy(OrderBy.asc("age")) + .setLimit(10) .build(); QueryResults results4 = datastore.run(projectionQuery); assertTrue(results4.hasNext()); ProjectionEntity entity = results4.next(); - assertEquals(ENTITY2.key(), entity.key()); + assertEquals(ENTITY2.getKey(), entity.getKey()); assertEquals(20, entity.getLong("age")); - assertEquals(1, entity.properties().size()); + assertEquals(1, entity.getProperties().size()); assertFalse(results4.hasNext()); } @@ -502,7 +504,7 @@ public void testStructuredQueryPagination() throws DatastoreException { } EasyMock.replay(rpcFactoryMock, rpcMock); Datastore datastore = rpcMockOptions.service(); - QueryResults results = datastore.run(Query.keyQueryBuilder().build()); + QueryResults results = datastore.run(Query.newKeyQueryBuilder().build()); int count = 0; while (results.hasNext()) { count += 1; @@ -513,11 +515,11 @@ public void testStructuredQueryPagination() throws DatastoreException { } private List buildResponsesForQueryPagination() { - Entity entity4 = Entity.builder(KEY4).set("value", StringValue.of("value")).build(); - Entity entity5 = Entity.builder(KEY5).set("value", "value").build(); + Entity entity4 = Entity.newBuilder(KEY4).set("value", StringValue.of("value")).build(); + Entity entity5 = Entity.newBuilder(KEY5).set("value", "value").build(); datastore.add(ENTITY3, entity4, entity5); List responses = new ArrayList<>(); - Query query = Query.keyQueryBuilder().build(); + Query query = Query.newKeyQueryBuilder().build(); RunQueryRequest.Builder requestPb = RunQueryRequest.newBuilder(); query.populatePb(requestPb); QueryResultBatch queryResultBatchPb = RunQueryResponse.newBuilder() @@ -566,7 +568,7 @@ public void testQueryPaginationWithLimit() throws DatastoreException { int limit = 2; int totalCount = 0; Iterator cursorIter = endCursors.iterator(); - StructuredQuery query = Query.entityQueryBuilder().limit(limit).build(); + StructuredQuery query = Query.newEntityQueryBuilder().setLimit(limit).build(); while (true) { QueryResults results = datastore.run(query); int resultCount = 0; @@ -577,23 +579,23 @@ public void testQueryPaginationWithLimit() throws DatastoreException { } assertTrue(cursorIter.hasNext()); Cursor expectedEndCursor = Cursor.copyFrom(cursorIter.next().toByteArray()); - assertEquals(expectedEndCursor, results.cursorAfter()); + assertEquals(expectedEndCursor, results.getCursorAfter()); if (resultCount < limit) { break; } - query = query.toBuilder().startCursor(results.cursorAfter()).build(); + query = query.toBuilder().setStartCursor(results.getCursorAfter()).build(); } assertEquals(5, totalCount); EasyMock.verify(rpcFactoryMock, rpcMock); } private List buildResponsesForQueryPaginationWithLimit() { - Entity entity4 = Entity.builder(KEY4).set("value", StringValue.of("value")).build(); - Entity entity5 = Entity.builder(KEY5).set("value", "value").build(); + Entity entity4 = Entity.newBuilder(KEY4).set("value", StringValue.of("value")).build(); + Entity entity5 = Entity.newBuilder(KEY5).set("value", "value").build(); datastore.add(ENTITY3, entity4, entity5); DatastoreRpc datastoreRpc = datastore.options().rpc(); List responses = new ArrayList<>(); - Query query = Query.entityQueryBuilder().build(); + Query query = Query.newEntityQueryBuilder().build(); RunQueryRequest.Builder requestPb = RunQueryRequest.newBuilder(); query.populatePb(requestPb); QueryResultBatch queryResultBatchPb = RunQueryResponse.newBuilder() @@ -652,7 +654,7 @@ public void testEventualConsistencyQuery() { EasyMock.replay(rpcFactoryMock, rpcMock); Datastore datastore = rpcMockOptions.service(); datastore.run( - Query.gqlQueryBuilder("FROM * SELECT *").build(), ReadOption.eventualConsistency()); + Query.newGqlQueryBuilder("FROM * SELECT *").build(), ReadOption.eventualConsistency()); EasyMock.verify(rpcFactoryMock, rpcMock); } @@ -669,43 +671,43 @@ public void testToUrlSafe() { @Test public void testAllocateId() { - KeyFactory keyFactory = datastore.newKeyFactory().kind(KIND1); + KeyFactory keyFactory = datastore.newKeyFactory().setKind(KIND1); IncompleteKey pk1 = keyFactory.newKey(); Key key1 = datastore.allocateId(pk1); - assertEquals(key1.projectId(), pk1.projectId()); - assertEquals(key1.namespace(), pk1.namespace()); - assertEquals(key1.ancestors(), pk1.ancestors()); - assertEquals(key1.kind(), pk1.kind()); + assertEquals(key1.getProjectId(), pk1.getProjectId()); + assertEquals(key1.getNamespace(), pk1.getNamespace()); + assertEquals(key1.getAncestors(), pk1.getAncestors()); + assertEquals(key1.getKind(), pk1.getKind()); assertTrue(key1.hasId()); assertFalse(key1.hasName()); - assertEquals(Key.builder(pk1, key1.id()).build(), key1); + assertEquals(Key.newBuilder(pk1, key1.getId()).build(), key1); Key key2 = datastore.allocateId(pk1); assertNotEquals(key1, key2); - assertEquals(Key.builder(pk1, key2.id()).build(), key2); + assertEquals(Key.newBuilder(pk1, key2.getId()).build(), key2); Key key3 = datastore.allocateId(key1); assertNotEquals(key1, key3); - assertEquals(Key.builder(pk1, key3.id()).build(), key3); + assertEquals(Key.newBuilder(pk1, key3.getId()).build(), key3); } @Test public void testAllocateIdArray() { - KeyFactory keyFactory = datastore.newKeyFactory().kind(KIND1); + KeyFactory keyFactory = datastore.newKeyFactory().setKind(KIND1); IncompleteKey incompleteKey1 = keyFactory.newKey(); IncompleteKey incompleteKey2 = - keyFactory.kind(KIND2).ancestors(PathElement.of(KIND1, 10)).newKey(); + keyFactory.setKind(KIND2).addAncestor(PathElement.of(KIND1, 10)).newKey(); Key key3 = keyFactory.newKey("name"); Key key4 = keyFactory.newKey(1); List result = datastore.allocateId(incompleteKey1, incompleteKey2, key3, key4, incompleteKey1, key3); assertEquals(6, result.size()); - assertEquals(Key.builder(incompleteKey1, result.get(0).id()).build(), result.get(0)); - assertEquals(Key.builder(incompleteKey1, result.get(4).id()).build(), result.get(4)); - assertEquals(Key.builder(incompleteKey2, result.get(1).id()).build(), result.get(1)); - assertEquals(Key.builder(key3).id(result.get(2).id()).build(), result.get(2)); - assertEquals(Key.builder(key3).id(result.get(5).id()).build(), result.get(5)); - assertEquals(Key.builder(key4).id(result.get(3).id()).build(), result.get(3)); + assertEquals(Key.newBuilder(incompleteKey1, result.get(0).getId()).build(), result.get(0)); + assertEquals(Key.newBuilder(incompleteKey1, result.get(4).getId()).build(), result.get(4)); + assertEquals(Key.newBuilder(incompleteKey2, result.get(1).getId()).build(), result.get(1)); + assertEquals(Key.newBuilder(key3).setId(result.get(2).getId()).build(), result.get(2)); + assertEquals(Key.newBuilder(key3).setId(result.get(5).getId()).build(), result.get(5)); + assertEquals(Key.newBuilder(key4).setId(result.get(3).getId()).build(), result.get(3)); } @Test @@ -729,7 +731,7 @@ public void testGet() { assertEquals(PARTIAL_ENTITY1, value6); ListValue value7 = entity.getValue("emptyList"); assertEquals(EMPTY_LIST_VALUE, value7); - assertEquals(7, entity.names().size()); + assertEquals(7, entity.getNames().size()); assertFalse(entity.contains("bla")); } @@ -759,7 +761,7 @@ public void testLookupEventualConsistency() { public void testGetArrayNoDeferredResults() { datastore.put(ENTITY3); Iterator result = - datastore.fetch(KEY1, Key.builder(KEY1).name("bla").build(), KEY2, KEY3).iterator(); + datastore.fetch(KEY1, Key.newBuilder(KEY1).setName("bla").build(), KEY2, KEY3).iterator(); assertEquals(ENTITY1, result.next()); assertNull(result.next()); assertEquals(ENTITY2, result.next()); @@ -772,10 +774,10 @@ public void testGetArrayNoDeferredResults() { FullEntity partial2 = entity3.getEntity("partial2"); assertEquals(PARTIAL_ENTITY2, partial1); assertEquals(ENTITY2, partial2); - assertEquals(ValueType.BOOLEAN, entity3.getValue("bool").type()); + assertEquals(ValueType.BOOLEAN, entity3.getValue("bool").getType()); assertEquals(LAT_LNG_VALUE, entity3.getValue("latLng")); assertEquals(EMPTY_LIST_VALUE, entity3.getValue("emptyList")); - assertEquals(8, entity3.names().size()); + assertEquals(8, entity3.getNames().size()); assertFalse(entity3.contains("bla")); try { entity3.getString("str"); @@ -797,7 +799,7 @@ public void testGetArrayDeferredResults() throws DatastoreException { Iterator iter = createDatastoreForDeferredLookup().get(KEY1, KEY2, KEY3, KEY4, KEY5); Set keysOfFoundEntities = new HashSet<>(); while (iter.hasNext()) { - keysOfFoundEntities.add(iter.next().key()); + keysOfFoundEntities.add(iter.next().getKey()); } assertEquals(requestedKeys, keysOfFoundEntities); } @@ -806,11 +808,11 @@ public void testGetArrayDeferredResults() throws DatastoreException { public void testFetchArrayDeferredResults() throws DatastoreException { List foundEntities = createDatastoreForDeferredLookup().fetch(KEY1, KEY2, KEY3, KEY4, KEY5); - assertEquals(foundEntities.get(0).key(), KEY1); - assertEquals(foundEntities.get(1).key(), KEY2); - assertEquals(foundEntities.get(2).key(), KEY3); - assertEquals(foundEntities.get(3).key(), KEY4); - assertEquals(foundEntities.get(4).key(), KEY5); + assertEquals(foundEntities.get(0).getKey(), KEY1); + assertEquals(foundEntities.get(1).getKey(), KEY2); + assertEquals(foundEntities.get(2).getKey(), KEY3); + assertEquals(foundEntities.get(3).getKey(), KEY4); + assertEquals(foundEntities.get(4).getKey(), KEY5); assertEquals(foundEntities.size(), 5); } @@ -830,8 +832,8 @@ private Datastore createDatastoreForDeferredLookup() throws DatastoreException { .addKeys(keysPb.get(4)) .build()); lookupRequests.add(LookupRequest.newBuilder().addKeys(keysPb.get(4)).build()); - Entity entity4 = Entity.builder(KEY4).set("value", StringValue.of("value")).build(); - Entity entity5 = Entity.builder(KEY5).set("value", "value").build(); + Entity entity4 = Entity.newBuilder(KEY4).set("value", StringValue.of("value")).build(); + Entity entity5 = Entity.newBuilder(KEY5).set("value", "value").build(); List lookupResponses = new ArrayList<>(); lookupResponses.add( LookupResponse.newBuilder() @@ -860,7 +862,7 @@ private Datastore createDatastoreForDeferredLookup() throws DatastoreException { @Test public void testAddEntity() { - List keys = datastore.fetch(ENTITY1.key(), ENTITY3.key()); + List keys = datastore.fetch(ENTITY1.getKey(), ENTITY3.getKey()); assertEquals(ENTITY1, keys.get(0)); assertNull(keys.get(1)); assertEquals(2, keys.size()); @@ -873,19 +875,19 @@ public void testAddEntity() { } List entities = datastore.add(ENTITY3, PARTIAL_ENTITY1, PARTIAL_ENTITY2); - assertEquals(ENTITY3, datastore.get(ENTITY3.key())); + assertEquals(ENTITY3, datastore.get(ENTITY3.getKey())); assertEquals(ENTITY3, entities.get(0)); - assertEquals(PARTIAL_ENTITY1.properties(), entities.get(1).properties()); - assertEquals(PARTIAL_ENTITY1.key().ancestors(), entities.get(1).key().ancestors()); - assertNotNull(datastore.get(entities.get(1).key())); - assertEquals(PARTIAL_ENTITY2.properties(), entities.get(2).properties()); - assertEquals(PARTIAL_ENTITY2.key().ancestors(), entities.get(2).key().ancestors()); - assertNotNull(datastore.get(entities.get(2).key())); + assertEquals(PARTIAL_ENTITY1.getProperties(), entities.get(1).getProperties()); + assertEquals(PARTIAL_ENTITY1.getKey().getAncestors(), entities.get(1).getKey().getAncestors()); + assertNotNull(datastore.get(entities.get(1).getKey())); + assertEquals(PARTIAL_ENTITY2.getProperties(), entities.get(2).getProperties()); + assertEquals(PARTIAL_ENTITY2.getKey().getAncestors(), entities.get(2).getKey().getAncestors()); + assertNotNull(datastore.get(entities.get(2).getKey())); } @Test public void testUpdate() { - List keys = datastore.fetch(ENTITY1.key(), ENTITY3.key()); + List keys = datastore.fetch(ENTITY1.getKey(), ENTITY3.getKey()); assertEquals(ENTITY1, keys.get(0)); assertNull(keys.get(1)); assertEquals(2, keys.size()); @@ -897,44 +899,44 @@ public void testUpdate() { // expected; } datastore.add(ENTITY3); - assertEquals(ENTITY3, datastore.get(ENTITY3.key())); - Entity entity3 = Entity.builder(ENTITY3).clear().set("bla", new NullValue()).build(); + assertEquals(ENTITY3, datastore.get(ENTITY3.getKey())); + Entity entity3 = Entity.newBuilder(ENTITY3).clear().set("bla", new NullValue()).build(); assertNotEquals(ENTITY3, entity3); datastore.update(entity3); - assertEquals(entity3, datastore.get(ENTITY3.key())); + assertEquals(entity3, datastore.get(ENTITY3.getKey())); } @Test public void testPut() { - Entity updatedEntity = Entity.builder(ENTITY1).set("new_property", 42L).build(); + Entity updatedEntity = Entity.newBuilder(ENTITY1).set("new_property", 42L).build(); assertEquals(updatedEntity, datastore.put(updatedEntity)); - assertEquals(updatedEntity, datastore.get(updatedEntity.key())); + assertEquals(updatedEntity, datastore.get(updatedEntity.getKey())); - Entity entity2 = Entity.builder(ENTITY2).clear().set("bla", new NullValue()).build(); + Entity entity2 = Entity.newBuilder(ENTITY2).clear().set("bla", new NullValue()).build(); assertNotEquals(ENTITY2, entity2); List entities = datastore.put(ENTITY1, entity2, ENTITY3, PARTIAL_ENTITY1); assertEquals(ENTITY1, entities.get(0)); assertEquals(entity2, entities.get(1)); assertEquals(ENTITY3, entities.get(2)); - assertEquals(PARTIAL_ENTITY1.properties(), entities.get(3).properties()); - assertEquals(PARTIAL_ENTITY1.key().ancestors(), entities.get(3).key().ancestors()); - assertEquals(ENTITY1, datastore.get(ENTITY1.key())); - assertEquals(entity2, datastore.get(entity2.key())); - assertEquals(ENTITY3, datastore.get(ENTITY3.key())); - Entity entity = datastore.get(entities.get(3).key()); + assertEquals(PARTIAL_ENTITY1.getProperties(), entities.get(3).getProperties()); + assertEquals(PARTIAL_ENTITY1.getKey().getAncestors(), entities.get(3).getKey().getAncestors()); + assertEquals(ENTITY1, datastore.get(ENTITY1.getKey())); + assertEquals(entity2, datastore.get(entity2.getKey())); + assertEquals(ENTITY3, datastore.get(ENTITY3.getKey())); + Entity entity = datastore.get(entities.get(3).getKey()); assertEquals(entities.get(3), entity); } @Test public void testDelete() { Iterator keys = - datastore.fetch(ENTITY1.key(), ENTITY2.key(), ENTITY3.key()).iterator(); + datastore.fetch(ENTITY1.getKey(), ENTITY2.getKey(), ENTITY3.getKey()).iterator(); assertEquals(ENTITY1, keys.next()); assertEquals(ENTITY2, keys.next()); assertNull(keys.next()); assertFalse(keys.hasNext()); - datastore.delete(ENTITY1.key(), ENTITY2.key(), ENTITY3.key()); - keys = datastore.fetch(ENTITY1.key(), ENTITY2.key(), ENTITY3.key()).iterator(); + datastore.delete(ENTITY1.getKey(), ENTITY2.getKey(), ENTITY3.getKey()); + keys = datastore.fetch(ENTITY1.getKey(), ENTITY2.getKey(), ENTITY3.getKey()).iterator(); assertNull(keys.next()); assertNull(keys.next()); assertNull(keys.next()); @@ -943,12 +945,12 @@ public void testDelete() { @Test public void testKeyFactory() { - KeyFactory keyFactory = datastore.newKeyFactory().kind(KIND1); + KeyFactory keyFactory = datastore.newKeyFactory().setKind(KIND1); assertEquals(INCOMPLETE_KEY1, keyFactory.newKey()); - assertEquals(IncompleteKey.builder(INCOMPLETE_KEY1).kind(KIND2).build(), - datastore.newKeyFactory().kind(KIND2).newKey()); + assertEquals(IncompleteKey.newBuilder(INCOMPLETE_KEY1).setKind(KIND2).build(), + datastore.newKeyFactory().setKind(KIND2).newKey()); assertEquals(KEY1, keyFactory.newKey("name")); - assertEquals(Key.builder(KEY1).id(2).build(), keyFactory.newKey(2)); + assertEquals(Key.newBuilder(KEY1).setId(2).build(), keyFactory.newKey(2)); } @Test diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DateTimeTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DateTimeTest.java index 34c2f7b7e29f..3131ea54747b 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DateTimeTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DateTimeTest.java @@ -28,6 +28,13 @@ public class DateTimeTest { @Test public void testTimestampMicroseconds() throws Exception { + Calendar cal = Calendar.getInstance(); + DateTime date = DateTime.copyFrom(cal); + assertEquals(cal.getTimeInMillis() * 1000, date.getTimestampMicroseconds()); + } + + @Test + public void testTimestampMicrosecondsDepreated() throws Exception { Calendar cal = Calendar.getInstance(); DateTime date = DateTime.copyFrom(cal); assertEquals(cal.getTimeInMillis() * 1000, date.timestampMicroseconds()); @@ -35,6 +42,13 @@ public void testTimestampMicroseconds() throws Exception { @Test public void testTimestampMillis() throws Exception { + Calendar cal = Calendar.getInstance(); + DateTime date = DateTime.copyFrom(cal); + assertEquals(cal.getTimeInMillis(), date.getTimestampMillis()); + } + + @Test + public void testTimestampMillisDepreated() throws Exception { Calendar cal = Calendar.getInstance(); DateTime date = DateTime.copyFrom(cal); assertEquals(cal.getTimeInMillis(), date.timestampMillis()); @@ -59,8 +73,8 @@ public void testNow() throws Exception { Calendar cal1 = Calendar.getInstance(); DateTime now = DateTime.now(); Calendar cal2 = Calendar.getInstance(); - assertTrue(now.timestampMillis() >= cal1.getTimeInMillis()); - assertTrue(now.timestampMillis() <= cal2.getTimeInMillis()); + assertTrue(now.getTimestampMillis() >= cal1.getTimeInMillis()); + assertTrue(now.getTimestampMillis() <= cal2.getTimeInMillis()); } @Test @@ -74,4 +88,3 @@ public void testCopyFrom() throws Exception { assertNotEquals(date1, date3); } } - diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DateTimeValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DateTimeValueTest.java index 8262e97241fa..501f7c46cba8 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DateTimeValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DateTimeValueTest.java @@ -32,7 +32,6 @@ public void testToBuilder() throws Exception { assertEquals(value, value.toBuilder().build()); } - @SuppressWarnings("deprecation") @Test public void testOf() throws Exception { DateTimeValue value = DateTimeValue.of(CONTENT); @@ -43,6 +42,15 @@ public void testOf() throws Exception { @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { + DateTimeValue.Builder builder = DateTimeValue.newBuilder(CONTENT); + DateTimeValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build(); + assertEquals(CONTENT, value.get()); + assertEquals(1, value.getMeaning()); + assertTrue(value.excludeFromIndexes()); + } + + @Test + public void testBuilderDeprecated() throws Exception { DateTimeValue.Builder builder = DateTimeValue.builder(CONTENT); DateTimeValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DoubleValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DoubleValueTest.java index ecc80fd14454..d3e7f8b76e56 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DoubleValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DoubleValueTest.java @@ -43,6 +43,15 @@ public void testOf() throws Exception { @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { + DoubleValue.Builder builder = DoubleValue.newBuilder(CONTENT); + DoubleValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build(); + assertEquals(CONTENT, value.get()); + assertEquals(1, value.getMeaning()); + assertTrue(value.excludeFromIndexes()); + } + + @Test + public void testBuilderDeprecated() throws Exception { DoubleValue.Builder builder = DoubleValue.builder(CONTENT); DoubleValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/EntityTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/EntityTest.java index c3aad6f285ff..470c58243567 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/EntityTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/EntityTest.java @@ -24,35 +24,61 @@ public class EntityTest { - private static final Key KEY1 = Key.builder("ds1", "k1", "n1").build(); - private static final Key KEY2 = Key.builder("ds1", "k2", 1).build(); - private static final IncompleteKey INCOMPLETE_KEY = IncompleteKey.builder("ds1", "k2").build(); - private static final Entity ENTITY = Entity.builder(KEY1).set("foo", "bar").build(); + private static final Key KEY1 = Key.newBuilder("ds1", "k1", "n1").build(); + private static final Key KEY2 = Key.newBuilder("ds1", "k2", 1).build(); + private static final IncompleteKey INCOMPLETE_KEY = IncompleteKey.newBuilder("ds1", "k2").build(); + private static final Entity ENTITY = Entity.newBuilder(KEY1).set("foo", "bar").build(); + private static final Entity DEPRECATED_ENTITY = Entity.builder(KEY1).set("foo", "bar").build(); private static final FullEntity INCOMPLETE_ENTITY = - Entity.builder(INCOMPLETE_KEY).set("a", "b").build(); + Entity.newBuilder(INCOMPLETE_KEY).set("a", "b").build(); @Test public void testEntity() throws Exception { assertTrue(ENTITY.hasKey()); - assertEquals(KEY1, ENTITY.key()); + assertEquals(KEY1, ENTITY.getKey()); assertEquals("bar", ENTITY.getString("foo")); } + @Test + public void testEntityDeprecated() throws Exception { + assertTrue(ENTITY.hasKey()); + assertEquals(KEY1, DEPRECATED_ENTITY.key()); + assertEquals("bar", DEPRECATED_ENTITY.getString("foo")); + } + @Test public void testCopyFrom() throws Exception { + Entity.Builder builder = Entity.newBuilder(ENTITY); + assertEquals(ENTITY, builder.build()); + Entity entity = builder.setKey(KEY2).build(); + assertNotEquals(ENTITY, entity); + assertEquals(KEY2, entity.getKey()); + assertEquals(ENTITY.getProperties(), entity.getProperties()); + } + + @Test + public void testCopyFromDeprecated() throws Exception { Entity.Builder builder = Entity.builder(ENTITY); assertEquals(ENTITY, builder.build()); Entity entity = builder.key(KEY2).build(); assertNotEquals(ENTITY, entity); assertEquals(KEY2, entity.key()); - assertEquals(ENTITY.properties(), entity.properties()); + assertEquals(ENTITY.getProperties(), entity.getProperties()); } @Test public void testCopyFromIncompleteEntity() throws Exception { + Entity.Builder builder = Entity.newBuilder(KEY2, INCOMPLETE_ENTITY); + Entity entity = builder.build(); + assertNotEquals(INCOMPLETE_ENTITY, entity); + assertEquals(INCOMPLETE_ENTITY.getProperties(), entity.getProperties()); + } + + @Test + public void testCopyFromIncompleteEntityDeprecated() throws Exception { Entity.Builder builder = Entity.builder(KEY2, INCOMPLETE_ENTITY); Entity entity = builder.build(); assertNotEquals(INCOMPLETE_ENTITY, entity); - assertEquals(INCOMPLETE_ENTITY.properties(), entity.properties()); + assertEquals(INCOMPLETE_ENTITY.getProperties(), entity.getProperties()); } } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/EntityValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/EntityValueTest.java index 07fb3bb0d5cf..ca50ddefeb5e 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/EntityValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/EntityValueTest.java @@ -24,8 +24,8 @@ public class EntityValueTest { - private static final Key KEY = Key.builder("ds", "kind", 1).build(); - private static final Entity CONTENT = Entity.builder(KEY).set("FOO", "BAR").build(); + private static final Key KEY = Key.newBuilder("ds", "kind", 1).build(); + private static final Entity CONTENT = Entity.newBuilder(KEY).set("FOO", "BAR").build(); @Test public void testToBuilder() throws Exception { @@ -44,6 +44,15 @@ public void testOf() throws Exception { @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { + EntityValue.Builder builder = EntityValue.newBuilder(CONTENT); + EntityValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build(); + assertEquals(CONTENT, value.get()); + assertEquals(1, value.getMeaning()); + assertTrue(value.excludeFromIndexes()); + } + + @Test + public void testBuilderDeprecated() throws Exception { EntityValue.Builder builder = EntityValue.builder(CONTENT); EntityValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/FullEntityTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/FullEntityTest.java index c1a47212e422..c48ea5aad7fc 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/FullEntityTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/FullEntityTest.java @@ -25,29 +25,41 @@ public class FullEntityTest { - private static final Key KEY1 = Key.builder("ds1", "k1", "n1").build(); - private static final Key KEY2 = Key.builder("ds1", "k2", 1).build(); - private static final IncompleteKey INCOMPLETE_KEY = IncompleteKey.builder("ds1", "k2").build(); - private static final Entity ENTITY = Entity.builder(KEY1).set("foo", "bar").build(); + private static final Key KEY1 = Key.newBuilder("ds1", "k1", "n1").build(); + private static final Key KEY2 = Key.newBuilder("ds1", "k2", 1).build(); + private static final IncompleteKey INCOMPLETE_KEY = IncompleteKey.newBuilder("ds1", "k2").build(); + private static final Entity ENTITY = Entity.newBuilder(KEY1).set("foo", "bar").build(); private static final FullEntity COMPLETE_ENTITY1 = ENTITY; private static final FullEntity COMPLETE_ENTITY2 = - FullEntity.builder(KEY2).set("foo", "bar").build(); + FullEntity.newBuilder(KEY2).set("foo", "bar").build(); private static final FullEntity INCOMPLETE_ENTITY = - Entity.builder(INCOMPLETE_KEY).set("a", "b").build(); + Entity.newBuilder(INCOMPLETE_KEY).set("a", "b").build(); @Test public void testFullEntity() throws Exception { assertTrue(COMPLETE_ENTITY1.hasKey()); - assertEquals(KEY1, COMPLETE_ENTITY1.key()); + assertEquals(KEY1, COMPLETE_ENTITY1.getKey()); assertEquals("bar", COMPLETE_ENTITY1.getString("foo")); assertTrue(COMPLETE_ENTITY2.hasKey()); - assertEquals(KEY2, COMPLETE_ENTITY2.key()); + assertEquals(KEY2, COMPLETE_ENTITY2.getKey()); assertEquals("bar", COMPLETE_ENTITY2.getString("foo")); } @Test public void testNoKey() throws Exception { + FullEntity entity = FullEntity.newBuilder().set("foo", "bar").build(); + assertFalse(entity.hasKey()); + assertNull(entity.getKey()); + assertEquals("bar", entity.getString("foo")); + + entity = FullEntity.newBuilder((IncompleteKey) null).build(); + assertFalse(entity.hasKey()); + assertNull(entity.getKey()); + } + + @Test + public void testNoKeyDeprecated() throws Exception { FullEntity entity = FullEntity.builder().set("foo", "bar").build(); assertFalse(entity.hasKey()); assertNull(entity.key()); @@ -60,6 +72,18 @@ public void testNoKey() throws Exception { @Test public void testCopyFrom() throws Exception { + FullEntity.Builder builder1 = FullEntity.newBuilder(ENTITY); + assertEquals(ENTITY, builder1.build()); + + builder1 = FullEntity.newBuilder(COMPLETE_ENTITY1); + assertEquals(COMPLETE_ENTITY1, builder1.build()); + + FullEntity.Builder builder2 = FullEntity.newBuilder(INCOMPLETE_ENTITY); + assertEquals(INCOMPLETE_ENTITY, builder2.build()); + } + + @Test + public void testCopyFromDeprected() throws Exception { FullEntity.Builder builder1 = FullEntity.builder(ENTITY); assertEquals(ENTITY, builder1.build()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/IncompleteKeyTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/IncompleteKeyTest.java index f4562901d5c6..bb5531106603 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/IncompleteKeyTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/IncompleteKeyTest.java @@ -26,38 +26,67 @@ public class IncompleteKeyTest { private static IncompleteKey pk1, pk2; + private static IncompleteKey deprecatedPk1, deprecatedPk2; private static Key parent1; @Before public void setUp() { - pk1 = IncompleteKey.builder("ds", "kind1").build(); - parent1 = Key.builder("ds", "kind2", 10).namespace("ns").build(); - pk2 = IncompleteKey.builder(parent1, "kind3").build(); + pk1 = IncompleteKey.newBuilder("ds", "kind1").build(); + parent1 = Key.newBuilder("ds", "kind2", 10).setNamespace("ns").build(); + pk2 = IncompleteKey.newBuilder(parent1, "kind3").build(); + deprecatedPk1 = IncompleteKey.builder("ds", "kind1").build(); + deprecatedPk2 = IncompleteKey.builder(parent1, "kind3").build(); } @Test public void testBuilders() throws Exception { - assertEquals("ds", pk1.projectId()); - assertEquals("kind1", pk1.kind()); - assertTrue(pk1.ancestors().isEmpty()); - - assertEquals("ds", pk2.projectId()); - assertEquals("kind3", pk2.kind()); - assertEquals(parent1.path(), pk2.ancestors()); - - assertEquals(pk2, IncompleteKey.builder(pk2).build()); - IncompleteKey pk3 = IncompleteKey.builder(pk2).kind("kind4").build(); - assertEquals("ds", pk3.projectId()); - assertEquals("kind4", pk3.kind()); - assertEquals(parent1.path(), pk3.ancestors()); + assertEquals("ds", pk1.getProjectId()); + assertEquals("kind1", pk1.getKind()); + assertTrue(pk1.getAncestors().isEmpty()); + + assertEquals("ds", pk2.getProjectId()); + assertEquals("kind3", pk2.getKind()); + assertEquals(parent1.getPath(), pk2.getAncestors()); + + assertEquals(pk2, IncompleteKey.newBuilder(pk2).build()); + IncompleteKey pk3 = IncompleteKey.newBuilder(pk2).setKind("kind4").build(); + assertEquals("ds", pk3.getProjectId()); + assertEquals("kind4", pk3.getKind()); + assertEquals(parent1.getPath(), pk3.getAncestors()); + } + + @Test + public void testBuildersDeprecated() throws Exception { + assertEquals("ds", deprecatedPk1.projectId()); + assertEquals("kind1", deprecatedPk1.kind()); + assertTrue(deprecatedPk1.ancestors().isEmpty()); + + assertEquals("ds", deprecatedPk2.projectId()); + assertEquals("kind3", deprecatedPk2.kind()); + assertEquals(parent1.path(), deprecatedPk2.ancestors()); + + assertEquals(deprecatedPk2, IncompleteKey.builder(deprecatedPk2).build()); + IncompleteKey deprecatedPk3 = IncompleteKey.builder(deprecatedPk2).kind("kind4").build(); + assertEquals("ds", deprecatedPk3.projectId()); + assertEquals("kind4", deprecatedPk3.kind()); + assertEquals(parent1.path(), deprecatedPk3.ancestors()); } @Test public void testParent() { - assertNull(pk1.parent()); - assertEquals(parent1, pk2.parent()); - Key parent2 = Key.builder("ds", "kind3", "name").namespace("ns").build(); - IncompleteKey pk3 = IncompleteKey.builder(parent2, "kind3").build(); - assertEquals(parent2, pk3.parent()); + assertNull(pk1.getParent()); + assertEquals(parent1, pk2.getParent()); + Key parent2 = Key.newBuilder("ds", "kind3", "name").setNamespace("ns").build(); + IncompleteKey pk3 = IncompleteKey.newBuilder(parent2, "kind3").build(); + assertEquals(parent2, pk3.getParent()); + } + + @Test + public void testParentDeprecated() { + assertNull(deprecatedPk1.parent()); + assertEquals(parent1, deprecatedPk2.parent()); + Key parent2 = Key.newBuilder("ds", "kind3", "name").setName("ns").build(); + IncompleteKey deprecatedPk3 = IncompleteKey.builder(parent2, "kind3").build(); + assertEquals(parent2, deprecatedPk3.parent()); } } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/KeyFactoryTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/KeyFactoryTest.java index 93f08de11be8..45aec369d9b3 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/KeyFactoryTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/KeyFactoryTest.java @@ -29,43 +29,87 @@ public class KeyFactoryTest { private static final String PROJECT_ID = "projectid"; private KeyFactory keyFactory; + private KeyFactory deprecatedKeyFactory; @Before public void setUp() { - keyFactory = new KeyFactory(PROJECT_ID).kind("k"); + keyFactory = new KeyFactory(PROJECT_ID).setKind("k"); + deprecatedKeyFactory = new KeyFactory(PROJECT_ID).kind("k"); } @Test public void testReset() { - IncompleteKey key = - keyFactory.projectId("ds1").namespace("ns1").ancestors(PathElement.of("p", 1)).build(); + IncompleteKey key = keyFactory + .setProjectId("ds1") + .setNamespace("ns1") + .addAncestor(PathElement.of("p", 1)) + .build(); + assertEquals("k", key.getKind()); + assertEquals("ds1", key.getProjectId()); + assertEquals("ns1", key.getNamespace()); + assertEquals(1, key.getAncestors().size()); + + keyFactory.reset(); + try { + keyFactory.newKey(1); + } catch (NullPointerException ex) { + assertEquals("kind must not be null", ex.getMessage()); + } + keyFactory.setKind("k1"); + key = keyFactory.newKey(); + assertEquals("k1", key.getKind()); + assertEquals(PROJECT_ID, key.getProjectId()); + assertTrue(key.getNamespace().isEmpty()); + assertTrue(key.getAncestors().isEmpty()); + + keyFactory = new KeyFactory(PROJECT_ID, "ns1").setKind("k"); + key = keyFactory.newKey(); + assertEquals(PROJECT_ID, key.getProjectId()); + assertEquals("ns1", key.getNamespace()); + key = keyFactory.setProjectId("bla1").setNamespace("bla2").build(); + assertEquals("bla1", key.getProjectId()); + assertEquals("bla2", key.getNamespace()); + keyFactory.reset().setKind("kind"); + key = keyFactory.newKey(); + assertEquals(PROJECT_ID, key.getProjectId()); + assertEquals("ns1", key.getNamespace()); + assertEquals("kind", key.getKind()); + } + + @Test + public void testResetDeprecated() { + IncompleteKey key = deprecatedKeyFactory + .projectId("ds1") + .namespace("ns1") + .ancestors(PathElement.of("p", 1)) + .build(); assertEquals("k", key.kind()); assertEquals("ds1", key.projectId()); assertEquals("ns1", key.namespace()); assertEquals(1, key.ancestors().size()); - keyFactory.reset(); + deprecatedKeyFactory.reset(); try { - keyFactory.newKey(1); + deprecatedKeyFactory.newKey(1); } catch (NullPointerException ex) { assertEquals("kind must not be null", ex.getMessage()); } - keyFactory.kind("k1"); - key = keyFactory.newKey(); + deprecatedKeyFactory.kind("k1"); + key = deprecatedKeyFactory.newKey(); assertEquals("k1", key.kind()); assertEquals(PROJECT_ID, key.projectId()); assertTrue(key.namespace().isEmpty()); assertTrue(key.ancestors().isEmpty()); - keyFactory = new KeyFactory(PROJECT_ID, "ns1").kind("k"); - key = keyFactory.newKey(); + deprecatedKeyFactory = new KeyFactory(PROJECT_ID, "ns1").kind("k"); + key = deprecatedKeyFactory.newKey(); assertEquals(PROJECT_ID, key.projectId()); assertEquals("ns1", key.namespace()); - key = keyFactory.projectId("bla1").namespace("bla2").build(); + key = deprecatedKeyFactory.projectId("bla1").namespace("bla2").build(); assertEquals("bla1", key.projectId()); assertEquals("bla2", key.namespace()); - keyFactory.reset().kind("kind"); - key = keyFactory.newKey(); + deprecatedKeyFactory.reset().kind("kind"); + key = deprecatedKeyFactory.newKey(); assertEquals(PROJECT_ID, key.projectId()); assertEquals("ns1", key.namespace()); assertEquals("kind", key.kind()); @@ -79,7 +123,19 @@ public void testNewKey() throws Exception { verifyKey(key, "n", ""); PathElement p1 = PathElement.of("k1", "n"); PathElement p2 = PathElement.of("k2", 10); - key = keyFactory.namespace("ns").ancestors(p1, p2).newKey("k3"); + key = keyFactory.setNamespace("ns").addAncestors(p1, p2).newKey("k3"); + verifyKey(key, "k3", "ns", p1, p2); + } + + @Test + public void testNewKeyDeprecated() throws Exception { + Key key = keyFactory.newKey(1); + verifyKey(key, 1L, ""); + key = deprecatedKeyFactory.newKey("n"); + verifyKey(key, "n", ""); + PathElement p1 = PathElement.of("k1", "n"); + PathElement p2 = PathElement.of("k2", 10); + key = deprecatedKeyFactory.namespace("ns").ancestors(p1, p2).newKey("k3"); verifyKey(key, "k3", "ns", p1, p2); } @@ -89,7 +145,17 @@ public void testNewIncompleteKey() throws Exception { verifyIncompleteKey(key, ""); PathElement p1 = PathElement.of("k1", "n"); PathElement p2 = PathElement.of("k2", 10); - key = keyFactory.namespace("ns").ancestors(p1, p2).newKey(); + key = keyFactory.setNamespace("ns").addAncestors(p1, p2).newKey(); + verifyIncompleteKey(key, "ns", p1, p2); + } + + @Test + public void testNewIncompleteKeyDeprecated() throws Exception { + IncompleteKey key = deprecatedKeyFactory.newKey(); + verifyIncompleteKey(key, ""); + PathElement p1 = PathElement.of("k1", "n"); + PathElement p2 = PathElement.of("k2", 10); + key = deprecatedKeyFactory.namespace("ns").ancestors(p1, p2).newKey(); verifyIncompleteKey(key, "ns", p1, p2); } @@ -99,21 +165,21 @@ public void testNewIncompleteWithNoKind() { } private void verifyKey(Key key, String name, String namespace, PathElement... ancestors) { - assertEquals(name, key.name()); + assertEquals(name, key.getName()); verifyIncompleteKey(key, namespace, ancestors); } private void verifyKey(Key key, Long id, String namespace, PathElement... ancestors) { - assertEquals(id, key.id()); + assertEquals(id, key.getId()); verifyIncompleteKey(key, namespace, ancestors); } private void verifyIncompleteKey(IncompleteKey key, String namespace, PathElement... ancestors) { - assertEquals("k", key.kind()); - assertEquals(PROJECT_ID, key.projectId()); - assertEquals(namespace, key.namespace()); - assertEquals(ancestors.length, key.ancestors().size()); - Iterator iter = key.ancestors().iterator(); + assertEquals("k", key.getKind()); + assertEquals(PROJECT_ID, key.getProjectId()); + assertEquals(namespace, key.getNamespace()); + assertEquals(ancestors.length, key.getAncestors().size()); + Iterator iter = key.getAncestors().iterator(); for (PathElement ancestor : ancestors) { assertEquals(ancestor, iter.next()); } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/KeyTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/KeyTest.java index 398ea22d01e4..aaa50130da0c 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/KeyTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/KeyTest.java @@ -26,6 +26,15 @@ public class KeyTest { @Test public void testHasId() throws Exception { + Key.Builder builder = Key.newBuilder("d", "k", 10); + Key key = builder.build(); + assertTrue(key.hasId()); + key = builder.setName("bla").build(); + assertFalse(key.hasId()); + } + + @Test + public void testHasIdDeprecated() throws Exception { Key.Builder builder = Key.builder("d", "k", 10); Key key = builder.build(); assertTrue(key.hasId()); @@ -35,6 +44,15 @@ public void testHasId() throws Exception { @Test public void testId() throws Exception { + Key.Builder builder = Key.newBuilder("d", "k", 10); + Key key = builder.build(); + assertEquals(Long.valueOf(10), key.getId()); + key = builder.setId(100).build(); + assertEquals(Long.valueOf(100), key.getId()); + } + + @Test + public void testIdDeprecated() throws Exception { Key.Builder builder = Key.builder("d", "k", 10); Key key = builder.build(); assertEquals(Long.valueOf(10), key.id()); @@ -44,6 +62,15 @@ public void testId() throws Exception { @Test public void testHasName() throws Exception { + Key.Builder builder = Key.newBuilder("d", "k", "n"); + Key key = builder.build(); + assertTrue(key.hasName()); + key = builder.setId(1).build(); + assertFalse(key.hasName()); + } + + @Test + public void testHasNameDeprecated() throws Exception { Key.Builder builder = Key.builder("d", "k", "n"); Key key = builder.build(); assertTrue(key.hasName()); @@ -53,6 +80,15 @@ public void testHasName() throws Exception { @Test public void testName() throws Exception { + Key.Builder builder = Key.newBuilder("d", "k", "n"); + Key key = builder.build(); + assertEquals("n", key.getName()); + key = builder.setName("o").build(); + assertEquals("o", key.getName()); + } + + @Test + public void testNameDeprecated() throws Exception { Key.Builder builder = Key.builder("d", "k", "n"); Key key = builder.build(); assertEquals("n", key.name()); @@ -62,6 +98,15 @@ public void testName() throws Exception { @Test public void testNameOrId() throws Exception { + Key.Builder builder = Key.newBuilder("d", "k", "n"); + Key key = builder.build(); + assertEquals("n", key.getNameOrId()); + key = builder.setId(1).build(); + assertEquals(Long.valueOf(1), key.getNameOrId()); + } + + @Test + public void testNameOrIdDeprecated() throws Exception { Key.Builder builder = Key.builder("d", "k", "n"); Key key = builder.build(); assertEquals("n", key.nameOrId()); @@ -71,7 +116,7 @@ public void testNameOrId() throws Exception { @Test public void testToAndFromUrlSafe() throws Exception { - Key key = Key.builder("d", "k", "n").build(); + Key key = Key.newBuilder("d", "k", "n").build(); String urlSafe = key.toUrlSafe(); Key copy = Key.fromUrlSafe(urlSafe); assertEquals(key, copy); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/KeyValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/KeyValueTest.java index 0d2670b48c88..3f7d5d4a5af9 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/KeyValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/KeyValueTest.java @@ -24,7 +24,7 @@ public class KeyValueTest { - private static final Key CONTENT = Key.builder("ds", "kind", 1).build(); + private static final Key CONTENT = Key.newBuilder("ds", "kind", 1).build(); @Test public void testToBuilder() throws Exception { @@ -43,7 +43,16 @@ public void testOf() throws Exception { @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { - KeyValue.Builder builder = KeyValue.builder(CONTENT); + KeyValue.Builder builder = KeyValue.newBuilder(CONTENT); + KeyValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build(); + assertEquals(CONTENT, value.get()); + assertEquals(1, value.getMeaning()); + assertTrue(value.excludeFromIndexes()); + } + + @Test + public void testBuilderDeprecated() throws Exception { + KeyValue.Builder builder = KeyValue.newBuilder(CONTENT); KeyValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); assertEquals(1, value.meaning()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/LatLngTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/LatLngTest.java index 401d8cc0c4c8..f693808263c3 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/LatLngTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/LatLngTest.java @@ -36,6 +36,18 @@ public class LatLngTest { private static final String INVALID_LNG_MESSAGE = "latitude must be in the range [-180, 180] degrees"; + @Test + public void testLatLng() { + assertEquals(37.422035, gp1.getLatitude(), 0); + assertEquals(-122.084124, gp1.getLongitude(), 0); + } + + @Test + public void testLatLngDeprecated() { + assertEquals(37.422035, gp1.latitude(), 0); + assertEquals(-122.084124, gp1.longitude(), 0); + } + @Test public void testEquals() { assertEquals(gp1, gp1); @@ -74,4 +86,3 @@ public void testLowerLngRange() { new LatLng(0, -181); } } - diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/LatLngValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/LatLngValueTest.java index 583f89ef6cfe..ae3c36b50ad4 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/LatLngValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/LatLngValueTest.java @@ -43,6 +43,15 @@ public void testOf() throws Exception { @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { + LatLngValue.Builder builder = LatLngValue.newBuilder(CONTENT); + LatLngValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build(); + assertEquals(CONTENT, value.get()); + assertEquals(1, value.getMeaning()); + assertTrue(value.excludeFromIndexes()); + } + + @Test + public void testBuilderDeprecated() throws Exception { LatLngValue.Builder builder = LatLngValue.builder(CONTENT); LatLngValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/ListValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/ListValueTest.java index 567f2778dc38..d4d3a0ed8015 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/ListValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/ListValueTest.java @@ -43,10 +43,10 @@ public class ListValueTest { private static final DateTime DATETIME2 = new DateTime(2); private static final LatLng LATLNG1 = LatLng.of(DOUBLE1, DOUBLE2); private static final LatLng LATLNG2 = LatLng.of(DOUBLE2, DOUBLE1); - private static final Key KEY1 = Key.builder("project", "kind", "name1").build(); - private static final Key KEY2 = Key.builder("project", "kind", "name2").build(); - private static final FullEntity ENTITY1 = FullEntity.builder(KEY1).build(); - private static final FullEntity ENTITY2 = FullEntity.builder(KEY2).build(); + private static final Key KEY1 = Key.newBuilder("project", "kind", "name1").build(); + private static final Key KEY2 = Key.newBuilder("project", "kind", "name2").build(); + private static final FullEntity ENTITY1 = FullEntity.newBuilder(KEY1).build(); + private static final FullEntity ENTITY2 = FullEntity.newBuilder(KEY2).build(); private static final Blob BLOB1 = Blob.copyFrom(new byte[]{0xD, 0xE, 0xA, 0xD}); private static final Blob BLOB2 = Blob.copyFrom(new byte[]{0xB, 0x0, 0x0, 0x0}); @@ -107,13 +107,13 @@ public void testOf() throws Exception { @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { - ListValue.Builder builder = ListValue.builder().set(CONTENT); - ListValue value = builder.meaning(1).excludeFromIndexes(true).build(); + ListValue.Builder builder = ListValue.newBuilder().set(CONTENT); + ListValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); - assertEquals(1, value.meaning()); + assertEquals(1, value.getMeaning()); assertTrue(value.excludeFromIndexes()); - builder = ListValue.builder(); + builder = ListValue.newBuilder(); for (Value v : CONTENT) { builder.addValue(v); } @@ -199,4 +199,19 @@ public void testBuilder() throws Exception { builder = builder.addValue(BLOB1, BLOB2); assertEquals(ImmutableList.of(BlobValue.of(BLOB1), BlobValue.of(BLOB2)), builder.build().get()); } + + @Test + public void testBuilderDeprecated() throws Exception { + ListValue.Builder builder = ListValue.builder().set(CONTENT); + ListValue value = builder.meaning(1).excludeFromIndexes(true).build(); + assertEquals(CONTENT, value.get()); + assertEquals(1, value.meaning()); + assertTrue(value.excludeFromIndexes()); + + builder = ListValue.builder(); + for (Value v : CONTENT) { + builder.addValue(v); + } + assertEquals(CONTENT, builder.build().get()); + } } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/LongValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/LongValueTest.java index 135f5fb8ac6a..5765cf5f4182 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/LongValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/LongValueTest.java @@ -43,6 +43,15 @@ public void testOf() throws Exception { @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { + LongValue.Builder builder = LongValue.newBuilder(CONTENT); + LongValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build(); + assertEquals(CONTENT, value.get()); + assertEquals(1, value.getMeaning()); + assertTrue(value.excludeFromIndexes()); + } + + @Test + public void testBuilderDeprecated() throws Exception { LongValue.Builder builder = LongValue.builder(CONTENT); LongValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/NullValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/NullValueTest.java index ffed6e69c4f5..e49c8e429735 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/NullValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/NullValueTest.java @@ -41,6 +41,15 @@ public void testOf() throws Exception { @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { + NullValue.Builder builder = NullValue.newBuilder(); + NullValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build(); + assertNull(value.get()); + assertEquals(1, value.getMeaning()); + assertTrue(value.excludeFromIndexes()); + } + + @Test + public void testBuilderDeprecated() throws Exception { NullValue.Builder builder = NullValue.builder(); NullValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertNull(value.get()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/PathElementTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/PathElementTest.java index 269dddb51d71..3d69c10d8048 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/PathElementTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/PathElementTest.java @@ -31,6 +31,13 @@ public class PathElementTest { @Test public void testKind() throws Exception { + assertEquals("k1", PE_1.getKind()); + assertEquals("k2", PE_2.getKind()); + assertEquals("k3", PE_3.getKind()); + } + + @Test + public void testKindDeprected() throws Exception { assertEquals("k1", PE_1.kind()); assertEquals("k2", PE_2.kind()); assertEquals("k3", PE_3.kind()); @@ -45,6 +52,13 @@ public void testHasId() throws Exception { @Test public void testId() throws Exception { + assertNull(PE_1.getId()); + assertNull(PE_2.getId()); + assertEquals(Long.valueOf(1), PE_3.getId()); + } + + @Test + public void testIdDeprecated() throws Exception { assertNull(PE_1.id()); assertNull(PE_2.id()); assertEquals(Long.valueOf(1), PE_3.id()); @@ -59,6 +73,13 @@ public void testHasName() throws Exception { @Test public void testName() throws Exception { + assertNull(PE_1.getName()); + assertEquals("n", PE_2.getName()); + assertNull(PE_3.getName()); + } + + @Test + public void testNameDeprecated() throws Exception { assertNull(PE_1.name()); assertEquals("n", PE_2.name()); assertNull(PE_3.name()); @@ -66,6 +87,13 @@ public void testName() throws Exception { @Test public void testNameOrId() throws Exception { + assertNull(PE_1.getNameOrId()); + assertEquals("n", PE_2.getNameOrId()); + assertEquals(Long.valueOf(1), PE_3.getNameOrId()); + } + + @Test + public void testNameOrIdDeprecated() throws Exception { assertNull(PE_1.nameOrId()); assertEquals("n", PE_2.nameOrId()); assertEquals(Long.valueOf(1), PE_3.nameOrId()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/ProjectionEntityTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/ProjectionEntityTest.java index 2b53e6efc04c..d666921298e7 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/ProjectionEntityTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/ProjectionEntityTest.java @@ -26,15 +26,15 @@ public class ProjectionEntityTest { - private static final Key KEY = Key.builder("ds1", "k1", "n1").build(); + private static final Key KEY = Key.newBuilder("ds1", "k1", "n1").build(); private static final StringValue STRING_INDEX_VALUE = - StringValue.builder("foo").meaning(18).build(); + StringValue.newBuilder("foo").setMeaning(18).build(); private static final BlobValue BLOB_VALUE = BlobValue.of(Blob.copyFrom(new byte[]{1})); private static final DateTimeValue DATE_TIME_VALUE = DateTimeValue.of(DateTime.now()); private static final LongValue LONG_INDEX_VALUE = - LongValue.builder(DATE_TIME_VALUE.get().timestampMicroseconds()).meaning(18).build(); + LongValue.newBuilder(DATE_TIME_VALUE.get().getTimestampMicroseconds()).setMeaning(18).build(); private static final ProjectionEntity ENTITY1 = - new ProjectionEntity.Builder().key(KEY).set("a", "b").build(); + new ProjectionEntity.Builder().setKey(KEY).set("a", "b").build(); private static final ProjectionEntity ENTITY2 = new ProjectionEntity.Builder() .set("a", STRING_INDEX_VALUE) .set("b", BLOB_VALUE) @@ -50,8 +50,8 @@ public void testHasKey() throws Exception { @Test public void testKey() throws Exception { - assertEquals(KEY, ENTITY1.key()); - assertNull(ENTITY2.key()); + assertEquals(KEY, ENTITY1.getKey()); + assertNull(ENTITY2.getKey()); } @Test diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/RawValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/RawValueTest.java index 4c82b6d888e0..5b4f57ba21c6 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/RawValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/RawValueTest.java @@ -42,10 +42,10 @@ public void testOf() throws Exception { @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { - RawValue.Builder builder = RawValue.builder(CONTENT); - RawValue value = builder.meaning(1).excludeFromIndexes(true).build(); + RawValue.Builder builder = RawValue.newBuilder(CONTENT); + RawValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); - assertEquals(1, value.meaning()); + assertEquals(1, value.getMeaning()); assertTrue(value.excludeFromIndexes()); } } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java index 07f94255c985..505043a4ffbb 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java @@ -28,50 +28,51 @@ public class SerializationTest extends BaseSerializationTest { private static final IncompleteKey INCOMPLETE_KEY1 = - IncompleteKey.builder("ds", "k").ancestors(PathElement.of("p", 1)).build(); - private static final Key KEY1 = Key.builder("ds", "k", "n").build(); + IncompleteKey.newBuilder("ds", "k").addAncestor(PathElement.of("p", 1)).build(); + private static final Key KEY1 = Key.newBuilder("ds", "k", "n").build(); private static final IncompleteKey INCOMPLETE_KEY2 = - IncompleteKey.builder(KEY1, "v").ancestors(PathElement.of("p", 1)).build(); - private static final Key KEY2 = Key.builder(KEY1, "v", 2).build(); + IncompleteKey.newBuilder(KEY1, "v").addAncestor(PathElement.of("p", 1)).build(); + private static final Key KEY2 = Key.newBuilder(KEY1, "v", 2).build(); private static final DateTime DATE_TIME1 = DateTime.now(); private static final LatLng LAT_LNG = new LatLng(37.422035, -122.084124); private static final Blob BLOB1 = Blob.copyFrom(UTF_8.encode("hello world")); private static final Cursor CURSOR1 = Cursor.copyFrom(new byte[] {1, 2}); private static final Cursor CURSOR2 = Cursor.copyFrom(new byte[] {10}); private static final Query GQL1 = - Query.gqlQueryBuilder("select * from kind1 where name = @name and age > @1") + Query.newGqlQueryBuilder("select * from kind1 where name = @name and age > @1") .setBinding("name", "name1") .addBinding(20) - .namespace("ns1") + .setNamespace("ns1") .build(); private static final Query GQL2 = - Query.gqlQueryBuilder( + Query.newGqlQueryBuilder( Query.ResultType.ENTITY, "select * from kind1 where name = @name and age > @1") .setBinding("name", "name1") .addBinding(20) - .namespace("ns1") + .setNamespace("ns1") .build(); private static final Query QUERY1 = - Query.entityQueryBuilder().kind("kind1").build(); - private static final Query QUERY2 = Query.keyQueryBuilder() - .kind("k") - .filter(PropertyFilter.eq("p1", "hello")) + Query.newEntityQueryBuilder().setKind("kind1").build(); + private static final Query QUERY2 = Query.newKeyQueryBuilder() + .setKind("k") + .setFilter(PropertyFilter.eq("p1", "hello")) .build(); private static final Query QUERY3 = - Query.projectionEntityQueryBuilder() - .kind("k") - .namespace("ns1") - .projection("p") - .limit(100) - .offset(5) - .startCursor(CURSOR1) - .endCursor(CURSOR2) - .filter(CompositeFilter.and(PropertyFilter.gt("p1", 10), PropertyFilter.eq("a", "v"))) + Query.newProjectionEntityQueryBuilder() + .setKind("k") + .setNamespace("ns1") + .addProjection("p") + .setLimit(100) + .setOffset(5) + .setStartCursor(CURSOR1) + .setEndCursor(CURSOR2) + .setFilter(CompositeFilter.and(PropertyFilter.gt("p1", 10), PropertyFilter.eq("a", "v"))) .addDistinctOn("p") .addOrderBy(OrderBy.asc("p")) .build(); private static final KeyValue KEY_VALUE = KeyValue.of(KEY1); - private static final NullValue NULL_VALUE = NullValue.builder().excludeFromIndexes(true).build(); + private static final NullValue NULL_VALUE = + NullValue.newBuilder().setExcludeFromIndexes(true).build(); private static final StringValue STRING_VALUE = StringValue.of("hello"); private static final LongValue LONG_VALUE = LongValue.of(123); private static final DoubleValue DOUBLE_VALUE = DoubleValue.of(12.34); @@ -81,23 +82,24 @@ public class SerializationTest extends BaseSerializationTest { private static final RawValue RAW_VALUE = RawValue.of(com.google.datastore.v1.Value.newBuilder().setMeaning(18).build()); private static final LatLngValue LAT_LNG_VALUE = LatLngValue.of(LAT_LNG); - private static final Entity ENTITY1 = Entity.builder(KEY1).build(); + private static final Entity ENTITY1 = Entity.newBuilder(KEY1).build(); private static final Entity ENTITY2 = - Entity.builder(KEY2).set("null", NullValue.of()).build(); - private static final Entity ENTITY3 = Entity.builder(KEY2) - .set("p1", StringValue.builder("hi1").meaning(10).build()) - .set("p2", StringValue.builder("hi2").meaning(11).excludeFromIndexes(true).build()) - .set("p3", LongValue.builder(100).excludeFromIndexes(true).meaning(100).build()) + Entity.newBuilder(KEY2).set("null", NullValue.of()).build(); + private static final Entity ENTITY3 = Entity.newBuilder(KEY2) + .set("p1", StringValue.newBuilder("hi1").setMeaning(10).build()) + .set("p2", StringValue.newBuilder("hi2").setMeaning(11).setExcludeFromIndexes(true).build()) + .set("p3", LongValue.newBuilder(100).setExcludeFromIndexes(true).setMeaning(100).build()) .set("blob", BLOB1) .build(); - private static final FullEntity EMBEDDED_ENTITY = Entity.builder(INCOMPLETE_KEY1) - .set("p1", STRING_VALUE) - .set("p2", LongValue.builder(100).excludeFromIndexes(true).meaning(100).build()) - .build(); + private static final FullEntity EMBEDDED_ENTITY = + Entity.newBuilder(INCOMPLETE_KEY1) + .set("p1", STRING_VALUE) + .set("p2", LongValue.newBuilder(100).setExcludeFromIndexes(true).setMeaning(100).build()) + .build(); private static final EntityValue EMBEDDED_ENTITY_VALUE1 = EntityValue.of(ENTITY1); private static final EntityValue EMBEDDED_ENTITY_VALUE2 = EntityValue.of(ENTITY2); private static final EntityValue EMBEDDED_ENTITY_VALUE3 = EntityValue.of(EMBEDDED_ENTITY); - private static final ListValue LIST_VALUE = ListValue.builder() + private static final ListValue LIST_VALUE = ListValue.newBuilder() .addValue(NULL_VALUE) .addValue(STRING_VALUE) .addValue(new NullValue()) diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/StringValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/StringValueTest.java index 8dab36015515..ee26ea0103b7 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/StringValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/StringValueTest.java @@ -42,6 +42,15 @@ public void testOf() throws Exception { @SuppressWarnings("deprecation") @Test public void testBuilder() throws Exception { + StringValue.Builder builder = StringValue.newBuilder(CONTENT); + StringValue value = builder.setMeaning(1).setExcludeFromIndexes(true).build(); + assertEquals(CONTENT, value.get()); + assertEquals(1, value.getMeaning()); + assertTrue(value.excludeFromIndexes()); + } + + @Test + public void testBuilderDeprecated() throws Exception { StringValue.Builder builder = StringValue.builder(CONTENT); StringValue value = builder.meaning(1).excludeFromIndexes(true).build(); assertEquals(CONTENT, value.get()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/StructuredQueryTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/StructuredQueryTest.java index cc2ec78e06a1..a19423b0709b 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/StructuredQueryTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/StructuredQueryTest.java @@ -50,7 +50,40 @@ public class StructuredQueryTest { private static final String DISTINCT_ON1 = "p6"; private static final String DISTINCT_ON2 = "p7"; private static final List DISTINCT_ON = ImmutableList.of(DISTINCT_ON1, DISTINCT_ON2); - private static final EntityQuery ENTITY_QUERY = Query.entityQueryBuilder() + private static final EntityQuery ENTITY_QUERY = Query.newEntityQueryBuilder() + .setNamespace(NAMESPACE) + .setKind(KIND) + .setStartCursor(START_CURSOR) + .setEndCursor(END_CURSOR) + .setOffset(OFFSET) + .setLimit(LIMIT) + .setFilter(FILTER) + .setOrderBy(ORDER_BY_1, ORDER_BY_2) + .build(); + private static final KeyQuery KEY_QUERY = Query.newKeyQueryBuilder() + .setNamespace(NAMESPACE) + .setKind(KIND) + .setStartCursor(START_CURSOR) + .setEndCursor(END_CURSOR) + .setOffset(OFFSET) + .setLimit(LIMIT) + .setFilter(FILTER) + .setOrderBy(ORDER_BY_1, ORDER_BY_2) + .build(); + private static final ProjectionEntityQuery PROJECTION_QUERY = + Query.newProjectionEntityQueryBuilder() + .setNamespace(NAMESPACE) + .setKind(KIND) + .setStartCursor(START_CURSOR) + .setEndCursor(END_CURSOR) + .setOffset(OFFSET) + .setLimit(LIMIT) + .setFilter(FILTER) + .setOrderBy(ORDER_BY_1, ORDER_BY_2) + .setProjection(PROJECTION1, PROJECTION2) + .setDistinctOn(DISTINCT_ON1, DISTINCT_ON2) + .build(); + private static final EntityQuery DEPRECATED_ENTITY_QUERY = Query.entityQueryBuilder() .namespace(NAMESPACE) .kind(KIND) .startCursor(START_CURSOR) @@ -60,7 +93,7 @@ public class StructuredQueryTest { .filter(FILTER) .orderBy(ORDER_BY_1, ORDER_BY_2) .build(); - private static final KeyQuery KEY_QUERY = Query.keyQueryBuilder() + private static final KeyQuery DEPRECATED_KEY_QUERY = Query.keyQueryBuilder() .namespace(NAMESPACE) .kind(KIND) .startCursor(START_CURSOR) @@ -70,7 +103,7 @@ public class StructuredQueryTest { .filter(FILTER) .orderBy(ORDER_BY_1, ORDER_BY_2) .build(); - private static final ProjectionEntityQuery PROJECTION_QUERY = + private static final ProjectionEntityQuery DEPRECATED_PROJECTION_QUERY = Query.projectionEntityQueryBuilder() .namespace(NAMESPACE) .kind(KIND) @@ -87,25 +120,58 @@ public class StructuredQueryTest { @Test public void testEntityQueryBuilder() { compareBaseBuilderFields(ENTITY_QUERY); - assertTrue(ENTITY_QUERY.projection().isEmpty()); - assertTrue(ENTITY_QUERY.distinctOn().isEmpty()); + assertTrue(ENTITY_QUERY.getProjection().isEmpty()); + assertTrue(ENTITY_QUERY.getDistinctOn().isEmpty()); + } + + @Test + public void testEntityQueryBuilderDeprecated() { + compareBaseBuilderFieldsDeprecated(ENTITY_QUERY); + assertTrue(DEPRECATED_ENTITY_QUERY.projection().isEmpty()); + assertTrue(DEPRECATED_ENTITY_QUERY.distinctOn().isEmpty()); } @Test public void testKeyQueryBuilder() { compareBaseBuilderFields(KEY_QUERY); - assertEquals(ImmutableList.of(StructuredQuery.KEY_PROPERTY_NAME), KEY_QUERY.projection()); - assertTrue(KEY_QUERY.distinctOn().isEmpty()); + assertEquals(ImmutableList.of(StructuredQuery.KEY_PROPERTY_NAME), KEY_QUERY.getProjection()); + assertTrue(KEY_QUERY.getDistinctOn().isEmpty()); + } + + @Test + public void testKeyQueryBuilderDeprecated() { + compareBaseBuilderFieldsDeprecated(DEPRECATED_KEY_QUERY); + assertEquals(ImmutableList.of(StructuredQuery.KEY_PROPERTY_NAME), + DEPRECATED_KEY_QUERY.projection()); + assertTrue(DEPRECATED_KEY_QUERY.distinctOn().isEmpty()); } @Test public void testProjectionEntityQueryBuilder() { compareBaseBuilderFields(PROJECTION_QUERY); - assertEquals(PROJECTION, PROJECTION_QUERY.projection()); - assertEquals(DISTINCT_ON, PROJECTION_QUERY.distinctOn()); + assertEquals(PROJECTION, PROJECTION_QUERY.getProjection()); + assertEquals(DISTINCT_ON, PROJECTION_QUERY.getDistinctOn()); + } + + @Test + public void testProjectionEntityQueryBuilderDeprecated() { + compareBaseBuilderFieldsDeprecated(DEPRECATED_PROJECTION_QUERY); + assertEquals(PROJECTION, DEPRECATED_PROJECTION_QUERY.projection()); + assertEquals(DISTINCT_ON, DEPRECATED_PROJECTION_QUERY.distinctOn()); } private void compareBaseBuilderFields(StructuredQuery query) { + assertEquals(NAMESPACE, query.namespace()); + assertEquals(KIND, query.getKind()); + assertEquals(START_CURSOR, query.getStartCursor()); + assertEquals(END_CURSOR, query.getEndCursor()); + assertEquals(OFFSET, query.getOffset()); + assertEquals(LIMIT, query.getLimit()); + assertEquals(FILTER, query.getFilter()); + assertEquals(ORDER_BY, query.getOrderBy()); + } + + private void compareBaseBuilderFieldsDeprecated(StructuredQuery query) { assertEquals(NAMESPACE, query.namespace()); assertEquals(KIND, query.kind()); assertEquals(START_CURSOR, query.startCursor()); @@ -127,15 +193,15 @@ public void mergeFrom() { } private void compareMergedQuery(StructuredQuery expected, StructuredQuery actual) { - assertEquals(expected.kind(), actual.kind()); - assertEquals(expected.startCursor(), actual.startCursor()); - assertEquals(expected.endCursor(), actual.endCursor()); - assertEquals(expected.offset(), actual.offset()); - assertEquals(expected.limit(), actual.limit()); - assertEquals(expected.filter(), actual.filter()); - assertEquals(expected.orderBy(), actual.orderBy()); - assertEquals(expected.projection(), actual.projection()); - assertEquals(expected.distinctOn(), actual.distinctOn()); + assertEquals(expected.getKind(), actual.getKind()); + assertEquals(expected.getStartCursor(), actual.getStartCursor()); + assertEquals(expected.getEndCursor(), actual.getEndCursor()); + assertEquals(expected.getOffset(), actual.getOffset()); + assertEquals(expected.getLimit(), actual.getLimit()); + assertEquals(expected.getFilter(), actual.getFilter()); + assertEquals(expected.getOrderBy(), actual.getOrderBy()); + assertEquals(expected.getProjection(), actual.getProjection()); + assertEquals(expected.getDistinctOn(), actual.getDistinctOn()); } @Test @@ -162,8 +228,8 @@ public void testToBuilder() { @Test public void testKeyOnly() { - assertTrue(KEY_QUERY.keyOnly()); - assertFalse(ENTITY_QUERY.keyOnly()); - assertFalse(PROJECTION_QUERY.keyOnly()); + assertTrue(KEY_QUERY.isKeyOnly()); + assertFalse(ENTITY_QUERY.isKeyOnly()); + assertFalse(PROJECTION_QUERY.isKeyOnly()); } } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/ValueTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/ValueTest.java index bb039d1a1ac9..e36d69657b6d 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/ValueTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/ValueTest.java @@ -34,10 +34,10 @@ public class ValueTest { - private static final Key KEY = Key.builder("ds", "kind", 1).build(); + private static final Key KEY = Key.newBuilder("ds", "kind", 1).build(); private static final Blob BLOB = Blob.copyFrom(new byte[]{}); private static final DateTime DATE_TIME = DateTime.now(); - private static final Entity ENTITY = Entity.builder(KEY).set("FOO", "BAR").build(); + private static final Entity ENTITY = Entity.newBuilder(KEY).set("FOO", "BAR").build(); private static final NullValue NULL_VALUE = NullValue.of(); private static final StringValue STRING_VALUE = StringValue.of("hello"); private static final RawValue RAW_VALUE = RawValue.of(STRING_VALUE.toPb()); @@ -115,6 +115,13 @@ public void setUp() throws Exception { @Test public void testType() throws Exception { + for (Map.Entry> entry : typeToValue.entrySet()) { + assertEquals(entry.getKey(), entry.getValue().getType()); + } + } + + @Test + public void testTypeDeprecated() throws Exception { for (Map.Entry> entry : typeToValue.entrySet()) { assertEquals(entry.getKey(), entry.getValue().type()); } @@ -122,6 +129,17 @@ public void testType() throws Exception { @Test public void testExcludeFromIndexes() throws Exception { + for (Map.Entry> entry : typeToValue.entrySet()) { + assertFalse(entry.getValue().excludeFromIndexes()); + } + TestBuilder builder = new TestBuilder(); + assertFalse(builder.build().excludeFromIndexes()); + assertTrue(builder.setExcludeFromIndexes(true).build().excludeFromIndexes()); + assertFalse(builder.setExcludeFromIndexes(false).build().excludeFromIndexes()); + } + + @Test + public void testExcludeFromIndexesDeprecated() throws Exception { for (Map.Entry> entry : typeToValue.entrySet()) { assertFalse(entry.getValue().excludeFromIndexes()); } @@ -134,6 +152,12 @@ public void testExcludeFromIndexes() throws Exception { @SuppressWarnings("deprecation") @Test public void testMeaning() throws Exception { + TestBuilder builder = new TestBuilder(); + assertEquals(10, builder.setMeaning(10).build().getMeaning()); + } + + @Test + public void testMeaningDeprecated() throws Exception { TestBuilder builder = new TestBuilder(); assertEquals(10, builder.meaning(10).build().meaning()); } @@ -157,12 +181,12 @@ public void testToBuilder() throws Exception { Set content = Collections.singleton("bla"); @SuppressWarnings("rawtypes") ValueBuilder builder = new TestBuilder(); - builder.meaning(1).set(content).excludeFromIndexes(true); + builder.setMeaning(1).set(content).setExcludeFromIndexes(true); Value value = builder.build(); builder = value.toBuilder(); - assertEquals(1, value.meaning()); + assertEquals(1, value.getMeaning()); assertTrue(value.excludeFromIndexes()); - assertEquals(ValueType.LIST, value.type()); + assertEquals(ValueType.LIST, value.getType()); assertEquals(content, value.get()); assertEquals(value, builder.build()); } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/it/ITDatastoreTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/it/ITDatastoreTest.java index 35664071f862..c0a3901a9acd 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/it/ITDatastoreTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/it/ITDatastoreTest.java @@ -73,7 +73,7 @@ public class ITDatastoreTest { private static final RemoteDatastoreHelper HELPER = RemoteDatastoreHelper.create(); - private static final DatastoreOptions OPTIONS = HELPER.options(); + private static final DatastoreOptions OPTIONS = HELPER.getOptions(); private static final Datastore DATASTORE = OPTIONS.service(); private static final String PROJECT_ID = OPTIONS.projectId(); private static final String NAMESPACE = OPTIONS.namespace(); @@ -82,19 +82,28 @@ public class ITDatastoreTest { private static final String KIND3 = "kind3"; private static final NullValue NULL_VALUE = NullValue.of(); private static final StringValue STR_VALUE = StringValue.of("str"); - private static final BooleanValue BOOL_VALUE = BooleanValue.builder(false) - .excludeFromIndexes(true).build(); + private static final BooleanValue BOOL_VALUE = BooleanValue.newBuilder(false) + .setExcludeFromIndexes(true).build(); private static final IncompleteKey INCOMPLETE_KEY1 = - IncompleteKey.builder(PROJECT_ID, KIND1).namespace(NAMESPACE).build(); + IncompleteKey.newBuilder(PROJECT_ID, KIND1).setNamespace(NAMESPACE).build(); private static final IncompleteKey INCOMPLETE_KEY2 = - IncompleteKey.builder(PROJECT_ID, KIND2).namespace(NAMESPACE).build(); - private static final Key KEY1 = Key.builder(INCOMPLETE_KEY1, "name").build(); - private static final Key KEY2 = Key.builder(KEY1, KIND2, 1).build(); - private static final Key KEY3 = Key.builder(KEY2).name("bla").namespace(NAMESPACE).build(); - private static final Key KEY4 = Key.builder(KEY2).name("newName1").namespace(NAMESPACE).build(); - private static final Key KEY5 = Key.builder(KEY2).name("newName2").namespace(NAMESPACE).build(); + IncompleteKey.newBuilder(PROJECT_ID, KIND2).setNamespace(NAMESPACE).build(); + private static final Key KEY1 = Key.newBuilder(INCOMPLETE_KEY1, "name").build(); + private static final Key KEY2 = Key.newBuilder(KEY1, KIND2, 1).build(); + private static final Key KEY3 = Key.newBuilder(KEY2) + .setName("bla") + .setNamespace(NAMESPACE) + .build(); + private static final Key KEY4 = Key.newBuilder(KEY2) + .setName("newName1") + .setNamespace(NAMESPACE) + .build(); + private static final Key KEY5 = Key.newBuilder(KEY2) + .setName("newName2") + .setNamespace(NAMESPACE) + .build(); private static final KeyValue KEY_VALUE = KeyValue.of(KEY1); - private static final ListValue LIST_VALUE1 = ListValue.builder() + private static final ListValue LIST_VALUE1 = ListValue.newBuilder() .addValue(NULL_VALUE) .addValue(STR_VALUE, BOOL_VALUE) .build(); @@ -104,15 +113,17 @@ public class ITDatastoreTest { private static final LatLngValue LAT_LNG_VALUE = new LatLngValue(LatLng.of(37.422035, -122.084124)); private static final FullEntity PARTIAL_ENTITY1 = - FullEntity.builder(INCOMPLETE_KEY2).set("str", STR_VALUE).set("bool", BOOL_VALUE) + FullEntity.newBuilder(INCOMPLETE_KEY2).set("str", STR_VALUE).set("bool", BOOL_VALUE) .set("list", LIST_VALUE1).build(); private static final FullEntity PARTIAL_ENTITY2 = - FullEntity.builder(PARTIAL_ENTITY1).remove("str").set("bool", true) + FullEntity.newBuilder(PARTIAL_ENTITY1).remove("str").set("bool", true) .set("list", LIST_VALUE1.get()).build(); private static final FullEntity PARTIAL_ENTITY3 = - FullEntity.builder(PARTIAL_ENTITY1).key(IncompleteKey.builder(PROJECT_ID, KIND3).build()) + FullEntity.newBuilder(PARTIAL_ENTITY1) + + .setKey(IncompleteKey.newBuilder(PROJECT_ID, KIND3).build()) .build(); - private static final Entity ENTITY1 = Entity.builder(KEY1) + private static final Entity ENTITY1 = Entity.newBuilder(KEY1) .set("str", STR_VALUE) .set("date", DATE_TIME_VALUE) .set("latLng", LAT_LNG_VALUE) @@ -121,9 +132,9 @@ public class ITDatastoreTest { .set("list", LIST_VALUE2) .set("emptyList", EMPTY_LIST_VALUE) .build(); - private static final Entity ENTITY2 = Entity.builder(ENTITY1).key(KEY2).remove("str") + private static final Entity ENTITY2 = Entity.newBuilder(ENTITY1).setKey(KEY2).remove("str") .set("name", "Dan").setNull("null").set("age", 20).build(); - private static final Entity ENTITY3 = Entity.builder(ENTITY1).key(KEY3).remove("str") + private static final Entity ENTITY3 = Entity.newBuilder(ENTITY1).setKey(KEY3).remove("str") .set("null", NULL_VALUE).set("partial1", PARTIAL_ENTITY2).set("partial2", ENTITY2).build(); @Rule @@ -148,14 +159,14 @@ public void tearDown() { public void testNewTransactionCommit() { Transaction transaction = DATASTORE.newTransaction(); transaction.add(ENTITY3); - Entity entity2 = Entity.builder(ENTITY2) + Entity entity2 = Entity.newBuilder(ENTITY2) .clear() .setNull("bla") .build(); transaction.update(entity2); transaction.delete(KEY1); transaction.commit(); - assertFalse(transaction.active()); + assertFalse(transaction.isActive()); List list = DATASTORE.fetch(KEY1, KEY2, KEY3); assertNull(list.get(0)); @@ -189,8 +200,8 @@ public void testTransactionWithRead() { transaction = DATASTORE.newTransaction(); assertEquals(ENTITY3, transaction.get(KEY3)); // update entity3 during the transaction - DATASTORE.put(Entity.builder(ENTITY2).clear().set("from", "datastore").build()); - transaction.update(Entity.builder(ENTITY2).clear().set("from", "transaction").build()); + DATASTORE.put(Entity.newBuilder(ENTITY2).clear().set("from", "datastore").build()); + transaction.update(Entity.newBuilder(ENTITY2).clear().set("from", "transaction").build()); try { transaction.commit(); fail("Expecting a failure"); @@ -201,10 +212,10 @@ public void testTransactionWithRead() { @Test public void testTransactionWithQuery() throws InterruptedException { - Query query = Query.entityQueryBuilder() - .kind(KIND2) - .filter(PropertyFilter.hasAncestor(KEY2)) - .namespace(NAMESPACE) + Query query = Query.newEntityQueryBuilder() + .setKind(KIND2) + .setFilter(PropertyFilter.hasAncestor(KEY2)) + .setNamespace(NAMESPACE) .build(); Transaction transaction = DATASTORE.newTransaction(); QueryResults results = transaction.run(query); @@ -230,9 +241,9 @@ public void testTransactionWithQuery() throws InterruptedException { assertTrue(results.hasNext()); assertEquals(ENTITY2, results.next()); assertFalse(results.hasNext()); - transaction.delete(ENTITY3.key()); + transaction.delete(ENTITY3.getKey()); // update entity2 during the transaction - DATASTORE.put(Entity.builder(ENTITY2).clear().build()); + DATASTORE.put(Entity.newBuilder(ENTITY2).clear().build()); try { transaction.commit(); fail("Expecting a failure"); @@ -245,8 +256,8 @@ public void testTransactionWithQuery() throws InterruptedException { public void testNewTransactionRollback() { Transaction transaction = DATASTORE.newTransaction(); transaction.add(ENTITY3); - Entity entity2 = Entity.builder(ENTITY2).clear().setNull("bla") - .set("list3", StringValue.of("bla"), StringValue.builder("bla").build()).build(); + Entity entity2 = Entity.newBuilder(ENTITY2).clear().setNull("bla") + .set("list3", StringValue.of("bla"), StringValue.newBuilder("bla").build()).build(); transaction.update(entity2); transaction.delete(KEY1); transaction.rollback(); @@ -269,28 +280,28 @@ public void testNewTransactionRollback() { @Test public void testNewBatch() { Batch batch = DATASTORE.newBatch(); - Entity entity1 = Entity.builder(ENTITY1).clear().build(); - Entity entity2 = Entity.builder(ENTITY2).clear().setNull("bla").build(); - Entity entity4 = Entity.builder(KEY4).set("value", StringValue.of("value")).build(); - Entity entity5 = Entity.builder(KEY5).set("value", "value").build(); + Entity entity1 = Entity.newBuilder(ENTITY1).clear().build(); + Entity entity2 = Entity.newBuilder(ENTITY2).clear().setNull("bla").build(); + Entity entity4 = Entity.newBuilder(KEY4).set("value", StringValue.of("value")).build(); + Entity entity5 = Entity.newBuilder(KEY5).set("value", "value").build(); List entities = batch.add(entity4, PARTIAL_ENTITY2, entity5); Entity entity6 = entities.get(1); assertSame(entity4, entities.get(0)); - assertEquals(PARTIAL_ENTITY2.names(), entity6.names()); - assertEquals(PARTIAL_ENTITY2.key().projectId(), entity6.key().projectId()); - assertEquals(PARTIAL_ENTITY2.key().namespace(), entity6.key().namespace()); - assertEquals(PARTIAL_ENTITY2.key().ancestors(), entity6.key().ancestors()); - assertEquals(PARTIAL_ENTITY2.key().kind(), entity6.key().kind()); - assertEquals(PARTIAL_ENTITY2.key(), IncompleteKey.builder(entity6.key()).build()); - assertEquals(PARTIAL_ENTITY2.key().ancestors(), entity6.key().ancestors()); - assertNotEquals(PARTIAL_ENTITY2.key(), entity6.key()); + assertEquals(PARTIAL_ENTITY2.getNames(), entity6.getNames()); + assertEquals(PARTIAL_ENTITY2.getKey().getProjectId(), entity6.getKey().getProjectId()); + assertEquals(PARTIAL_ENTITY2.getKey().getNamespace(), entity6.getKey().getNamespace()); + assertEquals(PARTIAL_ENTITY2.getKey().getAncestors(), entity6.getKey().getAncestors()); + assertEquals(PARTIAL_ENTITY2.getKey().getKind(), entity6.getKey().getKind()); + assertEquals(PARTIAL_ENTITY2.getKey(), IncompleteKey.newBuilder(entity6.getKey()).build()); + assertEquals(PARTIAL_ENTITY2.getKey().getAncestors(), entity6.getKey().getAncestors()); + assertNotEquals(PARTIAL_ENTITY2.getKey(), entity6.getKey()); assertSame(entity5, entities.get(2)); batch.addWithDeferredIdAllocation(PARTIAL_ENTITY3); batch.put(ENTITY3, entity1, entity2); Batch.Response response = batch.submit(); - entities = DATASTORE.fetch(KEY1, KEY2, KEY3, entity4.key(), entity5.key(), entity6.key()); + entities = DATASTORE.fetch(KEY1, KEY2, KEY3, entity4.getKey(), entity5.getKey(), entity6.getKey()); assertEquals(entity1, entities.get(0)); assertEquals(entity2, entities.get(1)); assertEquals(ENTITY3, entities.get(2)); @@ -298,10 +309,10 @@ public void testNewBatch() { assertEquals(entity5, entities.get(4)); assertEquals(entity6, entities.get(5)); assertEquals(6, entities.size()); - List generatedKeys = response.generatedKeys(); + List generatedKeys = response.getGeneratedKeys(); assertEquals(1, generatedKeys.size()); - assertEquals(PARTIAL_ENTITY3.names(), DATASTORE.get(generatedKeys.get(0)).names()); - assertEquals(PARTIAL_ENTITY3.key(), IncompleteKey.builder(generatedKeys.get(0)).build()); + assertEquals(PARTIAL_ENTITY3.getNames(), DATASTORE.get(generatedKeys.get(0)).getNames()); + assertEquals(PARTIAL_ENTITY3.getKey(), IncompleteKey.newBuilder(generatedKeys.get(0)).build()); try { batch.submit(); @@ -311,10 +322,10 @@ public void testNewBatch() { } batch = DATASTORE.newBatch(); - batch.delete(entity4.key(), entity5.key(), entity6.key()); + batch.delete(entity4.getKey(), entity5.getKey(), entity6.getKey()); batch.update(ENTITY1, ENTITY2, ENTITY3); batch.submit(); - entities = DATASTORE.fetch(KEY1, KEY2, KEY3, entity4.key(), entity5.key(), entity6.key()); + entities = DATASTORE.fetch(KEY1, KEY2, KEY3, entity4.getKey(), entity5.getKey(), entity6.getKey()); assertEquals(ENTITY1, entities.get(0)); assertEquals(ENTITY2, entities.get(1)); assertEquals(ENTITY3, entities.get(2)); @@ -326,8 +337,8 @@ public void testNewBatch() { @Test public void testRunGqlQueryNoCasting() throws InterruptedException { - Query query1 = Query.gqlQueryBuilder(ResultType.ENTITY, "select * from " + KIND1) - .namespace(NAMESPACE) + Query query1 = Query.newGqlQueryBuilder(ResultType.ENTITY, "select * from " + KIND1) + .setNamespace(NAMESPACE) .build(); QueryResults results1 = DATASTORE.run(query1); while (Iterators.size(results1) < 1) { @@ -341,8 +352,8 @@ public void testRunGqlQueryNoCasting() throws InterruptedException { DATASTORE.put(ENTITY3); Query query2 = - Query.gqlQueryBuilder(ResultType.ENTITY, "select * from " + KIND2 + " order by __key__") - .namespace(NAMESPACE) + Query.newGqlQueryBuilder(ResultType.ENTITY, "select * from " + KIND2 + " order by __key__") + .setNamespace(NAMESPACE) .build(); QueryResults results2 = DATASTORE.run(query2); while (Iterators.size(results2) < 2) { @@ -356,14 +367,14 @@ public void testRunGqlQueryNoCasting() throws InterruptedException { assertEquals(ENTITY3, results2.next()); assertFalse(results2.hasNext()); - query1 = Query.gqlQueryBuilder(ResultType.ENTITY, "select * from bla") - .namespace(NAMESPACE) + query1 = Query.newGqlQueryBuilder(ResultType.ENTITY, "select * from bla") + .setNamespace(NAMESPACE) .build(); results1 = DATASTORE.run(query1); assertFalse(results1.hasNext()); - Query keyOnlyQuery = Query.gqlQueryBuilder(ResultType.KEY, "select __key__ from " + KIND1) - .namespace(NAMESPACE) + Query keyOnlyQuery = Query.newGqlQueryBuilder(ResultType.KEY, "select __key__ from " + KIND1) + .setNamespace(NAMESPACE) .build(); QueryResults keyOnlyResults = DATASTORE.run(keyOnlyQuery); while (Iterators.size(keyOnlyResults) < 1) { @@ -376,8 +387,8 @@ public void testRunGqlQueryNoCasting() throws InterruptedException { assertFalse(keyOnlyResults.hasNext()); GqlQuery keyProjectionQuery = - Query.gqlQueryBuilder(ResultType.PROJECTION_ENTITY, "select __key__ from " + KIND1) - .namespace(NAMESPACE) + Query.newGqlQueryBuilder(ResultType.PROJECTION_ENTITY, "select __key__ from " + KIND1) + .setNamespace(NAMESPACE) .build(); QueryResults keyProjectionResult = DATASTORE.run(keyProjectionQuery); while (Iterators.size(keyProjectionResult) < 1) { @@ -387,16 +398,16 @@ public void testRunGqlQueryNoCasting() throws InterruptedException { keyProjectionResult = DATASTORE.run(keyProjectionQuery); assertTrue(keyProjectionResult.hasNext()); ProjectionEntity projectionEntity = keyProjectionResult.next(); - assertEquals(KEY1, projectionEntity.key()); - assertTrue(projectionEntity.names().isEmpty()); + assertEquals(KEY1, projectionEntity.getKey()); + assertTrue(projectionEntity.getNames().isEmpty()); assertFalse(keyProjectionResult.hasNext()); } @Test public void testRunGqlQueryWithCasting() throws InterruptedException { @SuppressWarnings("unchecked") - Query query1 = (Query) Query.gqlQueryBuilder("select * from " + KIND1) - .namespace(NAMESPACE) + Query query1 = (Query) Query.newGqlQueryBuilder("select * from " + KIND1) + .setNamespace(NAMESPACE) .build(); QueryResults results1 = DATASTORE.run(query1); while (Iterators.size(results1) < 1) { @@ -408,8 +419,8 @@ public void testRunGqlQueryWithCasting() throws InterruptedException { assertEquals(ENTITY1, results1.next()); assertFalse(results1.hasNext()); - Query query2 = Query.gqlQueryBuilder("select * from " + KIND1) - .namespace(NAMESPACE) + Query query2 = Query.newGqlQueryBuilder("select * from " + KIND1) + .setNamespace(NAMESPACE) .build(); QueryResults results2 = DATASTORE.run(query2); while (Iterators.size(results2) < 1) { @@ -417,7 +428,7 @@ public void testRunGqlQueryWithCasting() throws InterruptedException { results2 = DATASTORE.run(query2); } results2 = DATASTORE.run(query1); - assertSame(Entity.class, results2.resultClass()); + assertSame(Entity.class, results2.getResultClass()); @SuppressWarnings("unchecked") QueryResults results3 = (QueryResults) results2; assertTrue(results3.hasNext()); @@ -428,7 +439,7 @@ public void testRunGqlQueryWithCasting() throws InterruptedException { @Test public void testRunStructuredQuery() throws InterruptedException { Query query = - Query.entityQueryBuilder().kind(KIND1).orderBy(OrderBy.asc("__key__")).build(); + Query.newEntityQueryBuilder().setKind(KIND1).setOrderBy(OrderBy.asc("__key__")).build(); QueryResults results1 = DATASTORE.run(query); while (Iterators.size(results1) < 1) { Thread.sleep(500); @@ -439,7 +450,7 @@ public void testRunStructuredQuery() throws InterruptedException { assertEquals(ENTITY1, results1.next()); assertFalse(results1.hasNext()); - Query keyOnlyQuery = Query.keyQueryBuilder().kind(KIND1).build(); + Query keyOnlyQuery = Query.newKeyQueryBuilder().setKind(KIND1).build(); QueryResults results2 = DATASTORE.run(keyOnlyQuery); while (Iterators.size(results2) < 1) { Thread.sleep(500); @@ -447,12 +458,12 @@ public void testRunStructuredQuery() throws InterruptedException { } results2 = DATASTORE.run(keyOnlyQuery); assertTrue(results2.hasNext()); - assertEquals(ENTITY1.key(), results2.next()); + assertEquals(ENTITY1.getKey(), results2.next()); assertFalse(results2.hasNext()); StructuredQuery keyOnlyProjectionQuery = - Query.projectionEntityQueryBuilder() - .kind(KIND1).projection("__key__").build(); + Query.newProjectionEntityQueryBuilder() + .setKind(KIND1).setProjection("__key__").build(); QueryResults results3 = DATASTORE.run(keyOnlyProjectionQuery); while (Iterators.size(results3) < 1) { Thread.sleep(500); @@ -461,17 +472,17 @@ public void testRunStructuredQuery() throws InterruptedException { results3 = DATASTORE.run(keyOnlyProjectionQuery); assertTrue(results3.hasNext()); ProjectionEntity projectionEntity = results3.next(); - assertEquals(ENTITY1.key(), projectionEntity.key()); - assertTrue(projectionEntity.names().isEmpty()); + assertEquals(ENTITY1.getKey(), projectionEntity.getKey()); + assertTrue(projectionEntity.getNames().isEmpty()); assertFalse(results2.hasNext()); - StructuredQuery projectionQuery = Query.projectionEntityQueryBuilder() - .kind(KIND2) - .projection("age") - .filter(PropertyFilter.gt("age", 18)) - .distinctOn("age") - .orderBy(OrderBy.asc("age")) - .limit(10) + StructuredQuery projectionQuery = Query.newProjectionEntityQueryBuilder() + .setKind(KIND2) + .setProjection("age") + .setFilter(PropertyFilter.gt("age", 18)) + .setDistinctOn("age") + .setOrderBy(OrderBy.asc("age")) + .setLimit(10) .build(); QueryResults results4 = DATASTORE.run(projectionQuery); @@ -482,51 +493,51 @@ public void testRunStructuredQuery() throws InterruptedException { results4 = DATASTORE.run(projectionQuery); assertTrue(results4.hasNext()); ProjectionEntity entity = results4.next(); - assertEquals(ENTITY2.key(), entity.key()); + assertEquals(ENTITY2.getKey(), entity.getKey()); assertEquals(20, entity.getLong("age")); - assertEquals(1, entity.names().size()); + assertEquals(1, entity.getNames().size()); assertFalse(results4.hasNext()); } @Test public void testAllocateId() { - KeyFactory keyFactory = DATASTORE.newKeyFactory().kind(KIND1); + KeyFactory keyFactory = DATASTORE.newKeyFactory().setKind(KIND1); IncompleteKey pk1 = keyFactory.newKey(); Key key1 = DATASTORE.allocateId(pk1); - assertEquals(key1.projectId(), pk1.projectId()); - assertEquals(key1.namespace(), pk1.namespace()); - assertEquals(key1.ancestors(), pk1.ancestors()); - assertEquals(key1.kind(), pk1.kind()); + assertEquals(key1.getProjectId(), pk1.getProjectId()); + assertEquals(key1.getNamespace(), pk1.getNamespace()); + assertEquals(key1.getAncestors(), pk1.getAncestors()); + assertEquals(key1.getKind(), pk1.getKind()); assertTrue(key1.hasId()); assertFalse(key1.hasName()); - assertEquals(Key.builder(pk1, key1.id()).build(), key1); + assertEquals(Key.newBuilder(pk1, key1.getId()).build(), key1); Key key2 = DATASTORE.allocateId(pk1); assertNotEquals(key1, key2); - assertEquals(Key.builder(pk1, key2.id()).build(), key2); + assertEquals(Key.newBuilder(pk1, key2.getId()).build(), key2); Key key3 = DATASTORE.allocateId(key1); assertNotEquals(key1, key3); - assertEquals(Key.builder(pk1, key3.id()).build(), key3); + assertEquals(Key.newBuilder(pk1, key3.getId()).build(), key3); } @Test public void testAllocateIdArray() { - KeyFactory keyFactory = DATASTORE.newKeyFactory().kind(KIND1); + KeyFactory keyFactory = DATASTORE.newKeyFactory().setKind(KIND1); IncompleteKey incompleteKey1 = keyFactory.newKey(); IncompleteKey incompleteKey2 = - keyFactory.kind(KIND2).ancestors(PathElement.of(KIND1, 10)).newKey(); + keyFactory.setKind(KIND2).addAncestors(PathElement.of(KIND1, 10)).newKey(); Key key3 = keyFactory.newKey("name"); Key key4 = keyFactory.newKey(1); List result = DATASTORE.allocateId(incompleteKey1, incompleteKey2, key3, key4, incompleteKey1, key3); assertEquals(6, result.size()); - assertEquals(Key.builder(incompleteKey1, result.get(0).id()).build(), result.get(0)); - assertEquals(Key.builder(incompleteKey1, result.get(4).id()).build(), result.get(4)); - assertEquals(Key.builder(incompleteKey2, result.get(1).id()).build(), result.get(1)); - assertEquals(Key.builder(key3).id(result.get(2).id()).build(), result.get(2)); - assertEquals(Key.builder(key3).id(result.get(5).id()).build(), result.get(5)); - assertEquals(Key.builder(key4).id(result.get(3).id()).build(), result.get(3)); + assertEquals(Key.newBuilder(incompleteKey1, result.get(0).getId()).build(), result.get(0)); + assertEquals(Key.newBuilder(incompleteKey1, result.get(4).getId()).build(), result.get(4)); + assertEquals(Key.newBuilder(incompleteKey2, result.get(1).getId()).build(), result.get(1)); + assertEquals(Key.newBuilder(key3).setId(result.get(2).getId()).build(), result.get(2)); + assertEquals(Key.newBuilder(key3).setId(result.get(5).getId()).build(), result.get(5)); + assertEquals(Key.newBuilder(key4).setId(result.get(3).getId()).build(), result.get(3)); } @Test @@ -550,7 +561,7 @@ public void testGet() { assertEquals(PARTIAL_ENTITY1, value6); ListValue value7 = entity.getValue("emptyList"); assertEquals(EMPTY_LIST_VALUE, value7); - assertEquals(7, entity.names().size()); + assertEquals(7, entity.getNames().size()); assertFalse(entity.contains("bla")); } @@ -558,7 +569,7 @@ public void testGet() { public void testGetArrayNoDeferredResults() { DATASTORE.put(ENTITY3); Iterator result = - DATASTORE.fetch(KEY1, Key.builder(KEY1).name("bla").build(), KEY2, KEY3).iterator(); + DATASTORE.fetch(KEY1, Key.newBuilder(KEY1).setName("bla").build(), KEY2, KEY3).iterator(); assertEquals(ENTITY1, result.next()); assertNull(result.next()); assertEquals(ENTITY2, result.next()); @@ -571,10 +582,10 @@ public void testGetArrayNoDeferredResults() { FullEntity partial2 = entity3.getEntity("partial2"); assertEquals(PARTIAL_ENTITY2, partial1); assertEquals(ENTITY2, partial2); - assertEquals(ValueType.BOOLEAN, entity3.getValue("bool").type()); + assertEquals(ValueType.BOOLEAN, entity3.getValue("bool").getType()); assertEquals(LAT_LNG_VALUE, entity3.getValue("latLng")); assertEquals(EMPTY_LIST_VALUE, entity3.getValue("emptyList")); - assertEquals(8, entity3.names().size()); + assertEquals(8, entity3.getNames().size()); assertFalse(entity3.contains("bla")); try { entity3.getString("str"); @@ -587,7 +598,7 @@ public void testGetArrayNoDeferredResults() { @Test public void testAddEntity() { - List keys = DATASTORE.fetch(ENTITY1.key(), ENTITY3.key()); + List keys = DATASTORE.fetch(ENTITY1.getKey(), ENTITY3.getKey()); assertEquals(ENTITY1, keys.get(0)); assertNull(keys.get(1)); assertEquals(2, keys.size()); @@ -600,22 +611,22 @@ public void testAddEntity() { } List entities = DATASTORE.add(ENTITY3, PARTIAL_ENTITY1, PARTIAL_ENTITY2); - assertEquals(ENTITY3, DATASTORE.get(ENTITY3.key())); + assertEquals(ENTITY3, DATASTORE.get(ENTITY3.getKey())); assertEquals(ENTITY3, entities.get(0)); - assertEquals(PARTIAL_ENTITY1.names(), entities.get(1).names()); - assertEquals(PARTIAL_ENTITY1.key().ancestors(), entities.get(1).key().ancestors()); - assertNotNull(DATASTORE.get(entities.get(1).key())); - assertEquals(PARTIAL_ENTITY2.names(), entities.get(2).names()); - assertEquals(PARTIAL_ENTITY2.key().ancestors(), entities.get(2).key().ancestors()); - assertNotNull(DATASTORE.get(entities.get(2).key())); + assertEquals(PARTIAL_ENTITY1.getNames(), entities.get(1).getNames()); + assertEquals(PARTIAL_ENTITY1.getKey().getAncestors(), entities.get(1).getKey().getAncestors()); + assertNotNull(DATASTORE.get(entities.get(1).getKey())); + assertEquals(PARTIAL_ENTITY2.getNames(), entities.get(2).getNames()); + assertEquals(PARTIAL_ENTITY2.getKey().getAncestors(), entities.get(2).getKey().getAncestors()); + assertNotNull(DATASTORE.get(entities.get(2).getKey())); for (Entity entity : entities) { - DATASTORE.delete(entity.key()); + DATASTORE.delete(entity.getKey()); } } @Test public void testUpdate() { - List keys = DATASTORE.fetch(ENTITY1.key(), ENTITY3.key()); + List keys = DATASTORE.fetch(ENTITY1.getKey(), ENTITY3.getKey()); assertEquals(ENTITY1, keys.get(0)); assertNull(keys.get(1)); assertEquals(2, keys.size()); @@ -627,47 +638,47 @@ public void testUpdate() { // expected; } DATASTORE.add(ENTITY3); - assertEquals(ENTITY3, DATASTORE.get(ENTITY3.key())); - Entity entity3 = Entity.builder(ENTITY3).clear().set("bla", new NullValue()).build(); + assertEquals(ENTITY3, DATASTORE.get(ENTITY3.getKey())); + Entity entity3 = Entity.newBuilder(ENTITY3).clear().set("bla", new NullValue()).build(); assertNotEquals(ENTITY3, entity3); DATASTORE.update(entity3); - assertEquals(entity3, DATASTORE.get(ENTITY3.key())); + assertEquals(entity3, DATASTORE.get(ENTITY3.getKey())); } @Test public void testPut() { - Entity updatedEntity = Entity.builder(ENTITY1).set("new_property", 42L).build(); + Entity updatedEntity = Entity.newBuilder(ENTITY1).set("new_property", 42L).build(); assertEquals(updatedEntity, DATASTORE.put(updatedEntity)); - assertEquals(updatedEntity, DATASTORE.get(updatedEntity.key())); + assertEquals(updatedEntity, DATASTORE.get(updatedEntity.getKey())); - Entity entity2 = Entity.builder(ENTITY2).clear().set("bla", new NullValue()).build(); + Entity entity2 = Entity.newBuilder(ENTITY2).clear().set("bla", new NullValue()).build(); assertNotEquals(ENTITY2, entity2); List entities = DATASTORE.put(ENTITY1, entity2, ENTITY3, PARTIAL_ENTITY1); assertEquals(ENTITY1, entities.get(0)); assertEquals(entity2, entities.get(1)); assertEquals(ENTITY3, entities.get(2)); - assertEquals(PARTIAL_ENTITY1.names(), entities.get(3).names()); - assertEquals(PARTIAL_ENTITY1.key().ancestors(), entities.get(3).key().ancestors()); - assertEquals(ENTITY1, DATASTORE.get(ENTITY1.key())); - assertEquals(entity2, DATASTORE.get(entity2.key())); - assertEquals(ENTITY3, DATASTORE.get(ENTITY3.key())); - Entity entity = DATASTORE.get(entities.get(3).key()); + assertEquals(PARTIAL_ENTITY1.getNames(), entities.get(3).getNames()); + assertEquals(PARTIAL_ENTITY1.getKey().getAncestors(), entities.get(3).getKey().getAncestors()); + assertEquals(ENTITY1, DATASTORE.get(ENTITY1.getKey())); + assertEquals(entity2, DATASTORE.get(entity2.getKey())); + assertEquals(ENTITY3, DATASTORE.get(ENTITY3.getKey())); + Entity entity = DATASTORE.get(entities.get(3).getKey()); assertEquals(entities.get(3), entity); for (Entity entityToDelete : entities) { - DATASTORE.delete(entityToDelete.key()); + DATASTORE.delete(entityToDelete.getKey()); } } @Test public void testDelete() { Iterator keys = - DATASTORE.fetch(ENTITY1.key(), ENTITY2.key(), ENTITY3.key()).iterator(); + DATASTORE.fetch(ENTITY1.getKey(), ENTITY2.getKey(), ENTITY3.getKey()).iterator(); assertEquals(ENTITY1, keys.next()); assertEquals(ENTITY2, keys.next()); assertNull(keys.next()); assertFalse(keys.hasNext()); - DATASTORE.delete(ENTITY1.key(), ENTITY2.key(), ENTITY3.key()); - keys = DATASTORE.fetch(ENTITY1.key(), ENTITY2.key(), ENTITY3.key()).iterator(); + DATASTORE.delete(ENTITY1.getKey(), ENTITY2.getKey(), ENTITY3.getKey()); + keys = DATASTORE.fetch(ENTITY1.getKey(), ENTITY2.getKey(), ENTITY3.getKey()).iterator(); assertNull(keys.next()); assertNull(keys.next()); assertNull(keys.next()); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java index cab189ae8cb9..4aa0a7261f62 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java @@ -49,6 +49,16 @@ public class LocalDatastoreHelperTest { @Test public void testCreate() { + LocalDatastoreHelper helper = LocalDatastoreHelper.create(0.75); + assertTrue(Math.abs(0.75 - helper.getConsistency()) < TOLERANCE); + assertTrue(helper.getProjectId().startsWith(PROJECT_ID_PREFIX)); + helper = LocalDatastoreHelper.create(); + assertTrue(Math.abs(0.9 - helper.getConsistency()) < TOLERANCE); + assertTrue(helper.getProjectId().startsWith(PROJECT_ID_PREFIX)); + } + + @Test + public void testCreateDeprecated() { LocalDatastoreHelper helper = LocalDatastoreHelper.create(0.75); assertTrue(Math.abs(0.75 - helper.consistency()) < TOLERANCE); assertTrue(helper.projectId().startsWith(PROJECT_ID_PREFIX)); @@ -60,11 +70,11 @@ public void testCreate() { @Test public void testOptions() { LocalDatastoreHelper helper = LocalDatastoreHelper.create(); - DatastoreOptions options = helper.options(); + DatastoreOptions options = helper.getOptions(); assertTrue(options.projectId().startsWith(PROJECT_ID_PREFIX)); assertTrue(options.host().startsWith("localhost:")); assertSame(AuthCredentials.noAuth(), options.authCredentials()); - options = helper.options(NAMESPACE); + options = helper.getOptions(NAMESPACE); assertTrue(options.projectId().startsWith(PROJECT_ID_PREFIX)); assertTrue(options.host().startsWith("localhost:")); assertSame(AuthCredentials.noAuth(), options.authCredentials()); @@ -75,9 +85,9 @@ public void testOptions() { public void testStartStopReset() throws IOException, InterruptedException { LocalDatastoreHelper helper = LocalDatastoreHelper.create(); helper.start(); - Datastore datastore = helper.options().service(); - Key key = datastore.newKeyFactory().kind("kind").newKey("name"); - datastore.put(Entity.builder(key).build()); + Datastore datastore = helper.getOptions().service(); + Key key = datastore.newKeyFactory().setKind("kind").newKey("name"); + datastore.put(Entity.newBuilder(key).build()); assertNotNull(datastore.get(key)); helper.reset(); assertNull(datastore.get(key)); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/DatastoreExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/DatastoreExample.java index 524958fbd042..515d1ceac5d4 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/DatastoreExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/DatastoreExample.java @@ -80,10 +80,10 @@ public void run(Transaction tx, Key userKey, Void arg) { System.out.println("Nothing to delete, user does not exist."); return; } - Query query = Query.keyQueryBuilder() - .namespace(NAMESPACE) - .kind(COMMENT_KIND) - .filter(PropertyFilter.hasAncestor(userKey)) + Query query = Query.newKeyQueryBuilder() + .setNamespace(NAMESPACE) + .setKind(COMMENT_KIND) + .setFilter(PropertyFilter.hasAncestor(userKey)) .build(); QueryResults comments = tx.run(query); int count = 0; @@ -92,7 +92,7 @@ public void run(Transaction tx, Key userKey, Void arg) { count++; } tx.delete(userKey); - System.out.printf("Deleting user '%s' and %d comment[s].%n", userKey.name(), count); + System.out.printf("Deleting user '%s' and %d comment[s].%n", userKey.getName(), count); } @Override @@ -110,7 +110,7 @@ private static class DisplayAction extends DatastoreAction { public void run(Transaction tx, Key userKey, Void arg) { Entity user = tx.get(userKey); if (user == null) { - System.out.printf("User '%s' does not exist.%n", userKey.name()); + System.out.printf("User '%s' does not exist.%n", userKey.getName()); return; } if (user.contains("contact")) { @@ -118,17 +118,17 @@ public void run(Transaction tx, Key userKey, Void arg) { String email = contact.getString("email"); String phone = contact.getString("phone"); System.out.printf("User '%s' email is '%s', phone is '%s'.%n", - userKey.name(), email, phone); + userKey.getName(), email, phone); } - System.out.printf("User '%s' has %d comment[s].%n", userKey.name(), user.getLong("count")); + System.out.printf("User '%s' has %d comment[s].%n", userKey.getName(), user.getLong("count")); int limit = 200; Map sortedComments = new TreeMap<>(); StructuredQuery query = - Query.entityQueryBuilder() - .namespace(NAMESPACE) - .kind(COMMENT_KIND) - .filter(PropertyFilter.hasAncestor(userKey)) - .limit(limit) + Query.newEntityQueryBuilder() + .setNamespace(NAMESPACE) + .setKind(COMMENT_KIND) + .setFilter(PropertyFilter.hasAncestor(userKey)) + .setLimit(limit) .build(); while (true) { QueryResults results = tx.run(query); @@ -141,7 +141,7 @@ public void run(Transaction tx, Key userKey, Void arg) { if (resultCount < limit) { break; } - query = query.toBuilder().startCursor(results.cursorAfter()).build(); + query = query.toBuilder().setStartCursor(results.getCursorAfter()).build(); } // We could have added "ORDER BY timestamp" to the query to avoid sorting, but that would // require adding an ancestor index for timestamp. @@ -166,19 +166,19 @@ public void run(Transaction tx, Key userKey, String content) { Entity user = tx.get(userKey); if (user == null) { System.out.println("Adding a new user."); - user = Entity.builder(userKey).set("count", 1).build(); + user = Entity.newBuilder(userKey).set("count", 1).build(); tx.add(user); } else { - user = Entity.builder(user).set("count", user.getLong("count") + 1L).build(); + user = Entity.newBuilder(user).set("count", user.getLong("count") + 1L).build(); tx.update(user); } - IncompleteKey commentKey = IncompleteKey.builder(userKey, COMMENT_KIND).build(); - FullEntity comment = FullEntity.builder(commentKey) + IncompleteKey commentKey = IncompleteKey.newBuilder(userKey, COMMENT_KIND).build(); + FullEntity comment = FullEntity.newBuilder(commentKey) .set("content", content) .set("timestamp", DateTime.now()) .build(); tx.addWithDeferredIdAllocation(comment); - System.out.printf("Adding a comment to user '%s'.%n", userKey.name()); + System.out.printf("Adding a comment to user '%s'.%n", userKey.getName()); } @Override @@ -231,15 +231,15 @@ public void run(Transaction tx, Key userKey, Contact contact) { Entity user = tx.get(userKey); if (user == null) { System.out.println("Adding a new user."); - user = Entity.builder(userKey).set("count", 0L).build(); + user = Entity.newBuilder(userKey).set("count", 0L).build(); tx.add(user); } - FullEntity contactEntity = FullEntity.builder() + FullEntity contactEntity = FullEntity.newBuilder() .set("email", contact.email()) .set("phone", contact.phone()) .build(); - tx.update(Entity.builder(user).set("contact", contactEntity).build()); - System.out.printf("Setting contact for user '%s'.%n", userKey.name()); + tx.update(Entity.newBuilder(user).set("contact", contactEntity).build()); + System.out.printf("Setting contact for user '%s'.%n", userKey.getName()); } @Override @@ -293,9 +293,9 @@ public static void main(String... args) throws Exception { // .build(); DatastoreOptions options = DatastoreOptions.builder().projectId(projectId).namespace(NAMESPACE).build(); - String name = args.length > 1 ? args[1] : System.getProperty("user.name"); + String name = args.length > 1 ? args[1] : System.getProperty("user.getName"); Datastore datastore = options.service(); - KeyFactory keyFactory = datastore.newKeyFactory().kind(USER_KIND); + KeyFactory keyFactory = datastore.newKeyFactory().setKind(USER_KIND); Key key = keyFactory.newKey(name); String actionName = args.length > 2 ? args[2].toLowerCase() : DEFAULT_ACTION; DatastoreAction action = ACTIONS.get(actionName); @@ -322,7 +322,7 @@ public static void main(String... args) throws Exception { action.run(tx, key, request); tx.commit(); } finally { - if (tx.active()) { + if (tx.isActive()) { tx.rollback(); } } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java index 29b8453ccf28..122d93dbb637 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java @@ -43,9 +43,9 @@ public static void main(String... args) { Datastore datastore = DatastoreOptions.defaultInstance().service(); // Add an entity to Datastore - KeyFactory keyFactory = datastore.newKeyFactory().kind("Person"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("Person"); Key key = keyFactory.newKey("john.doe@gmail.com"); - Entity entity = Entity.builder(key) + Entity entity = Entity.newBuilder(key) .set("name", "John Doe") .set("age", 51) .set("favorite_food", "pizza") @@ -57,13 +57,13 @@ public static void main(String... args) { // Add a couple more entities to make the query results more interesting Key janeKey = keyFactory.newKey("jane.doe@gmail.com"); - Entity janeEntity = Entity.builder(janeKey) + Entity janeEntity = Entity.newBuilder(janeKey) .set("name", "Jane Doe") .set("age", 44) .set("favorite_food", "pizza") .build(); Key joeKey = keyFactory.newKey("joe.shmoe@gmail.com"); - Entity joeEntity = Entity.builder(joeKey) + Entity joeEntity = Entity.newBuilder(joeKey) .set("name", "Joe Shmoe") .set("age", 27) .set("favorite_food", "sushi") @@ -71,9 +71,9 @@ public static void main(String... args) { datastore.put(janeEntity, joeEntity); // Run a query - Query query = Query.entityQueryBuilder() - .kind("Person") - .filter(PropertyFilter.eq("favorite_food", "pizza")) + Query query = Query.newEntityQueryBuilder() + .setKind("Person") + .setFilter(PropertyFilter.eq("favorite_food", "pizza")) .build(); QueryResults results = datastore.run(query); while (results.hasNext()) { diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/CreateEntity.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/CreateEntity.java index 0ed4c5081450..9da67416f34b 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/CreateEntity.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/CreateEntity.java @@ -36,9 +36,9 @@ public class CreateEntity { public static void main(String... args) { Datastore datastore = DatastoreOptions.defaultInstance().service(); - KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind"); Key key = keyFactory.newKey("keyName"); - Entity entity = Entity.builder(key) + Entity entity = Entity.newBuilder(key) .set("name", "John Doe") .set("age", 30) .set("access_time", DateTime.now()) diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/DatastoreSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/DatastoreSnippets.java index 7eee484af92a..0233830f6606 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/DatastoreSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/DatastoreSnippets.java @@ -76,11 +76,11 @@ public String run(DatastoreReaderWriter readerWriter) { // [VARIABLE "my_key_name_2"] public Batch newBatch(String keyName1, String keyName2) { // [START newBatch] - Key key1 = datastore.newKeyFactory().kind("MyKind").newKey(keyName1); - Key key2 = datastore.newKeyFactory().kind("MyKind").newKey(keyName2); + Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); + Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); Batch batch = datastore.newBatch(); - Entity entity1 = Entity.builder(key1).set("name", "John").build(); - Entity entity2 = Entity.builder(key2).set("title", "title").build(); + Entity entity1 = Entity.newBuilder(key1).set("name", "John").build(); + Entity entity2 = Entity.newBuilder(key2).set("title", "title").build(); batch.add(entity1); batch.add(entity2); batch.submit(); @@ -94,7 +94,7 @@ public Batch newBatch(String keyName1, String keyName2) { // [TARGET allocateId(IncompleteKey)] public Key allocateIdSingle() { // [START allocateIdSingle] - KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); IncompleteKey incompleteKey = keyFactory.newKey(); // let cloud datastore automatically assign an id @@ -109,7 +109,7 @@ public Key allocateIdSingle() { // [TARGET allocateId(IncompleteKey...)] public List batchAllocateId() { // [START batchAllocateId] - KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); IncompleteKey incompleteKey1 = keyFactory.newKey(); IncompleteKey incompleteKey2 = keyFactory.newKey(); @@ -127,13 +127,13 @@ public List batchAllocateId() { // [VARIABLE "my_key_name_2"] public void batchUpdateEntities(String keyName1, String keyName2) { // [START batchUpdateEntities] - Key key1 = datastore.newKeyFactory().kind("MyKind").newKey(keyName1); - Entity.Builder entityBuilder1 = Entity.builder(key1); + Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); + Entity.Builder entityBuilder1 = Entity.newBuilder(key1); entityBuilder1.set("propertyName", "updatedValue1"); Entity entity1 = entityBuilder1.build(); - Key key2 = datastore.newKeyFactory().kind("MyKind").newKey(keyName2); - Entity.Builder entityBuilder2 = Entity.builder(key2); + Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); + Entity.Builder entityBuilder2 = Entity.newBuilder(key2); entityBuilder2.set("propertyName", "updatedValue2"); Entity entity2 = entityBuilder2.build(); @@ -148,8 +148,8 @@ public void batchUpdateEntities(String keyName1, String keyName2) { // [VARIABLE "my_key_name"] public void putSingleEntity(String keyName) { // [START putSingleEntity] - Key key = datastore.newKeyFactory().kind("MyKind").newKey(keyName); - Entity.Builder entityBuilder = Entity.builder(key); + Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); + Entity.Builder entityBuilder = Entity.newBuilder(key); entityBuilder.set("propertyName", "value"); Entity entity = entityBuilder.build(); datastore.put(entity); @@ -164,13 +164,13 @@ public void putSingleEntity(String keyName) { // [VARIABLE "my_key_name2"] public void batchPutEntities(String keyName1, String keyName2) { // [START batchPutEntities] - Key key1 = datastore.newKeyFactory().kind("MyKind").newKey(keyName1); - Entity.Builder entityBuilder1 = Entity.builder(key1); + Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); + Entity.Builder entityBuilder1 = Entity.newBuilder(key1); entityBuilder1.set("propertyName", "value1"); Entity entity1 = entityBuilder1.build(); - Key key2 = datastore.newKeyFactory().kind("MyKind").newKey(keyName2); - Entity.Builder entityBuilder2 = Entity.builder(key2); + Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); + Entity.Builder entityBuilder2 = Entity.newBuilder(key2); entityBuilder2.set("propertyName", "value2"); Entity entity2 = entityBuilder2.build(); @@ -186,8 +186,8 @@ public void batchPutEntities(String keyName1, String keyName2) { // [VARIABLE "my_key_name2"] public void batchDeleteEntities(String keyName1, String keyName2) { // [START batchDeleteEntities] - Key key1 = datastore.newKeyFactory().kind("MyKind").newKey(keyName1); - Key key2 = datastore.newKeyFactory().kind("MyKind").newKey(keyName2); + Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName1); + Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey(keyName2); datastore.delete(key1, key2); // [END batchDeleteEntities] } @@ -210,7 +210,7 @@ public KeyFactory createKeyFactory() { // [VARIABLE "my_key_name"] public Entity getEntityWithKey(String keyName) { // [START getEntityWithKey] - Key key = datastore.newKeyFactory().kind("MyKind").newKey(keyName); + Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); Entity entity = datastore.get(key); // Do something with the entity // [END getEntityWithKey] @@ -226,7 +226,7 @@ public Entity getEntityWithKey(String keyName) { public List getEntitiesWithKeys(String firstKeyName, String secondKeyName) { // TODO change so that it's not necessary to hold the entities in a list for integration testing // [START getEntitiesWithKeys] - KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); Key firstKey = keyFactory.newKey(firstKeyName); Key secondKey = keyFactory.newKey(secondKeyName); Iterator entitiesIterator = datastore.get(Lists.newArrayList(firstKey, secondKey)); @@ -248,7 +248,7 @@ public List getEntitiesWithKeys(String firstKeyName, String secondKeyNam // [VARIABLE "my_second_key_name"] public List fetchEntitiesWithKeys(String firstKeyName, String secondKeyName) { // [START fetchEntitiesWithKeys] - KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); Key firstKey = keyFactory.newKey(firstKeyName); Key secondKey = keyFactory.newKey(secondKeyName); List entities = datastore.fetch(Lists.newArrayList(firstKey, secondKey)); @@ -267,8 +267,8 @@ public List fetchEntitiesWithKeys(String firstKeyName, String secondKeyN public List runQuery(String kind) { // TODO change so that it's not necessary to hold the entities in a list for integration testing // [START runQuery] - StructuredQuery query = Query.entityQueryBuilder() - .kind(kind) + StructuredQuery query = Query.newEntityQueryBuilder() + .setKind(kind) .build(); QueryResults results = datastore.run(query); List entities = Lists.newArrayList(); @@ -291,9 +291,9 @@ public List runQuery(String kind) { public List runQueryOnProperty(String kind, String property, String value) { // TODO change so that it's not necessary to hold the entities in a list for integration testing // [START runQueryOnProperty] - StructuredQuery query = Query.entityQueryBuilder() - .kind(kind) - .filter(PropertyFilter.eq(property, value)) + StructuredQuery query = Query.newEntityQueryBuilder() + .setKind(kind) + .setFilter(PropertyFilter.eq(property, value)) .build(); QueryResults results = datastore.run(query); List entities = Lists.newArrayList(); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/QuerySnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/QuerySnippets.java index b35437cbac9f..878a21629934 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/QuerySnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/QuerySnippets.java @@ -43,71 +43,148 @@ public QuerySnippets(Datastore datastore) { /** * Example of creating and running a GQL query. */ - // [TARGET gqlQueryBuilder(String)] + // [TARGET newGqlQueryBuilder(String)] // [VARIABLE "my_kind"] public QueryResults newQuery(String kind) { // [START newQuery] String gqlQuery = "select * from " + kind; - Query query = Query.gqlQueryBuilder(gqlQuery).build(); + Query query = Query.newGqlQueryBuilder(gqlQuery).build(); QueryResults results = datastore.run(query); // Use results // [END newQuery] return results; } + /** + * Example of creating and running a GQL query. + */ + // [TARGET gqlQueryBuilder(String)] + // [VARIABLE "my_kind"] + public QueryResults newQueryDeprecated(String kind) { + // [START newQueryDeprecated] + String gqlQuery = "select * from " + kind; + Query query = Query.gqlQueryBuilder(gqlQuery).build(); + QueryResults results = datastore.run(query); + // Use results + // [END newQueryDeprecated] + return results; + } + /** * Example of creating and running a typed GQL query. */ - // [TARGET gqlQueryBuilder(ResultType, String)] + // [TARGET newGqlQueryBuilder(ResultType, String)] // [VARIABLE "my_kind"] public QueryResults newTypedQuery(String kind) { // [START newTypedQuery] String gqlQuery = "select * from " + kind; - Query query = Query.gqlQueryBuilder(Query.ResultType.ENTITY, gqlQuery).build(); + Query query = Query.newGqlQueryBuilder(Query.ResultType.ENTITY, gqlQuery).build(); QueryResults results = datastore.run(query); // Use results // [END newTypedQuery] return results; } + /** + * Example of creating and running a typed GQL query. + */ + // [TARGET gqlQueryBuilder(ResultType, String)] + // [VARIABLE "my_kind"] + public QueryResults newTypedQueryDeprecated(String kind) { + // [START newTypedQueryDeprecated] + String gqlQuery = "select * from " + kind; + Query query = Query.gqlQueryBuilder(Query.ResultType.ENTITY, gqlQuery).build(); + QueryResults results = datastore.run(query); + // Use results + // [END newTypedQueryDeprecated] + return results; + } + /** * Example of creating and running an entity query. */ - // [TARGET entityQueryBuilder()] + // [TARGET newEntityQueryBuilder()] // [VARIABLE "my_kind"] public QueryResults newEntityQuery(String kind) { // [START newEntityQuery] - Query query = Query.entityQueryBuilder().kind(kind).build(); + Query query = Query.newEntityQueryBuilder().setKind(kind).build(); QueryResults results = datastore.run(query); // Use results // [END newEntityQuery] return results; } + /** + * Example of creating and running an entity query. + */ + // [TARGET entityQueryBuilder()] + // [VARIABLE "my_kind"] + public QueryResults newEntityQueryDeprecated(String kind) { + // [START newEntityQueryDeprecated] + Query query = Query.entityQueryBuilder().setKind(kind).build(); + QueryResults results = datastore.run(query); + // Use results + // [END newEntityQueryDeprecated] + return results; + } + /** * Example of creating and running a key query. */ - // [TARGET keyQueryBuilder()] + // [TARGET newKeyQueryBuilder()] // [VARIABLE "my_kind"] public QueryResults newKeyQuery(String kind) { // [START newKeyQuery] - Query query = Query.keyQueryBuilder().kind(kind).build(); + Query query = Query.newKeyQueryBuilder().setKind(kind).build(); QueryResults results = datastore.run(query); // Use results // [END newKeyQuery] return results; } + /** + * Example of creating and running a key query. + */ + // [TARGET keyQueryBuilder()] + // [VARIABLE "my_kind"] + public QueryResults newKeyQueryDeprecated(String kind) { + // [START newKeyQueryDeprecated] + Query query = Query.keyQueryBuilder().setKind(kind).build(); + QueryResults results = datastore.run(query); + // Use results + // [END newKeyQueryDeprecated] + return results; + } + /** * Example of creating and running a projection entity query. */ - // [TARGET projectionEntityQueryBuilder()] + // [TARGET newProjectionEntityQueryBuilder()] // [VARIABLE "my_kind"] // [VARIABLE "my_property"] public QueryResults newProjectionEntityQuery(String kind, String property) { // [START newProjectionEntityQuery] + Query query = Query.newProjectionEntityQueryBuilder() + .setKind(kind) + .addProjection(property) + .build(); + QueryResults results = datastore.run(query); + // Use results + // [END newProjectionEntityQuery] + return results; + } + + /** + * Example of creating and running a projection entity query. + */ + // [TARGET projectionEntityQueryBuilder()] + // [VARIABLE "my_kind"] + // [VARIABLE "my_property"] + public QueryResults newProjectionEntityQueryDeprecated(String kind, + String property) { + // [START newProjectionEntityQuery] Query query = Query.projectionEntityQueryBuilder() - .kind(kind) + .setKind(kind) .addProjection(property) .build(); QueryResults results = datastore.run(query); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/TransactionSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/TransactionSnippets.java index eb6b5d4afdd4..07b5577759b2 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/TransactionSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/TransactionSnippets.java @@ -53,9 +53,9 @@ public TransactionSnippets(Transaction transaction) { // [TARGET get(Key)] // [VARIABLE "my_key_name"] public Entity get(String keyName) { - Datastore datastore = transaction.datastore(); + Datastore datastore = transaction.getDatastore(); // [START get] - Key key = datastore.newKeyFactory().kind("MyKind").newKey(keyName); + Key key = datastore.newKeyFactory().setKind("MyKind").newKey(keyName); Entity entity = transaction.get(key); transaction.commit(); // Do something with the entity @@ -70,10 +70,10 @@ public Entity get(String keyName) { // [VARIABLE "my_first_key_name"] // [VARIABLE "my_second_key_name"] public List getMultiple(String firstKeyName, String secondKeyName) { - Datastore datastore = transaction.datastore(); + Datastore datastore = transaction.getDatastore(); // TODO change so that it's not necessary to hold the entities in a list for integration testing // [START getMultiple] - KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); Key firstKey = keyFactory.newKey(firstKeyName); Key secondKey = keyFactory.newKey(secondKeyName); Iterator entitiesIterator = transaction.get(firstKey, secondKey); @@ -95,9 +95,9 @@ public List getMultiple(String firstKeyName, String secondKeyName) { // [VARIABLE "my_first_key_name"] // [VARIABLE "my_second_key_name"] public List fetchEntitiesWithKeys(String firstKeyName, String secondKeyName) { - Datastore datastore = transaction.datastore(); + Datastore datastore = transaction.getDatastore(); // [START fetchEntitiesWithKeys] - KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); Key firstKey = keyFactory.newKey(firstKeyName); Key secondKey = keyFactory.newKey(secondKeyName); List entities = transaction.fetch(firstKey, secondKey); @@ -115,14 +115,14 @@ public List fetchEntitiesWithKeys(String firstKeyName, String secondKeyN // [TARGET run(Query)] // [VARIABLE "my_parent_key_name"] public List run(String parentKeyName) { - Datastore datastore = transaction.datastore(); + Datastore datastore = transaction.getDatastore(); // [START run] - KeyFactory keyFactory = datastore.newKeyFactory().kind("ParentKind"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("ParentKind"); Key parentKey = keyFactory.newKey(parentKeyName); // Build a query - Query query = Query.entityQueryBuilder() - .kind("MyKind") - .filter(PropertyFilter.hasAncestor(parentKey)) + Query query = Query.newEntityQueryBuilder() + .setKind("MyKind") + .setFilter(PropertyFilter.hasAncestor(parentKey)) .build(); QueryResults results = transaction.run(query); List entities = Lists.newArrayList(); @@ -141,12 +141,12 @@ public List run(String parentKeyName) { */ // [TARGET commit()] public Key commit() { - Datastore datastore = transaction.datastore(); + Datastore datastore = transaction.getDatastore(); // [START commit] // create an entity - KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); Key key = datastore.allocateId(keyFactory.newKey()); - Entity entity = Entity.builder(key).set("description", "commit()").build(); + Entity entity = Entity.newBuilder(key).set("description", "commit()").build(); // add the entity and commit try { @@ -165,12 +165,12 @@ public Key commit() { */ // [TARGET rollback()] public Key rollback() { - Datastore datastore = transaction.datastore(); + Datastore datastore = transaction.getDatastore(); // [START rollback] // create an entity - KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); Key key = datastore.allocateId(keyFactory.newKey()); - Entity entity = Entity.builder(key).set("description", "rollback()").build(); + Entity entity = Entity.newBuilder(key).set("description", "rollback()").build(); // add the entity and rollback transaction.put(entity); @@ -185,12 +185,12 @@ public Key rollback() { */ // [TARGET active()] public Key active() { - Datastore datastore = transaction.datastore(); + Datastore datastore = transaction.getDatastore(); // [START active] // create an entity - KeyFactory keyFactory = datastore.newKeyFactory().kind("MyKind"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); Key key = datastore.allocateId(keyFactory.newKey()); - Entity entity = Entity.builder(key).set("description", "active()").build(); + Entity entity = Entity.newBuilder(key).set("description", "active()").build(); // calling transaction.active() now would return true try { // add the entity and commit @@ -207,4 +207,32 @@ public Key active() { // [END active] return key; } + + /** + * Example of verifying if a transaction is active. + */ + // [TARGET isActive()] + public Key isActive() { + Datastore datastore = transaction.getDatastore(); + // [START isActive] + // create an entity + KeyFactory keyFactory = datastore.newKeyFactory().setKind("MyKind"); + Key key = datastore.allocateId(keyFactory.newKey()); + Entity entity = Entity.newBuilder(key).set("description", "active()").build(); + // calling transaction.active() now would return true + try { + // add the entity and commit + transaction.put(entity); + transaction.commit(); + } finally { + // if committing succeeded + // then transaction.active() will be false + if (transaction.isActive()) { + // otherwise it's true and we need to rollback + transaction.rollback(); + } + } + // [END isActive] + return key; + } } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/UpdateEntity.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/UpdateEntity.java index 79cb6e8b9a5e..ce423b2535c4 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/UpdateEntity.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/UpdateEntity.java @@ -36,12 +36,12 @@ public class UpdateEntity { public static void main(String... args) { Datastore datastore = DatastoreOptions.defaultInstance().service(); - KeyFactory keyFactory = datastore.newKeyFactory().kind("keyKind"); + KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind"); Key key = keyFactory.newKey("keyName"); Entity entity = datastore.get(key); if (entity != null) { System.out.println("Updating access_time for " + entity.getString("name")); - entity = Entity.builder(entity) + entity = Entity.newBuilder(entity) .set("access_time", DateTime.now()) .build(); datastore.update(entity); diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITDatastoreSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITDatastoreSnippets.java index 9aef5a2f2d8d..c071f89547e7 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITDatastoreSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITDatastoreSnippets.java @@ -69,22 +69,22 @@ private String registerKey(String keyName) { } private String registerKey(String keyName, String kind) { - Key key = datastore.newKeyFactory().kind(kind).newKey(keyName); + Key key = datastore.newKeyFactory().setKind(kind).newKey(keyName); registeredKeys.add(key); - return key.name(); + return key.getName(); } private Map createEntityMap(List entities) { Map entityMap = new HashMap<>(); for (Entity entity : entities) { - entityMap.put(entity.key().name(), entity); + entityMap.put(entity.getKey().getName(), entity); } return entityMap; } private void addEntity(String keyName, String keyClass, String property, String value) { - Key key = datastore.newKeyFactory().kind(keyClass).newKey(keyName); - Entity.Builder entityBuilder = Entity.builder(key); + Key key = datastore.newKeyFactory().setKind(keyClass).newKey(keyName); + Entity.Builder entityBuilder = Entity.newBuilder(key); entityBuilder.set(property, value); Entity entity = entityBuilder.build(); datastore.put(entity); diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITQuerySnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITQuerySnippets.java index d735c12c1f75..bb1ee6782e18 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITQuerySnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITQuerySnippets.java @@ -55,16 +55,16 @@ public String apply(ProjectionEntity entity) { @BeforeClass public static void beforeClass() { datastore = DatastoreOptions.defaultInstance().service(); - Key key1 = Key.builder(datastore.options().projectId(), KIND, "key1").build(); - Key key2 = Key.builder(datastore.options().projectId(), KIND, "key2").build(); - entity1 = Entity.builder(key1).set("description", "entity1").build(); - entity2 = Entity.builder(key2).set("description", "entity2").build(); + Key key1 = Key.newBuilder(datastore.options().projectId(), KIND, "key1").build(); + Key key2 = Key.newBuilder(datastore.options().projectId(), KIND, "key2").build(); + entity1 = Entity.newBuilder(key1).set("description", "entity1").build(); + entity2 = Entity.newBuilder(key2).set("description", "entity2").build(); datastore.put(entity1, entity2); } @AfterClass public static void afterClass() { - datastore.delete(entity1.key(), entity2.key()); + datastore.delete(entity1.getKey(), entity2.getKey()); } @Test @@ -78,6 +78,17 @@ public void testNewQuery() throws InterruptedException { } } + @Test + public void testNewQueryDeprecated() throws InterruptedException { + QuerySnippets transactionSnippets = new QuerySnippets(datastore); + QueryResults results = transactionSnippets.newQueryDeprecated(KIND); + Set resultSet = Sets.newHashSet(results); + while (!resultSet.contains(entity1) || !resultSet.contains(entity2)) { + Thread.sleep(500); + resultSet = Sets.newHashSet(results); + } + } + @Test public void testNewTypedQuery() throws InterruptedException { QuerySnippets transactionSnippets = new QuerySnippets(datastore); @@ -89,6 +100,17 @@ public void testNewTypedQuery() throws InterruptedException { } } + @Test + public void testNewTypedQueryDeprecated() throws InterruptedException { + QuerySnippets transactionSnippets = new QuerySnippets(datastore); + QueryResults results = transactionSnippets.newTypedQueryDeprecated(KIND); + Set resultSet = Sets.newHashSet(results); + while (!resultSet.contains(entity1) || !resultSet.contains(entity2)) { + Thread.sleep(500); + resultSet = Sets.newHashSet(results); + } + } + @Test public void testNewEntityQuery() throws InterruptedException { QuerySnippets transactionSnippets = new QuerySnippets(datastore); @@ -105,7 +127,18 @@ public void testNewKeyQuery() throws InterruptedException { QuerySnippets transactionSnippets = new QuerySnippets(datastore); QueryResults results = transactionSnippets.newKeyQuery(KIND); Set resultSet = Sets.newHashSet(results); - while (!resultSet.contains(entity1.key()) || !resultSet.contains(entity2.key())) { + while (!resultSet.contains(entity1.getKey()) || !resultSet.contains(entity2.getKey())) { + Thread.sleep(500); + resultSet = Sets.newHashSet(results); + } + } + + @Test + public void testNewKeyQueryDeprecated() throws InterruptedException { + QuerySnippets transactionSnippets = new QuerySnippets(datastore); + QueryResults results = transactionSnippets.newKeyQueryDeprecated(KIND); + Set resultSet = Sets.newHashSet(results); + while (!resultSet.contains(entity1.getKey()) || !resultSet.contains(entity2.getKey())) { Thread.sleep(500); resultSet = Sets.newHashSet(results); } @@ -124,4 +157,18 @@ public void testNewProjectionEntityQuery() throws InterruptedException { resultSet = Sets.newHashSet(Iterators.transform(results, ENTITY_TO_DESCRIPTION_FUNCTION)); } } + + @Test + public void testNewProjectionEntityQueryDeprecated() throws InterruptedException { + QuerySnippets transactionSnippets = new QuerySnippets(datastore); + QueryResults results = + transactionSnippets.newProjectionEntityQueryDeprecated(KIND, "description"); + Set resultSet = + Sets.newHashSet(Iterators.transform(results, ENTITY_TO_DESCRIPTION_FUNCTION)); + while (!resultSet.contains(entity1.getString("description")) + || !resultSet.contains(entity2.getString("description"))) { + Thread.sleep(500); + resultSet = Sets.newHashSet(Iterators.transform(results, ENTITY_TO_DESCRIPTION_FUNCTION)); + } + } } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITTransactionSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITTransactionSnippets.java index 07492ffa2d27..418c50e84dd0 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITTransactionSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITTransactionSnippets.java @@ -45,7 +45,7 @@ public class ITTransactionSnippets { private String registerKey(Key key) { registeredKeys.add(key); - return key.name(); + return key.getName(); } private String registerKey(String keyName) { @@ -53,9 +53,9 @@ private String registerKey(String keyName) { } private String registerKey(String keyName, String kind) { - Key key = datastore.newKeyFactory().kind(kind).newKey(keyName); + Key key = datastore.newKeyFactory().setKind(kind).newKey(keyName); registeredKeys.add(key); - return key.name(); + return key.getName(); } @BeforeClass @@ -70,8 +70,8 @@ public void afterTest() { @Test public void testGet() { - Key key1 = datastore.newKeyFactory().kind("MyKind").newKey("fetch_key_1"); - Entity entity1 = Entity.builder(key1).set("description", "fetch1").build(); + Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey("fetch_key_1"); + Entity entity1 = Entity.newBuilder(key1).set("description", "fetch1").build(); datastore.put(entity1); registerKey("fetch_key_1"); @@ -82,10 +82,10 @@ public void testGet() { @Test public void testGetMultiple() { - Key key1 = datastore.newKeyFactory().kind("MyKind").newKey("fetch_key_1"); - Key key2 = datastore.newKeyFactory().kind("MyKind").newKey("fetch_key_2"); - Entity entity1 = Entity.builder(key1).set("description", "fetch1").build(); - Entity entity2 = Entity.builder(key2).set("description", "fetch2").build(); + Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey("fetch_key_1"); + Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey("fetch_key_2"); + Entity entity1 = Entity.newBuilder(key1).set("description", "fetch1").build(); + Entity entity2 = Entity.newBuilder(key2).set("description", "fetch2").build(); datastore.put(entity1, entity2); registerKey("fetch_key_1"); registerKey("fetch_key_2"); @@ -101,10 +101,10 @@ public void testGetMultiple() { @Test public void testFetchEntitiesWithKeys() { - Key key1 = datastore.newKeyFactory().kind("MyKind").newKey("fetch_key_1"); - Key key2 = datastore.newKeyFactory().kind("MyKind").newKey("fetch_key_2"); - Entity entity1 = Entity.builder(key1).set("description", "fetch1").build(); - Entity entity2 = Entity.builder(key2).set("description", "fetch2").build(); + Key key1 = datastore.newKeyFactory().setKind("MyKind").newKey("fetch_key_1"); + Key key2 = datastore.newKeyFactory().setKind("MyKind").newKey("fetch_key_2"); + Entity entity1 = Entity.newBuilder(key1).set("description", "fetch1").build(); + Entity entity2 = Entity.newBuilder(key2).set("description", "fetch2").build(); datastore.put(entity1, entity2); registerKey("fetch_key_1"); registerKey("fetch_key_2"); @@ -120,17 +120,17 @@ public void testFetchEntitiesWithKeys() { @Test public void testRun() { - Key key1 = datastore.newKeyFactory().kind("ParentKind").newKey("run_key_1"); - Entity entity1 = Entity.builder(key1).set("description", "run1").build(); + Key key1 = datastore.newKeyFactory().setKind("ParentKind").newKey("run_key_1"); + Entity entity1 = Entity.newBuilder(key1).set("description", "run1").build(); datastore.put(entity1); Key key2 = datastore .newKeyFactory() - .kind("MyKind") - .ancestors(PathElement.of("ParentKind", "run_key_1")) + .setKind("MyKind") + .addAncestor(PathElement.of("ParentKind", "run_key_1")) .newKey("run_key_2"); registerKey(key1); registerKey(key2); - Entity entity2 = Entity.builder(key2).set("description", "run2").build(); + Entity entity2 = Entity.newBuilder(key2).set("description", "run2").build(); datastore.put(entity2); Transaction transaction = datastore.newTransaction(); @@ -168,4 +168,14 @@ public void testActive() { assertNotNull(result); datastore.delete(key); } + + @Test + public void testIsActive() { + Transaction transaction = datastore.newTransaction(); + TransactionSnippets transactionSnippets = new TransactionSnippets(transaction); + Key key = transactionSnippets.isActive(); + Entity result = datastore.get(key); + assertNotNull(result); + datastore.delete(key); + } } From 307f9f0457817d094734c3d1dd929b82b49883a2 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Thu, 20 Oct 2016 16:24:54 +0200 Subject: [PATCH 12/32] Rename setters/getters/builders for Dns classes to meet proto conventions (#1316) * Rename setters/getters/builders for Dns classes to meet proto conventions * Update Dns examples, snippets and READMEs to use renamed getters/setters/builders --- README.md | 10 +- TESTING.md | 5 +- google-cloud-dns/README.md | 26 +- .../com/google/cloud/dns/ChangeRequest.java | 44 +- .../google/cloud/dns/ChangeRequestInfo.java | 116 +- .../java/com/google/cloud/dns/DnsBatch.java | 6 +- .../java/com/google/cloud/dns/DnsImpl.java | 2 +- .../java/com/google/cloud/dns/Option.java | 4 +- .../com/google/cloud/dns/ProjectInfo.java | 85 +- .../java/com/google/cloud/dns/RecordSet.java | 98 +- .../main/java/com/google/cloud/dns/Zone.java | 60 +- .../java/com/google/cloud/dns/ZoneInfo.java | 154 +- .../com/google/cloud/dns/package-info.java | 6 +- .../cloud/dns/testing/LocalDnsHelper.java | 9 + .../cloud/dns/ChangeRequestInfoTest.java | 137 +- .../google/cloud/dns/ChangeRequestTest.java | 59 +- .../com/google/cloud/dns/DnsBatchTest.java | 78 +- .../com/google/cloud/dns/DnsImplTest.java | 121 +- .../java/com/google/cloud/dns/DnsTest.java | 96 +- .../java/com/google/cloud/dns/OptionTest.java | 8 +- .../com/google/cloud/dns/ProjectInfoTest.java | 70 +- .../com/google/cloud/dns/RecordSetTest.java | 113 +- .../google/cloud/dns/SerializationTest.java | 44 +- .../com/google/cloud/dns/ZoneInfoTest.java | 70 +- .../java/com/google/cloud/dns/ZoneTest.java | 109 +- .../com/google/cloud/dns/it/ITDnsTest.java | 1460 +++++++++-------- .../cloud/dns/testing/LocalDnsHelperTest.java | 4 +- .../google/cloud/examples/dns/DnsExample.java | 62 +- .../snippets/CreateOrUpdateRecordSets.java | 9 +- .../examples/dns/snippets/CreateZone.java | 2 +- .../examples/dns/snippets/DeleteZone.java | 7 +- .../ManipulateZonesAndRecordSets.java | 26 +- 32 files changed, 1846 insertions(+), 1254 deletions(-) diff --git a/README.md b/README.md index 28b7b9a91848..6ce14f2c6447 100644 --- a/README.md +++ b/README.md @@ -359,19 +359,19 @@ Dns dns = DnsOptions.defaultInstance().service(); String zoneName = "my-unique-zone"; Zone zone = dns.getZone(zoneName); String ip = "12.13.14.15"; -RecordSet toCreate = RecordSet.builder("www.someexampledomain.com.", RecordSet.Type.A) - .ttl(24, TimeUnit.HOURS) +RecordSet toCreate = RecordSet.newBuilder("www.someexampledomain.com.", RecordSet.Type.A) + .setTtl(24, TimeUnit.HOURS) .addRecord(ip) .build(); -ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder().add(toCreate); +ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.newBuilder().add(toCreate); // Verify that the record does not exist yet. // If it does exist, we will overwrite it with our prepared record. Iterator recordSetIterator = zone.listRecordSets().iterateAll(); while (recordSetIterator.hasNext()) { RecordSet current = recordSetIterator.next(); - if (toCreate.name().equals(current.name()) && - toCreate.type().equals(current.type())) { + if (toCreate.name().equals(current.getName()) && + toCreate.type().equals(current.getType())) { changeBuilder.delete(current); } } diff --git a/TESTING.md b/TESTING.md index a2439fdb04f1..d3a0b18c1247 100644 --- a/TESTING.md +++ b/TESTING.md @@ -131,10 +131,11 @@ You can test against an in-memory local DNS by following these steps: The `delay` parameter determines if change requests should be processed synchronously (value `0`) or in a separate thread with a minimum of delay of `delay` milliseconds. -2. In your program, create the DNS service by using the helper's `options()` method. For example: +2. In your program, create the DNS service by using the helper's `getOptions()` method. +For example: ```java - Dns dns = LocalDnsHelper.options().service(); + Dns dns = LocalDnsHelper.getOptions().service(); ``` 3. Run your tests. diff --git a/google-cloud-dns/README.md b/google-cloud-dns/README.md index 2e6b8dba17d6..ebd986d74b31 100644 --- a/google-cloud-dns/README.md +++ b/google-cloud-dns/README.md @@ -125,7 +125,7 @@ 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.generatedId()); +System.out.printf("Zone was created and assigned ID %s.%n", zone.getGeneratedId()); ``` You now have an empty zone hosted in Google Cloud DNS which is ready to be populated with @@ -142,7 +142,7 @@ and then add ```java // Print assigned name servers -List nameServers = zone.nameServers(); +List nameServers = zone.getNameServers(); for(String nameServer : nameServers) { System.out.println(nameServer); } @@ -170,13 +170,13 @@ and proceed with: ```java // Prepare a www.someexampledomain.com. type A record set with ttl of 24 hours String ip = "12.13.14.15"; -RecordSet toCreate = RecordSet.builder("www." + zone.dnsName(), RecordSet.Type.A) - .ttl(24, TimeUnit.HOURS) +RecordSet toCreate = RecordSet.newBuilder("www." + zone.dnsName(), RecordSet.Type.A) + .setTtl(24, TimeUnit.HOURS) .addRecord(ip) .build(); // Make a change -ChangeRequestInfo changeRequest = ChangeRequestInfo.builder().add(toCreate).build(); +ChangeRequestInfo changeRequest = ChangeRequestInfo.newBuilder().add(toCreate).build(); // Build and apply the change request to our zone changeRequest = zone.applyChangeRequest(changeRequest); @@ -205,7 +205,8 @@ ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder().add(toCrea Iterator recordSetIterator = zone.listRecordSets().iterateAll(); while (recordSetIterator.hasNext()) { RecordSet current = recordSetIterator.next(); - if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) { + if (toCreate.getName().equals(current.getName()) + && toCreate.getType().equals(current.getType())) { changeBuilder.delete(current); } } @@ -255,7 +256,7 @@ while (zoneIterator.hasNext()) { // List the record sets in a particular zone recordSetIterator = zone.listRecordSets().iterateAll(); -System.out.println(String.format("Record sets inside %s:", zone.name())); +System.out.println(String.format("Record sets inside %s:", zone.getName())); while (recordSetIterator.hasNext()) { System.out.println(recordSetIterator.next()); } @@ -274,7 +275,7 @@ and then: // 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())); +System.out.println(String.format("The history of changes in %s:", zone.getName())); while (changeIterator.hasNext()) { System.out.println(changeIterator.next()); } @@ -287,18 +288,19 @@ 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 = ChangeRequestInfo.builder(); +changeBuilder = ChangeRequestInfo.newBuilder(); while (recordIterator.hasNext()) { RecordSet current = recordIterator.next(); // SOA and NS records cannot be deleted - if (!RecordSet.Type.SOA.equals(current.type()) && !RecordSet.Type.NS.equals(current.type())) { + if (!RecordSet.Type.SOA.equals(current.getType()) + && !RecordSet.Type.NS.equals(current.getType())) { changeBuilder.delete(current); } } // Build and apply the change request to our zone if it contains records to delete ChangeRequestInfo changeRequest = changeBuilder.build(); -if (!changeRequest.deletions().isEmpty()) { +if (!changeRequest.getDeletions().isEmpty()) { ChangeRequest pendingRequest = dns.applyChangeRequest(zoneName, changeRequest); // Wait for the change request to complete @@ -325,7 +327,7 @@ if (result) { #### Complete Source Code We composed some of the aforementioned snippets into complete executable code samples. In -[CreateZones.java](../google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateZone.java) +[CreateZone.java](../google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateZone.java) we create a zone. In [CreateOrUpdateRecordSets.java](../google-cloud-examples/src/main/java/com/google/cloud/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](../google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/DeleteZone.java). diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequest.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequest.java index 267acf199b87..d7ed6ef02dd2 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequest.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequest.java @@ -55,14 +55,26 @@ private Builder(ChangeRequest cr) { } @Override + @Deprecated public Builder additions(List additions) { - infoBuilder.additions(additions); + return setAdditions(additions); + } + + @Override + public Builder setAdditions(List additions) { + infoBuilder.setAdditions(additions); return this; } @Override + @Deprecated public Builder deletions(List deletions) { - infoBuilder.deletions(deletions); + return setDeletions(deletions); + } + + @Override + public Builder setDeletions(List deletions) { + infoBuilder.setDeletions(deletions); return this; } @@ -103,20 +115,20 @@ public Builder removeDeletion(RecordSet recordSet) { } @Override - Builder generatedId(String generatedId) { - infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + infoBuilder.setGeneratedId(generatedId); return this; } @Override - Builder startTimeMillis(long startTimeMillis) { - infoBuilder.startTimeMillis(startTimeMillis); + Builder setStartTime(long startTimeMillis) { + infoBuilder.setStartTime(startTimeMillis); return this; } @Override - Builder status(Status status) { - infoBuilder.status(status); + Builder setStatus(Status status) { + infoBuilder.setStatus(status); return this; } @@ -137,6 +149,13 @@ public ChangeRequest build() { * Returns the name of the {@link Zone} associated with this change request. */ public String zone() { + return getZone(); + } + + /** + * Returns the name of the {@link Zone} associated with this change request. + */ + public String getZone() { return this.zone; } @@ -144,6 +163,13 @@ public String zone() { * Returns the change request's {@code Dns} object used to issue requests. */ public Dns dns() { + return getDns(); + } + + /** + * Returns the change request's {@code Dns} object used to issue requests. + */ + public Dns getDns() { return dns; } @@ -168,7 +194,7 @@ public ChangeRequest applyTo(String zoneName, Dns.ChangeRequestOption... options * @throws DnsException upon failure of the API call or if the associated zone was not found */ public ChangeRequest reload(Dns.ChangeRequestOption... options) { - return dns.getChangeRequest(zone, generatedId(), options); + return dns.getChangeRequest(zone, getGeneratedId(), options); } /** diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequestInfo.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequestInfo.java index 8ed68765a163..78a529c1e8e6 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequestInfo.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequestInfo.java @@ -74,14 +74,28 @@ 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}. */ + @Deprecated public abstract Builder additions(List additions); + /** + * Sets a collection of {@link RecordSet}s which are to be added to the zone upon executing this + * {@code ChangeRequestInfo}. + */ + public abstract Builder setAdditions(List additions); + /** * Sets a collection of {@link RecordSet}s which are to be deleted from the zone upon executing * this {@code ChangeRequestInfo}. */ + @Deprecated public abstract Builder deletions(List deletions); + /** + * Sets a collection of {@link RecordSet}s which are to be deleted from the zone upon executing + * this {@code ChangeRequestInfo}. + */ + public abstract Builder setDeletions(List deletions); + /** * Adds a {@link RecordSet} to be added to the zone upon executing this {@code * ChangeRequestInfo}. @@ -121,17 +135,17 @@ public abstract static class Builder { /** * Associates a service-generated id to this {@code ChangeRequestInfo}. */ - abstract Builder generatedId(String generatedId); + abstract Builder setGeneratedId(String generatedId); /** * Sets the time when this change request was started by a server. */ - abstract Builder startTimeMillis(long startTimeMillis); + abstract Builder setStartTime(long startTimeMillis); /** * Sets the current status of this {@code ChangeRequest}. */ - abstract Builder status(ChangeRequest.Status status); + abstract Builder setStatus(ChangeRequest.Status status); /** * Creates a {@code ChangeRequestInfo} instance populated by the values associated with this @@ -153,21 +167,33 @@ static class BuilderImpl extends Builder { } BuilderImpl(ChangeRequestInfo info) { - this.additions = Lists.newLinkedList(info.additions()); - this.deletions = Lists.newLinkedList(info.deletions()); + this.additions = Lists.newLinkedList(info.getAdditions()); + this.deletions = Lists.newLinkedList(info.getDeletions()); this.generatedId = info.generatedId; this.startTimeMillis = info.startTimeMillis; this.status = info.status; } @Override + @Deprecated public Builder additions(List additions) { + return setAdditions(additions); + } + + @Override + public Builder setAdditions(List additions) { this.additions = Lists.newLinkedList(checkNotNull(additions)); return this; } @Override + @Deprecated public Builder deletions(List deletions) { + return setDeletions(deletions); + } + + @Override + public Builder setDeletions(List deletions) { this.deletions = Lists.newLinkedList(checkNotNull(deletions)); return this; } @@ -214,19 +240,19 @@ public ChangeRequestInfo build() { } @Override - Builder generatedId(String generatedId) { + Builder setGeneratedId(String generatedId) { this.generatedId = checkNotNull(generatedId); return this; } @Override - Builder startTimeMillis(long startTimeMillis) { + Builder setStartTime(long startTimeMillis) { this.startTimeMillis = startTimeMillis; return this; } @Override - Builder status(ChangeRequestInfo.Status status) { + Builder setStatus(ChangeRequestInfo.Status status) { this.status = checkNotNull(status); return this; } @@ -243,7 +269,15 @@ Builder status(ChangeRequestInfo.Status status) { /** * Returns an empty builder for the {@code ChangeRequestInfo} class. */ + @Deprecated public static Builder builder() { + return newBuilder(); + } + + /** + * Returns an empty builder for the {@code ChangeRequestInfo} class. + */ + public static Builder newBuilder() { return new BuilderImpl(); } @@ -258,7 +292,16 @@ public Builder toBuilder() { * Returns the list of {@link RecordSet}s to be added to the zone upon submitting this change * request. */ + @Deprecated public List additions() { + return getAdditions(); + } + + /** + * Returns the list of {@link RecordSet}s to be added to the zone upon submitting this change + * request. + */ + public List getAdditions() { return additions; } @@ -266,21 +309,46 @@ public List additions() { * Returns the list of {@link RecordSet}s to be deleted from the zone upon submitting this change * request. */ + @Deprecated public List deletions() { + return getDeletions(); + } + + /** + * Returns the list of {@link RecordSet}s to be deleted from the zone upon submitting this change + * request. + */ + public List getDeletions() { return deletions; } /** * Returns the service-generated id for this change request. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated id for this change request. + */ + public String getGeneratedId() { return generatedId; } /** * Returns the time when this change request was started by the server. */ + @Deprecated public Long startTimeMillis() { + return getStartTimeMillis(); + } + + /** + * Returns the time when this change request was started by the server. + */ + public Long getStartTimeMillis() { return startTimeMillis; } @@ -289,47 +357,55 @@ public Long startTimeMillis() { * status is {@code PENDING}. */ public ChangeRequestInfo.Status status() { + return getStatus(); + } + + /** + * Returns the status of this change request. If the change request has not been applied yet, the + * status is {@code PENDING}. + */ + public ChangeRequestInfo.Status getStatus() { return status; } Change toPb() { Change pb = new Change(); // set id - if (generatedId() != null) { - pb.setId(generatedId()); + if (getGeneratedId() != null) { + pb.setId(getGeneratedId()); } // set timestamp - if (startTimeMillis() != null) { - pb.setStartTime(ISODateTimeFormat.dateTime().withZoneUTC().print(startTimeMillis())); + if (getStartTimeMillis() != null) { + pb.setStartTime(ISODateTimeFormat.dateTime().withZoneUTC().print(getStartTimeMillis())); } // set status if (status() != null) { pb.setStatus(status().name().toLowerCase()); } // set a list of additions - pb.setAdditions(Lists.transform(additions(), RecordSet.TO_PB_FUNCTION)); + pb.setAdditions(Lists.transform(getAdditions(), RecordSet.TO_PB_FUNCTION)); // set a list of deletions - pb.setDeletions(Lists.transform(deletions(), RecordSet.TO_PB_FUNCTION)); + pb.setDeletions(Lists.transform(getDeletions(), RecordSet.TO_PB_FUNCTION)); return pb; } static ChangeRequestInfo fromPb(Change pb) { - Builder builder = builder(); + Builder builder = newBuilder(); if (pb.getId() != null) { - builder.generatedId(pb.getId()); + builder.setGeneratedId(pb.getId()); } if (pb.getStartTime() != null) { - builder.startTimeMillis(DateTime.parse(pb.getStartTime()).getMillis()); + builder.setStartTime(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())); + builder.setStatus(ChangeRequest.Status.valueOf(pb.getStatus().toUpperCase())); } if (pb.getDeletions() != null) { - builder.deletions(Lists.transform(pb.getDeletions(), RecordSet.FROM_PB_FUNCTION)); + builder.setDeletions(Lists.transform(pb.getDeletions(), RecordSet.FROM_PB_FUNCTION)); } if (pb.getAdditions() != null) { - builder.additions(Lists.transform(pb.getAdditions(), RecordSet.FROM_PB_FUNCTION)); + builder.setAdditions(Lists.transform(pb.getAdditions(), RecordSet.FROM_PB_FUNCTION)); } return builder.build(); } diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsBatch.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsBatch.java index 8037b6b28ce2..b1fa7165aeaa 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsBatch.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsBatch.java @@ -53,17 +53,17 @@ public class DnsBatch { } @VisibleForTesting - Object batch() { + Object getBatch() { return batch; } @VisibleForTesting - DnsRpc dnsRpc() { + DnsRpc getDnsRpc() { return dnsRpc; } @VisibleForTesting - DnsOptions options() { + DnsOptions getOptions() { return options; } diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsImpl.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsImpl.java index 1bf2a0c1d8cb..abcacf0521e6 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsImpl.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsImpl.java @@ -315,7 +315,7 @@ public DnsBatch batch() { static Map optionMap(Option... options) { Map temp = Maps.newEnumMap(DnsRpc.Option.class); for (Option option : options) { - Object prev = temp.put(option.rpcOption(), option.value()); + Object prev = temp.put(option.getRpcOption(), option.getValue()); checkArgument(prev == null, "Duplicate option %s", option); } return ImmutableMap.copyOf(temp); diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/Option.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/Option.java index 7a1f9955be05..a2429c3578f6 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/Option.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/Option.java @@ -38,11 +38,11 @@ abstract class Option implements Serializable { this.value = value; } - Object value() { + Object getValue() { return value; } - DnsRpc.Option rpcOption() { + DnsRpc.Option getRpcOption() { return rpcOption; } diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/ProjectInfo.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/ProjectInfo.java index bc35bacc317d..cf49fada0b77 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/ProjectInfo.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/ProjectInfo.java @@ -79,14 +79,30 @@ public static class Quota implements Serializable { /** * Returns the maximum allowed number of zones in the project. */ + @Deprecated public int zones() { + return getZones(); + } + + /** + * Returns the maximum allowed number of zones in the project. + */ + public int getZones() { return zones; } /** * Returns the maximum allowed number of records per {@link RecordSet}. */ + @Deprecated public int resourceRecordsPerRrset() { + return getResourceRecordsPerRrset(); + } + + /** + * Returns the maximum allowed number of records per {@link RecordSet}. + */ + public int getResourceRecordsPerRrset() { return resourceRecordsPerRrset; } @@ -94,7 +110,16 @@ public int resourceRecordsPerRrset() { * Returns the maximum allowed number of {@link RecordSet}s to add per {@link * ChangeRequest}. */ + @Deprecated public int rrsetAdditionsPerChange() { + return getRrsetAdditionsPerChange(); + } + + /** + * Returns the maximum allowed number of {@link RecordSet}s to add per {@link + * ChangeRequest}. + */ + public int getRrsetAdditionsPerChange() { return rrsetAdditionsPerChange; } @@ -102,7 +127,16 @@ public int rrsetAdditionsPerChange() { * Returns the maximum allowed number of {@link RecordSet}s to delete per {@link * ChangeRequest}. */ + @Deprecated public int rrsetDeletionsPerChange() { + return getRrsetDeletionsPerChange(); + } + + /** + * Returns the maximum allowed number of {@link RecordSet}s to delete per {@link + * ChangeRequest}. + */ + public int getRrsetDeletionsPerChange() { return rrsetDeletionsPerChange; } @@ -110,14 +144,31 @@ public int rrsetDeletionsPerChange() { * Returns the maximum allowed number of {@link RecordSet}s per {@link ZoneInfo} in the * project. */ + @Deprecated public int rrsetsPerZone() { + return getRrsetsPerZone(); + } + + /** + * Returns the maximum allowed number of {@link RecordSet}s per {@link ZoneInfo} in the + * project. + */ + public int getRrsetsPerZone() { return rrsetsPerZone; } /** * Returns the maximum allowed size for total records in one ChangesRequest in bytes. */ + @Deprecated public int totalRrdataSizePerChange() { + return getTotalRrdataSizePerChange(); + } + + /** + * Returns the maximum allowed size for total records in one ChangesRequest in bytes. + */ + public int getTotalRrdataSizePerChange() { return totalRrdataSizePerChange; } @@ -180,7 +231,7 @@ private Builder() { /** * Sets an id of the project. */ - Builder id(String id) { + Builder setId(String id) { this.id = checkNotNull(id); return this; } @@ -188,7 +239,7 @@ Builder id(String id) { /** * Sets a number of the project. */ - Builder number(BigInteger number) { + Builder setNumber(BigInteger number) { this.number = checkNotNull(number); return this; } @@ -196,7 +247,7 @@ Builder number(BigInteger number) { /** * Sets quotas assigned to the project. */ - Builder quota(Quota quota) { + Builder setQuota(Quota quota) { this.quota = checkNotNull(quota); return this; } @@ -218,28 +269,44 @@ private ProjectInfo(Builder builder) { /** * Returns a builder for {@code ProjectInfo}. */ - static Builder builder() { + static Builder newBuilder() { return new Builder(); } /** * Returns the {@code Quota} object which contains quotas assigned to this project. */ + @Deprecated public Quota quota() { + return getQuota(); + } + + /** + * Returns the {@code Quota} object which contains quotas assigned to this project. + */ + public Quota getQuota() { return quota; } /** * Returns project number. For internal use only. */ - BigInteger number() { + BigInteger getNumber() { return number; } /** * Returns project id. For internal use only. */ + @Deprecated String id() { + return getId(); + } + + /** + * Returns project id. For internal use only. + */ + String getId() { return id; } @@ -254,15 +321,15 @@ Project toPb() { } static ProjectInfo fromPb(Project pb) { - Builder builder = builder(); + Builder builder = newBuilder(); if (pb.getId() != null) { - builder.id(pb.getId()); + builder.setId(pb.getId()); } if (pb.getNumber() != null) { - builder.number(pb.getNumber()); + builder.setNumber(pb.getNumber()); } if (pb.getQuota() != null) { - builder.quota(Quota.fromPb(pb.getQuota())); + builder.setQuota(Quota.fromPb(pb.getQuota())); } return builder.build(); } diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/RecordSet.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/RecordSet.java index e9d2e1b2527e..5e6a47028ede 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/RecordSet.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/RecordSet.java @@ -180,7 +180,15 @@ public Builder clearRecords() { /** * Replaces the current records with the provided list of records. */ + @Deprecated public Builder records(List records) { + return setRecords(records); + } + + /** + * Replaces the current records with the provided list of records. + */ + public Builder setRecords(List records) { this.rrdatas = Lists.newLinkedList(checkNotNull(records)); return this; } @@ -188,7 +196,15 @@ public Builder records(List records) { /** * Sets the name for this record set. For example, www.example.com. */ + @Deprecated public Builder name(String name) { + return setName(name); + } + + /** + * Sets the name for this record set. For example, www.example.com. + */ + public Builder setName(String name) { this.name = checkNotNull(name); return this; } @@ -200,7 +216,19 @@ public Builder name(String name) { * @param duration A non-negative number of time units * @param unit The unit of the ttl parameter */ + @Deprecated public Builder ttl(int duration, TimeUnit unit) { + return setTtl(duration, unit); + } + + /** + * 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 duration A non-negative number of time units + * @param unit The unit of the ttl parameter + */ + public Builder setTtl(int duration, TimeUnit unit) { checkArgument(duration >= 0, "Duration cannot be negative. The supplied value was %s.", duration); checkNotNull(unit); @@ -213,7 +241,15 @@ public Builder ttl(int duration, TimeUnit unit) { /** * The identifier of a supported record type, for example, A, AAAA, MX, TXT, and so on. */ + @Deprecated public Builder type(Type type) { + return setType(type); + } + + /** + * The identifier of a supported record type, for example, A, AAAA, MX, TXT, and so on. + */ + public Builder setType(Type type) { this.type = checkNotNull(type); return this; } @@ -243,35 +279,75 @@ public Builder toBuilder() { /** * Creates a {@code RecordSet} builder for the given {@code name} and {@code type}. */ + @Deprecated public static Builder builder(String name, Type type) { + return newBuilder(name, type); + } + + /** + * Creates a {@code RecordSet} builder for the given {@code name} and {@code type}. + */ + public static Builder newBuilder(String name, Type type) { return new Builder(name, type); } /** * Returns the user-assigned name of this record set. */ + @Deprecated public String name() { + return getName(); + } + + /** + * Returns the user-assigned name of this record set. + */ + public String getName() { return name; } /** * Returns a list of records stored in this record set. */ + @Deprecated public List records() { + return getRecords(); + } + + /** + * Returns a list of records stored in this record set. + */ + public List getRecords() { return rrdatas; } /** * Returns the number of seconds that this record set can be cached by resolvers. */ + @Deprecated public Integer ttl() { + return getTtl(); + } + + /** + * Returns the number of seconds that this record set can be cached by resolvers. + */ + public Integer getTtl() { return ttl; } /** * Returns the type of this record set. */ + @Deprecated public Type type() { + return getType(); + } + + /** + * Returns the type of this record set. + */ + public Type getType() { return type; } @@ -289,20 +365,20 @@ public boolean equals(Object obj) { ResourceRecordSet toPb() { ResourceRecordSet pb = new ResourceRecordSet(); - pb.setName(this.name()); - pb.setRrdatas(this.records()); - pb.setTtl(this.ttl()); - pb.setType(this.type().name()); + pb.setName(this.getName()); + pb.setRrdatas(this.getRecords()); + pb.setTtl(this.getTtl()); + pb.setType(this.getType().name()); return pb; } static RecordSet fromPb(ResourceRecordSet pb) { - Builder builder = builder(pb.getName(), Type.valueOf(pb.getType())); + Builder builder = newBuilder(pb.getName(), Type.valueOf(pb.getType())); if (pb.getRrdatas() != null) { - builder.records(pb.getRrdatas()); + builder.setRecords(pb.getRrdatas()); } if (pb.getTtl() != null) { - builder.ttl(pb.getTtl(), TimeUnit.SECONDS); + builder.setTtl(pb.getTtl(), TimeUnit.SECONDS); } return builder.build(); } @@ -310,10 +386,10 @@ static RecordSet fromPb(ResourceRecordSet pb) { @Override public String toString() { return MoreObjects.toStringHelper(this) - .add("name", name()) - .add("rrdatas", records()) - .add("ttl", ttl()) - .add("type", type()) + .add("name", getName()) + .add("rrdatas", getRecords()) + .add("ttl", getTtl()) + .add("type", getType()) .toString(); } } diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/Zone.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/Zone.java index a01f7212d28e..5680af4c8646 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/Zone.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/Zone.java @@ -56,44 +56,62 @@ private Builder(Zone zone) { } @Override + @Deprecated public Builder name(String name) { - infoBuilder.name(name); + return setName(name); + } + + @Override + public Builder setName(String name) { + infoBuilder.setName(name); return this; } @Override - Builder generatedId(String generatedId) { - infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + infoBuilder.setGeneratedId(generatedId); return this; } @Override - Builder creationTimeMillis(long creationTimeMillis) { - infoBuilder.creationTimeMillis(creationTimeMillis); + Builder setCreationTimeMillis(long creationTimeMillis) { + infoBuilder.setCreationTimeMillis(creationTimeMillis); return this; } @Override + @Deprecated public Builder dnsName(String dnsName) { - infoBuilder.dnsName(dnsName); + return setDnsName(dnsName); + } + + @Override + public Builder setDnsName(String dnsName) { + infoBuilder.setDnsName(dnsName); return this; } @Override + @Deprecated public Builder description(String description) { - infoBuilder.description(description); + return setDescription(description); + } + + @Override + public Builder setDescription(String description) { + infoBuilder.setDescription(description); return this; } @Override - Builder nameServerSet(String nameServerSet) { - infoBuilder.nameServerSet(nameServerSet); + Builder setNameServerSet(String nameServerSet) { + infoBuilder.setNameServerSet(nameServerSet); return this; } @Override - Builder nameServers(List nameServers) { - infoBuilder.nameServers(nameServers); // infoBuilder makes a copy + Builder setNameServers(List nameServers) { + infoBuilder.setNameServers(nameServers); // infoBuilder makes a copy return this; } @@ -122,7 +140,7 @@ public Builder toBuilder() { * @throws DnsException upon failure */ public Zone reload(Dns.ZoneOption... options) { - return dns.getZone(name(), options); + return dns.getZone(getName(), options); } /** @@ -132,7 +150,7 @@ public Zone reload(Dns.ZoneOption... options) { * @throws DnsException upon failure */ public boolean delete() { - return dns.delete(name()); + return dns.delete(getName()); } /** @@ -143,7 +161,7 @@ public boolean delete() { * @throws DnsException upon failure or if the zone is not found */ public Page listRecordSets(Dns.RecordSetListOption... options) { - return dns.listRecordSets(name(), options); + return dns.listRecordSets(getName(), options); } /** @@ -157,7 +175,7 @@ public Page listRecordSets(Dns.RecordSetListOption... options) { public ChangeRequest applyChangeRequest(ChangeRequestInfo changeRequest, Dns.ChangeRequestOption... options) { checkNotNull(changeRequest); - return dns.applyChangeRequest(name(), changeRequest, options); + return dns.applyChangeRequest(getName(), changeRequest, options); } /** @@ -173,7 +191,7 @@ public ChangeRequest applyChangeRequest(ChangeRequestInfo changeRequest, public ChangeRequest getChangeRequest(String changeRequestId, Dns.ChangeRequestOption... options) { checkNotNull(changeRequestId); - return dns.getChangeRequest(name(), changeRequestId, options); + return dns.getChangeRequest(getName(), changeRequestId, options); } /** @@ -185,13 +203,21 @@ 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(name(), options); + return dns.listChangeRequests(getName(), options); } /** * Returns the {@link Dns} service object associated with this zone. */ + @Deprecated public Dns dns() { + return getDns(); + } + + /** + * Returns the {@link Dns} service object associated with this zone. + */ + public Dns getDns() { return this.dns; } diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/ZoneInfo.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/ZoneInfo.java index d6178479b68b..c4e494d33f09 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/ZoneInfo.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/ZoneInfo.java @@ -55,41 +55,60 @@ public abstract static class Builder { /** * Sets a mandatory user-provided name for the zone. It must be unique within the project. */ + @Deprecated public abstract Builder name(String name); + /** + * Sets a mandatory user-provided name for the zone. It must be unique within the project. + */ + public abstract Builder setName(String name); + /** * Sets service-generated id for the zone. */ - abstract Builder generatedId(String generatedId); + abstract Builder setGeneratedId(String generatedId); /** * Sets the time when this zone was created. */ - abstract Builder creationTimeMillis(long creationTimeMillis); + abstract Builder setCreationTimeMillis(long creationTimeMillis); /** * Sets a mandatory DNS name of this zone, for instance "example.com.". */ + @Deprecated public abstract Builder dnsName(String dnsName); + /** + * Sets a mandatory DNS name of this zone, for instance "example.com.". + */ + public abstract Builder setDnsName(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. */ + @Deprecated public abstract Builder description(String description); + /** + * 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 setDescription(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. */ - abstract Builder nameServerSet(String nameServerSet); + abstract Builder setNameServerSet(String nameServerSet); // 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 * by Google Cloud DNS and is read only. */ - abstract Builder nameServers(List nameServers); + abstract Builder setNameServers(List nameServers); /** * Builds the instance of {@code ZoneInfo} based on the information set by this builder. @@ -126,43 +145,61 @@ private BuilderImpl(String name) { } @Override + @Deprecated public Builder name(String name) { + return setName(name); + } + + @Override + public Builder setName(String name) { this.name = checkNotNull(name); return this; } @Override - Builder generatedId(String generatedId) { + Builder setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } @Override - Builder creationTimeMillis(long creationTimeMillis) { + Builder setCreationTimeMillis(long creationTimeMillis) { this.creationTimeMillis = creationTimeMillis; return this; } @Override + @Deprecated public Builder dnsName(String dnsName) { + return setDnsName(dnsName); + } + + @Override + public Builder setDnsName(String dnsName) { this.dnsName = checkNotNull(dnsName); return this; } @Override + @Deprecated public Builder description(String description) { + return setDescription(description); + } + + @Override + public Builder setDescription(String description) { this.description = checkNotNull(description); return this; } @Override - Builder nameServerSet(String nameServerSet) { + Builder setNameServerSet(String nameServerSet) { this.nameServerSet = checkNotNull(nameServerSet); return this; } @Override - Builder nameServers(List nameServers) { + Builder setNameServers(List nameServers) { checkNotNull(nameServers); this.nameServers = Lists.newLinkedList(nameServers); return this; @@ -189,41 +226,81 @@ public ZoneInfo build() { * Returns a ZoneInfo object with assigned {@code name}, {@code dnsName} and {@code description}. */ public static ZoneInfo of(String name, String dnsName, String description) { - return new BuilderImpl(name).dnsName(dnsName).description(description).build(); + return new BuilderImpl(name).setDnsName(dnsName).setDescription(description).build(); } /** * Returns the user-defined name of the zone. */ + @Deprecated public String name() { + return getName(); + } + + /** + * Returns the user-defined name of the zone. + */ + public String getName() { return name; } /** * Returns the service-generated id for this zone. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated id for this zone. + */ + public String getGeneratedId() { return generatedId; } /** * Returns the time when this zone was created on the server. */ + @Deprecated public Long creationTimeMillis() { + return getCreationTimeMillis(); + } + + /** + * Returns the time when this zone was created on the server. + */ + public Long getCreationTimeMillis() { return creationTimeMillis; } /** * Returns the DNS name of this zone, for instance "example.com.". */ + @Deprecated public String dnsName() { + return getDnsName(); + } + + /** + * Returns the DNS name of this zone, for instance "example.com.". + */ + public String getDnsName() { return dnsName; } /** * Returns the description of this zone. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns the description of this zone. + */ + public String getDescription() { return description; } @@ -231,14 +308,31 @@ public String description() { * 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. */ + @Deprecated public String nameServerSet() { + return getNameServerSet(); + } + + /** + * 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 getNameServerSet() { return nameServerSet; } /** * The nameservers that the zone should be delegated to. This is defined by the Google DNS cloud. */ + @Deprecated public List nameServers() { + return getNameServers(); + } + + /** + * The nameservers that the zone should be delegated to. This is defined by the Google DNS cloud. + */ + public List getNameServers() { return nameServers == null ? ImmutableList.of() : nameServers; } @@ -252,18 +346,18 @@ public Builder toBuilder() { ManagedZone toPb() { ManagedZone pb = new ManagedZone(); - pb.setDescription(this.description()); - pb.setDnsName(this.dnsName()); - if (this.generatedId() != null) { - pb.setId(new BigInteger(this.generatedId())); + pb.setDescription(this.getDescription()); + pb.setDnsName(this.getDnsName()); + if (this.getGeneratedId() != null) { + pb.setId(new BigInteger(this.getGeneratedId())); } - pb.setName(this.name()); + pb.setName(this.getName()); pb.setNameServers(this.nameServers); // do use real attribute value which may be null - pb.setNameServerSet(this.nameServerSet()); - if (this.creationTimeMillis() != null) { + pb.setNameServerSet(this.getNameServerSet()); + if (this.getCreationTimeMillis() != null) { pb.setCreationTime(ISODateTimeFormat.dateTime() .withZoneUTC() - .print(this.creationTimeMillis())); + .print(this.getCreationTimeMillis())); } return pb; } @@ -271,22 +365,22 @@ ManagedZone toPb() { static ZoneInfo fromPb(ManagedZone pb) { Builder builder = new BuilderImpl(pb.getName()); if (pb.getDescription() != null) { - builder.description(pb.getDescription()); + builder.setDescription(pb.getDescription()); } if (pb.getDnsName() != null) { - builder.dnsName(pb.getDnsName()); + builder.setDnsName(pb.getDnsName()); } if (pb.getId() != null) { - builder.generatedId(pb.getId().toString()); + builder.setGeneratedId(pb.getId().toString()); } if (pb.getNameServers() != null) { - builder.nameServers(pb.getNameServers()); + builder.setNameServers(pb.getNameServers()); } if (pb.getNameServerSet() != null) { - builder.nameServerSet(pb.getNameServerSet()); + builder.setNameServerSet(pb.getNameServerSet()); } if (pb.getCreationTime() != null) { - builder.creationTimeMillis(DateTime.parse(pb.getCreationTime()).getMillis()); + builder.setCreationTimeMillis(DateTime.parse(pb.getCreationTime()).getMillis()); } return builder.build(); } @@ -308,13 +402,13 @@ public int hashCode() { @Override public String toString() { return MoreObjects.toStringHelper(this) - .add("name", name()) - .add("generatedId", generatedId()) - .add("description", description()) - .add("dnsName", dnsName()) - .add("nameServerSet", nameServerSet()) - .add("nameServers", nameServers()) - .add("creationTimeMillis", creationTimeMillis()) + .add("name", getName()) + .add("generatedId", getGeneratedId()) + .add("description", getDescription()) + .add("dnsName", getDnsName()) + .add("nameServerSet", getNameServerSet()) + .add("nameServers", getNameServers()) + .add("creationTimeMillis", getCreationTimeMillis()) .toString(); } } diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/package-info.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/package-info.java index a9c29efaa0f1..a56db7757db7 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/package-info.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/package-info.java @@ -46,11 +46,11 @@ * String zoneName = "my-unique-zone"; * Zone zone = dns.getZone(zoneName); * String ip = "12.13.14.15"; - * RecordSet toCreate = RecordSet.builder("www.someexampledomain.com.", RecordSet.Type.A) - * .ttl(24, TimeUnit.HOURS) + * RecordSet toCreate = RecordSet.newBuilder("www.someexampledomain.com.", RecordSet.Type.A) + * .setTtl(24, TimeUnit.HOURS) * .addRecord(ip) * .build(); - * ChangeRequestInfo changeRequest = ChangeRequestInfo.builder().add(toCreate).build(); + * ChangeRequestInfo changeRequest = ChangeRequestInfo.newBuilder().add(toCreate).build(); * zone.applyChangeRequest(changeRequest); * }

* diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java index 774bc566a458..12e2599defcb 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java @@ -39,6 +39,7 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; import com.google.common.io.ByteStreams; + import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; @@ -494,7 +495,15 @@ public static LocalDnsHelper create(Long delay) { /** * Returns a {@link DnsOptions} instance that sets the host to use the mock server. */ + @Deprecated public DnsOptions options() { + return getOptions(); + } + + /** + * Returns a {@link DnsOptions} instance that sets the host to use the mock server. + */ + public DnsOptions getOptions() { return DnsOptions.builder() .projectId(PROJECT_ID) .host("http://localhost:" + port) diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/ChangeRequestInfoTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/ChangeRequestInfoTest.java index 2da7ad75c569..9632ac475c09 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/ChangeRequestInfoTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/ChangeRequestInfoTest.java @@ -41,22 +41,39 @@ public class ChangeRequestInfoTest { 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 RecordSet RECORD1 = RecordSet.newBuilder(NAME1, TYPE1).build(); + private static final RecordSet RECORD2 = RecordSet.newBuilder(NAME2, TYPE2).build(); + private static final RecordSet RECORD3 = RecordSet.newBuilder(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() + private static final ChangeRequestInfo CHANGE = ChangeRequest.newBuilder() .add(RECORD1) .add(RECORD2) .delete(RECORD3) - .startTimeMillis(START_TIME_MILLIS) - .status(STATUS) - .generatedId(GENERATED_ID) + .setStartTime(START_TIME_MILLIS) + .setStatus(STATUS) + .setGeneratedId(GENERATED_ID) + .build(); + private static final ChangeRequestInfo DEPRECATED_CHANGE = ChangeRequest.builder() + .add(RECORD1) + .add(RECORD2) + .delete(RECORD3) + .setStartTime(START_TIME_MILLIS) + .setStatus(STATUS) + .setGeneratedId(GENERATED_ID) .build(); @Test public void testEmptyBuilder() { + ChangeRequestInfo cr = ChangeRequest.newBuilder().build(); + assertNotNull(cr.getDeletions()); + assertTrue(cr.getDeletions().isEmpty()); + assertNotNull(cr.getAdditions()); + assertTrue(cr.getAdditions().isEmpty()); + } + + @Test + public void testEmptyBuilderDeprecated() { ChangeRequestInfo cr = ChangeRequest.builder().build(); assertNotNull(cr.deletions()); assertTrue(cr.deletions().isEmpty()); @@ -66,18 +83,34 @@ public void testEmptyBuilder() { @Test public void testBuilder() { - assertEquals(GENERATED_ID, CHANGE.generatedId()); + assertEquals(GENERATED_ID, CHANGE.getGeneratedId()); assertEquals(STATUS, CHANGE.status()); - assertEquals(START_TIME_MILLIS, CHANGE.startTimeMillis()); - assertEquals(ADDITIONS, CHANGE.additions()); - assertEquals(DELETIONS, CHANGE.deletions()); + assertEquals(START_TIME_MILLIS, CHANGE.getStartTimeMillis()); + assertEquals(ADDITIONS, CHANGE.getAdditions()); + assertEquals(DELETIONS, CHANGE.getDeletions()); + List recordList = ImmutableList.of(RECORD1); + ChangeRequestInfo another = CHANGE.toBuilder().setAdditions(recordList).build(); + assertEquals(recordList, another.getAdditions()); + assertEquals(CHANGE.getDeletions(), another.getDeletions()); + another = CHANGE.toBuilder().setDeletions(recordList).build(); + assertEquals(recordList, another.getDeletions()); + assertEquals(CHANGE.getAdditions(), another.getAdditions()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(GENERATED_ID, DEPRECATED_CHANGE.generatedId()); + assertEquals(STATUS, DEPRECATED_CHANGE.status()); + assertEquals(START_TIME_MILLIS, DEPRECATED_CHANGE.startTimeMillis()); + assertEquals(ADDITIONS, DEPRECATED_CHANGE.additions()); + assertEquals(DELETIONS, DEPRECATED_CHANGE.deletions()); List recordList = ImmutableList.of(RECORD1); - ChangeRequestInfo another = CHANGE.toBuilder().additions(recordList).build(); + ChangeRequestInfo another = DEPRECATED_CHANGE.toBuilder().additions(recordList).build(); assertEquals(recordList, another.additions()); - assertEquals(CHANGE.deletions(), another.deletions()); - another = CHANGE.toBuilder().deletions(recordList).build(); + assertEquals(DEPRECATED_CHANGE.deletions(), another.deletions()); + another = DEPRECATED_CHANGE.toBuilder().deletions(recordList).build(); assertEquals(recordList, another.deletions()); - assertEquals(CHANGE.additions(), another.additions()); + assertEquals(DEPRECATED_CHANGE.additions(), another.additions()); } @Test @@ -86,17 +119,17 @@ public void testEqualsAndNotEquals() { assertEquals(CHANGE, clone); clone = ChangeRequest.fromPb(CHANGE.toPb()); assertEquals(CHANGE, clone); - clone = CHANGE.toBuilder().generatedId("some-other-id").build(); + clone = CHANGE.toBuilder().setGeneratedId("some-other-id").build(); assertNotEquals(CHANGE, clone); - clone = CHANGE.toBuilder().startTimeMillis(CHANGE.startTimeMillis() + 1).build(); + clone = CHANGE.toBuilder().setStartTime(CHANGE.getStartTimeMillis() + 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(); + ChangeRequestInfo empty = ChangeRequest.newBuilder().build(); assertNotEquals(CHANGE, empty); - assertEquals(empty, ChangeRequest.builder().build()); + assertEquals(empty, ChangeRequest.newBuilder().build()); } @Test @@ -104,57 +137,57 @@ 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()); + ChangeRequestInfo empty = ChangeRequest.newBuilder().build(); + assertEquals(empty.hashCode(), ChangeRequest.newBuilder().build().hashCode()); } @Test public void testToAndFromPb() { assertEquals(CHANGE, ChangeRequest.fromPb(CHANGE.toPb())); - ChangeRequestInfo partial = ChangeRequest.builder().build(); + ChangeRequestInfo partial = ChangeRequest.newBuilder().build(); assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().generatedId(GENERATED_ID).build(); + partial = ChangeRequest.newBuilder().setGeneratedId(GENERATED_ID).build(); assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().add(RECORD1).build(); + partial = ChangeRequest.newBuilder().add(RECORD1).build(); assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().delete(RECORD1).build(); + partial = ChangeRequest.newBuilder().delete(RECORD1).build(); assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().additions(ADDITIONS).build(); + partial = ChangeRequest.newBuilder().setAdditions(ADDITIONS).build(); assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().deletions(DELETIONS).build(); + partial = ChangeRequest.newBuilder().setDeletions(DELETIONS).build(); assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().startTimeMillis(START_TIME_MILLIS).build(); + partial = ChangeRequest.newBuilder().setStartTime(START_TIME_MILLIS).build(); assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); - partial = ChangeRequest.builder().status(STATUS).build(); + partial = ChangeRequest.newBuilder().setStatus(STATUS).build(); assertEquals(partial, ChangeRequest.fromPb(partial.toPb())); } @Test public void testToBuilder() { assertEquals(CHANGE, CHANGE.toBuilder().build()); - ChangeRequestInfo partial = ChangeRequest.builder().build(); + ChangeRequestInfo partial = ChangeRequest.newBuilder().build(); assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().generatedId(GENERATED_ID).build(); + partial = ChangeRequest.newBuilder().setGeneratedId(GENERATED_ID).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().add(RECORD1).build(); + partial = ChangeRequest.newBuilder().add(RECORD1).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().delete(RECORD1).build(); + partial = ChangeRequest.newBuilder().delete(RECORD1).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().additions(ADDITIONS).build(); + partial = ChangeRequest.newBuilder().setAdditions(ADDITIONS).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().deletions(DELETIONS).build(); + partial = ChangeRequest.newBuilder().setDeletions(DELETIONS).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().startTimeMillis(START_TIME_MILLIS).build(); + partial = ChangeRequest.newBuilder().setStartTime(START_TIME_MILLIS).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ChangeRequest.builder().status(STATUS).build(); + partial = ChangeRequest.newBuilder().setStatus(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()); + assertTrue(clone.getAdditions().isEmpty()); + assertFalse(clone.getDeletions().isEmpty()); } @Test @@ -166,7 +199,7 @@ public void testAddAddition() { // expected } ChangeRequestInfo clone = CHANGE.toBuilder().add(RECORD1).build(); - assertEquals(CHANGE.additions().size() + 1, clone.additions().size()); + assertEquals(CHANGE.getAdditions().size() + 1, clone.getAdditions().size()); } @Test @@ -178,33 +211,33 @@ public void testAddDeletion() { // expected } ChangeRequestInfo clone = CHANGE.toBuilder().delete(RECORD1).build(); - assertEquals(CHANGE.deletions().size() + 1, clone.deletions().size()); + assertEquals(CHANGE.getDeletions().size() + 1, clone.getDeletions().size()); } @Test public void testClearDeletions() { ChangeRequestInfo clone = CHANGE.toBuilder().clearDeletions().build(); - assertTrue(clone.deletions().isEmpty()); - assertFalse(clone.additions().isEmpty()); + assertTrue(clone.getDeletions().isEmpty()); + assertFalse(clone.getAdditions().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)); + assertTrue(clone.getAdditions().contains(RECORD2)); + assertFalse(clone.getAdditions().contains(RECORD1)); + assertTrue(clone.getDeletions().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)); + assertFalse(clone.getAdditions().contains(RECORD2)); + assertFalse(clone.getAdditions().contains(RECORD1)); + assertTrue(clone.getAdditions().isEmpty()); + assertTrue(clone.getDeletions().contains(RECORD3)); } @Test public void testRemoveDeletion() { ChangeRequestInfo clone = CHANGE.toBuilder().removeDeletion(RECORD3).build(); - assertTrue(clone.deletions().isEmpty()); + assertTrue(clone.getDeletions().isEmpty()); } @Test @@ -212,7 +245,7 @@ public void testDateParsing() { String startTime = "2016-01-26T18:33:43.512Z"; // obtained from service Change change = CHANGE.toPb().setStartTime(startTime); ChangeRequestInfo converted = ChangeRequest.fromPb(change); - assertNotNull(converted.startTimeMillis()); + assertNotNull(converted.getStartTimeMillis()); assertEquals(change, converted.toPb()); assertEquals(change.getStartTime(), converted.toPb().getStartTime()); } diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/ChangeRequestTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/ChangeRequestTest.java index 6daa1a0a8cdd..f983ae47e686 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/ChangeRequestTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/ChangeRequestTest.java @@ -35,9 +35,9 @@ public class ChangeRequestTest { 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()) + private static final ChangeRequestInfo CHANGE_REQUEST_INFO = ChangeRequest.newBuilder() + .add(RecordSet.newBuilder("name", RecordSet.Type.A).build()) + .delete(RecordSet.newBuilder("othername", RecordSet.Type.AAAA).build()) .build(); private static final DnsOptions OPTIONS = createStrictMock(DnsOptions.class); @@ -53,15 +53,15 @@ public void setUp() throws Exception { replay(dns); changeRequest = new ChangeRequest(dns, ZONE_NAME, new ChangeRequestInfo.BuilderImpl( CHANGE_REQUEST_INFO.toBuilder() - .startTimeMillis(132L) - .generatedId("12") - .status(ChangeRequest.Status.DONE) + .setStartTime(132L) + .setGeneratedId("12") + .setStatus(ChangeRequest.Status.DONE) .build())); changeRequestPending = new ChangeRequest(dns, ZONE_NAME, new ChangeRequestInfo.BuilderImpl( CHANGE_REQUEST_INFO.toBuilder() - .startTimeMillis(132L) - .generatedId("12") - .status(ChangeRequest.Status.PENDING) + .setStartTime(132L) + .setGeneratedId("12") + .setStatus(ChangeRequest.Status.PENDING) .build())); changeRequestPartial = new ChangeRequest(dns, ZONE_NAME, new ChangeRequest.BuilderImpl(CHANGE_REQUEST_INFO)); @@ -106,15 +106,43 @@ public void testEqualsAndToBuilder() { assertEquals(changeRequestPartial.hashCode(), compare.hashCode()); } + @Test public void testBuilder() { + // one for each build() call because it invokes a constructor + expect(dns.options()).andReturn(OPTIONS).times(9); + replay(dns); + String id = changeRequest.getGeneratedId() + "aaa"; + assertEquals(id, changeRequest.toBuilder().setGeneratedId(id).build().getGeneratedId()); + ChangeRequest modified = + changeRequest.toBuilder().setStatus(ChangeRequest.Status.PENDING).build(); + assertEquals(ChangeRequest.Status.PENDING, modified.status()); + modified = changeRequest.toBuilder().clearDeletions().build(); + assertTrue(modified.getDeletions().isEmpty()); + modified = changeRequest.toBuilder().clearAdditions().build(); + assertTrue(modified.getAdditions().isEmpty()); + modified = changeRequest.toBuilder().setAdditions(ImmutableList.of()).build(); + assertTrue(modified.getAdditions().isEmpty()); + modified = changeRequest.toBuilder().setDeletions(ImmutableList.of()).build(); + assertTrue(modified.getDeletions().isEmpty()); + RecordSet cname = RecordSet.newBuilder("last", RecordSet.Type.CNAME).build(); + modified = changeRequest.toBuilder().add(cname).build(); + assertTrue(modified.getAdditions().contains(cname)); + modified = changeRequest.toBuilder().delete(cname).build(); + assertTrue(modified.getDeletions().contains(cname)); + modified = changeRequest.toBuilder().setStartTime(0L).build(); + assertEquals(Long.valueOf(0), modified.getStartTimeMillis()); + } + + @Test + public void testBuilderDeprecated() { // one for each build() call because it invokes a constructor expect(dns.options()).andReturn(OPTIONS).times(9); replay(dns); String id = changeRequest.generatedId() + "aaa"; - assertEquals(id, changeRequest.toBuilder().generatedId(id).build().generatedId()); + assertEquals(id, changeRequest.toBuilder().setGeneratedId(id).build().generatedId()); ChangeRequest modified = - changeRequest.toBuilder().status(ChangeRequest.Status.PENDING).build(); + changeRequest.toBuilder().setStatus(ChangeRequest.Status.PENDING).build(); assertEquals(ChangeRequest.Status.PENDING, modified.status()); modified = changeRequest.toBuilder().clearDeletions().build(); assertTrue(modified.deletions().isEmpty()); @@ -129,7 +157,7 @@ public void testBuilder() { assertTrue(modified.additions().contains(cname)); modified = changeRequest.toBuilder().delete(cname).build(); assertTrue(modified.deletions().contains(cname)); - modified = changeRequest.toBuilder().startTimeMillis(0L).build(); + modified = changeRequest.toBuilder().setStartTime(0L).build(); assertEquals(Long.valueOf(0), modified.startTimeMillis()); } @@ -147,8 +175,9 @@ public void testApplyTo() { @Test public void testReload() { - expect(dns.getChangeRequest(ZONE_NAME, changeRequest.generatedId())).andReturn(changeRequest); - expect(dns.getChangeRequest(ZONE_NAME, changeRequest.generatedId(), + expect(dns.getChangeRequest(ZONE_NAME, changeRequest.getGeneratedId())) + .andReturn(changeRequest); + expect(dns.getChangeRequest(ZONE_NAME, changeRequest.getGeneratedId(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.START_TIME))) .andReturn(changeRequest); replay(dns); @@ -163,7 +192,7 @@ public void testIsDone() { assertTrue(changeRequest.isDone()); verify(dns); reset(dns); - expect(dns.getChangeRequest(ZONE_NAME, changeRequest.generatedId(), + expect(dns.getChangeRequest(ZONE_NAME, changeRequest.getGeneratedId(), Dns.ChangeRequestOption.fields(Dns.ChangeRequestField.STATUS))) .andReturn(changeRequest); replay(dns); diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsBatchTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsBatchTest.java index 746a65ab7155..d348e8e9858f 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsBatchTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsBatchTest.java @@ -64,7 +64,7 @@ public class DnsBatchTest { Dns.ZoneListOption.pageSize(MAX_SIZE), Dns.ZoneListOption.pageToken(PAGE_TOKEN), Dns.ZoneListOption.fields(Dns.ZoneField.DESCRIPTION), Dns.ZoneListOption.dnsName(DNS_NAME)}; - private static final ProjectInfo PROJECT_INFO = ProjectInfo.builder().build(); + private static final ProjectInfo PROJECT_INFO = ProjectInfo.newBuilder().build(); private static final Dns.RecordSetListOption[] RECORD_SET_LIST_OPTIONS = { Dns.RecordSetListOption.pageSize(MAX_SIZE), Dns.RecordSetListOption.pageToken(PAGE_TOKEN), @@ -72,16 +72,16 @@ public class DnsBatchTest { Dns.RecordSetListOption.dnsName(DNS_NAME), Dns.RecordSetListOption.type(RecordSet.Type.AAAA)}; private static final RecordSet RECORD_SET = - RecordSet.builder("Something", RecordSet.Type.AAAA).build(); - private static final ChangeRequestInfo CHANGE_REQUEST_PARTIAL = ChangeRequestInfo.builder() + RecordSet.newBuilder("Something", RecordSet.Type.AAAA).build(); + private static final ChangeRequestInfo CHANGE_REQUEST_PARTIAL = ChangeRequestInfo.newBuilder() .add(RECORD_SET) .build(); private static final String CHANGE_ID = "some change id"; - private static final ChangeRequestInfo CHANGE_REQUEST_COMPLETE = ChangeRequestInfo.builder() + private static final ChangeRequestInfo CHANGE_REQUEST_COMPLETE = ChangeRequestInfo.newBuilder() .add(RECORD_SET) - .startTimeMillis(123L) - .status(ChangeRequest.Status.PENDING) - .generatedId(CHANGE_ID) + .setStartTime(123L) + .setStatus(ChangeRequest.Status.PENDING) + .setGeneratedId(CHANGE_ID) .build(); private static final Dns.ChangeRequestListOption[] CHANGE_LIST_OPTIONS = { Dns.ChangeRequestListOption.pageSize(MAX_SIZE), @@ -122,9 +122,9 @@ public void tearDown() { @Test public void testConstructor() { - assertSame(batchMock, dnsBatch.batch()); - assertSame(optionsMock, dnsBatch.options()); - assertSame(dnsRpcMock, dnsBatch.dnsRpc()); + assertSame(batchMock, dnsBatch.getBatch()); + assertSame(optionsMock, dnsBatch.getOptions()); + assertSame(dnsRpcMock, dnsBatch.getDnsRpc()); } @Test @@ -163,14 +163,14 @@ public void testListZonesWithOptions() { EasyMock.replay(batchMock); DnsBatchResult> batchResult = dnsBatch.listZones(ZONE_LIST_OPTIONS); assertNotNull(callback.getValue()); - Integer size = (Integer) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[0].rpcOption()); + Integer size = (Integer) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[0].getRpcOption()); assertEquals(MAX_SIZE, size); - String selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[1].rpcOption()); + String selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[1].getRpcOption()); assertEquals(PAGE_TOKEN, selector); - selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[2].rpcOption()); + selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[2].getRpcOption()); assertTrue(selector.contains(Dns.ZoneField.DESCRIPTION.selector())); assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); - selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[3].rpcOption()); + selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[3].getRpcOption()); assertEquals(DNS_NAME, selector); // check the callback ManagedZonesListResponse response = new ManagedZonesListResponse() @@ -245,7 +245,7 @@ public void testCreateZoneWithOptions() { DnsBatchResult batchResult = dnsBatch.createZone(ZONE_INFO, ZONE_FIELDS); assertEquals(ZONE_INFO.toPb(), capturedZone.getValue()); assertNotNull(callback.getValue()); - String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.getRpcOption()); assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.selector())); assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); RpcBatch.Callback capturedCallback = callback.getValue(); @@ -311,7 +311,7 @@ public void testGetZoneWithOptions() { EasyMock.replay(dns, batchMock, optionsMock); DnsBatchResult batchResult = dnsBatch.getZone(ZONE_NAME, ZONE_FIELDS); assertNotNull(callback.getValue()); - String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.getRpcOption()); assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.selector())); assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); RpcBatch.Callback capturedCallback = callback.getValue(); @@ -396,7 +396,7 @@ public void testGetProjectWithOptions() { EasyMock.replay(batchMock); DnsBatchResult batchResult = dnsBatch.getProject(PROJECT_FIELDS); assertNotNull(callback.getValue()); - String selector = (String) capturedOptions.getValue().get(PROJECT_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(PROJECT_FIELDS.getRpcOption()); assertTrue(selector.contains(Dns.ProjectField.QUOTA.selector())); assertTrue(selector.contains(Dns.ProjectField.PROJECT_ID.selector())); RpcBatch.Callback capturedCallback = callback.getValue(); @@ -443,19 +443,20 @@ public void testListRecordSetsWithOptions() { DnsBatchResult> batchResult = dnsBatch.listRecordSets(ZONE_NAME, RECORD_SET_LIST_OPTIONS); assertNotNull(callback.getValue()); - Integer size = (Integer) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[0].rpcOption()); + Integer size = + (Integer) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[0].getRpcOption()); assertEquals(MAX_SIZE, size); String selector = (String) capturedOptions.getValue() - .get(RECORD_SET_LIST_OPTIONS[1].rpcOption()); + .get(RECORD_SET_LIST_OPTIONS[1].getRpcOption()); assertEquals(PAGE_TOKEN, selector); - selector = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[2].rpcOption()); + selector = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[2].getRpcOption()); assertTrue(selector.contains(Dns.RecordSetField.NAME.selector())); assertTrue(selector.contains(Dns.RecordSetField.TTL.selector())); - selector = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[3].rpcOption()); - assertEquals(RECORD_SET_LIST_OPTIONS[3].value(), selector); + selector = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[3].getRpcOption()); + assertEquals(RECORD_SET_LIST_OPTIONS[3].getValue(), selector); String type = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[4] - .rpcOption()); - assertEquals(RECORD_SET_LIST_OPTIONS[4].value(), type); + .getRpcOption()); + assertEquals(RECORD_SET_LIST_OPTIONS[4].getValue(), type); RpcBatch.Callback capturedCallback = callback.getValue(); ResourceRecordSetsListResponse response = new ResourceRecordSetsListResponse() .setRrsets(RECORD_SET_LIST) @@ -511,14 +512,15 @@ public void testListChangeRequestsWithOptions() { DnsBatchResult> batchResult = dnsBatch.listChangeRequests(ZONE_NAME, CHANGE_LIST_OPTIONS); assertNotNull(callback.getValue()); - Integer size = (Integer) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[0].rpcOption()); + Integer size = (Integer) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[0].getRpcOption()); assertEquals(MAX_SIZE, size); - String selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[1].rpcOption()); + String selector = + (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[1].getRpcOption()); assertEquals(PAGE_TOKEN, selector); - selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[2].rpcOption()); + selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[2].getRpcOption()); assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); - selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[3].rpcOption()); + selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[3].getRpcOption()); assertTrue(selector.contains(Dns.SortingOrder.ASCENDING.selector())); // check the callback ChangesListResponse response = new ChangesListResponse() @@ -551,11 +553,11 @@ public void testGetChangeRequest() { Capture> callback = Capture.newInstance(); Capture> capturedOptions = Capture.newInstance(); batchMock.addGetChangeRequest(EasyMock.eq(ZONE_NAME), - EasyMock.eq(CHANGE_REQUEST_COMPLETE.generatedId()), EasyMock.capture(callback), + EasyMock.eq(CHANGE_REQUEST_COMPLETE.getGeneratedId()), EasyMock.capture(callback), EasyMock.capture(capturedOptions)); EasyMock.replay(batchMock); DnsBatchResult batchResult = dnsBatch.getChangeRequest(ZONE_NAME, - CHANGE_REQUEST_COMPLETE.generatedId()); + CHANGE_REQUEST_COMPLETE.getGeneratedId()); assertEquals(0, capturedOptions.getValue().size()); assertNotNull(callback.getValue()); try { @@ -582,11 +584,11 @@ public void testGetChangeRequestNotFound() { Capture> callback = Capture.newInstance(); Capture> capturedOptions = Capture.newInstance(); batchMock.addGetChangeRequest(EasyMock.eq(ZONE_NAME), - EasyMock.eq(CHANGE_REQUEST_COMPLETE.generatedId()), EasyMock.capture(callback), + EasyMock.eq(CHANGE_REQUEST_COMPLETE.getGeneratedId()), EasyMock.capture(callback), EasyMock.capture(capturedOptions)); EasyMock.replay(batchMock); DnsBatchResult batchResult = dnsBatch.getChangeRequest(ZONE_NAME, - CHANGE_REQUEST_COMPLETE.generatedId()); + CHANGE_REQUEST_COMPLETE.getGeneratedId()); assertEquals(0, capturedOptions.getValue().size()); RpcBatch.Callback capturedCallback = callback.getValue(); GoogleJsonError error = new GoogleJsonError(); @@ -607,13 +609,13 @@ public void testGetChangeRequestWithOptions() { Capture> callback = Capture.newInstance(); Capture> capturedOptions = Capture.newInstance(); batchMock.addGetChangeRequest(EasyMock.eq(ZONE_NAME), - EasyMock.eq(CHANGE_REQUEST_COMPLETE.generatedId()), EasyMock.capture(callback), + EasyMock.eq(CHANGE_REQUEST_COMPLETE.getGeneratedId()), EasyMock.capture(callback), EasyMock.capture(capturedOptions)); EasyMock.replay(dns, batchMock, optionsMock); DnsBatchResult batchResult = dnsBatch.getChangeRequest(ZONE_NAME, - CHANGE_REQUEST_COMPLETE.generatedId(), CHANGE_GET_FIELDS); + CHANGE_REQUEST_COMPLETE.getGeneratedId(), CHANGE_GET_FIELDS); assertNotNull(callback.getValue()); - String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.getRpcOption()); assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); RpcBatch.Callback capturedCallback = callback.getValue(); @@ -630,7 +632,7 @@ public void testApplyChangeRequest() { EasyMock.eq(CHANGE_REQUEST_PARTIAL.toPb()), EasyMock.capture(callback), EasyMock.capture(capturedOptions)); EasyMock.replay(batchMock); - DnsBatchResult batchResult = dnsBatch.applyChangeRequest(ZONE_INFO.name(), + DnsBatchResult batchResult = dnsBatch.applyChangeRequest(ZONE_INFO.getName(), CHANGE_REQUEST_PARTIAL); assertEquals(0, capturedOptions.getValue().size()); assertNotNull(callback.getValue()); @@ -665,9 +667,9 @@ public void testApplyChangeRequestWithOptions() { EasyMock.capture(capturedOptions)); EasyMock.expect(optionsMock.service()).andReturn(dns); EasyMock.replay(dns, batchMock, optionsMock); - DnsBatchResult batchResult = dnsBatch.applyChangeRequest(ZONE_INFO.name(), + DnsBatchResult batchResult = dnsBatch.applyChangeRequest(ZONE_INFO.getName(), CHANGE_REQUEST_PARTIAL, CHANGE_GET_FIELDS); - String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.getRpcOption()); assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); RpcBatch.Callback capturedCallback = callback.getValue(); diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsImplTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsImplTest.java index deefe21f36aa..19c143abbeaf 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsImplTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsImplTest.java @@ -47,21 +47,21 @@ public class DnsImplTest { private static final String DESCRIPTION = "desc"; private static final String CHANGE_ID = "some change id"; private static final RecordSet DNS_RECORD1 = - RecordSet.builder("Something", RecordSet.Type.AAAA).build(); + RecordSet.newBuilder("Something", RecordSet.Type.AAAA).build(); private static final RecordSet DNS_RECORD2 = - RecordSet.builder("Different", RecordSet.Type.AAAA).build(); + RecordSet.newBuilder("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); - private static final ProjectInfo PROJECT_INFO = ProjectInfo.builder().build(); - private static final ChangeRequestInfo CHANGE_REQUEST_PARTIAL = ChangeRequestInfo.builder() + private static final ProjectInfo PROJECT_INFO = ProjectInfo.newBuilder().build(); + private static final ChangeRequestInfo CHANGE_REQUEST_PARTIAL = ChangeRequestInfo.newBuilder() .add(DNS_RECORD1) .build(); - private static final ChangeRequestInfo CHANGE_REQUEST_COMPLETE = ChangeRequestInfo.builder() + private static final ChangeRequestInfo CHANGE_REQUEST_COMPLETE = ChangeRequestInfo.newBuilder() .add(DNS_RECORD1) - .startTimeMillis(123L) - .status(ChangeRequest.Status.PENDING) - .generatedId(CHANGE_ID) + .setStartTime(123L) + .setStatus(ChangeRequest.Status.PENDING) + .setGeneratedId(CHANGE_ID) .build(); // Result lists @@ -150,7 +150,7 @@ public void testCreateZoneWithOptions() { 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()); + String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.getRpcOption()); 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())); @@ -158,23 +158,23 @@ public void testCreateZoneWithOptions() { @Test public void testGetZone() { - EasyMock.expect(dnsRpcMock.getZone(ZONE_INFO.name(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(dnsRpcMock.getZone(ZONE_INFO.getName(), EMPTY_RPC_OPTIONS)) .andReturn(ZONE_INFO.toPb()); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl - Zone zone = dns.getZone(ZONE_INFO.name()); + Zone zone = dns.getZone(ZONE_INFO.getName()); assertEquals(new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)), zone); } @Test public void testGetZoneWithOptions() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(dnsRpcMock.getZone(EasyMock.eq(ZONE_INFO.name()), + EasyMock.expect(dnsRpcMock.getZone(EasyMock.eq(ZONE_INFO.getName()), EasyMock.capture(capturedOptions))).andReturn(ZONE_INFO.toPb()); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl - Zone zone = dns.getZone(ZONE_INFO.name(), ZONE_FIELDS); - String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.rpcOption()); + Zone zone = dns.getZone(ZONE_INFO.getName(), ZONE_FIELDS); + String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.getRpcOption()); 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())); @@ -182,11 +182,11 @@ public void testGetZoneWithOptions() { @Test public void testDeleteZone() { - EasyMock.expect(dnsRpcMock.deleteZone(ZONE_INFO.name())) + EasyMock.expect(dnsRpcMock.deleteZone(ZONE_INFO.getName())) .andReturn(true); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl - assertTrue(dns.delete(ZONE_INFO.name())); + assertTrue(dns.delete(ZONE_INFO.getName())); } @Test @@ -207,7 +207,7 @@ public void testProjectGetWithOptions() { EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl ProjectInfo projectInfo = dns.getProject(PROJECT_FIELDS); - String selector = (String) capturedOptions.getValue().get(PROJECT_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(PROJECT_FIELDS.getRpcOption()); assertEquals(PROJECT_INFO, projectInfo); assertTrue(selector.contains(Dns.ProjectField.QUOTA.selector())); assertTrue(selector.contains(Dns.ProjectField.PROJECT_ID.selector())); @@ -215,29 +215,29 @@ public void testProjectGetWithOptions() { @Test public void testGetChangeRequest() { - EasyMock.expect(dnsRpcMock.getChangeRequest(ZONE_INFO.name(), - CHANGE_REQUEST_COMPLETE.generatedId(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(dnsRpcMock.getChangeRequest(ZONE_INFO.getName(), + CHANGE_REQUEST_COMPLETE.getGeneratedId(), 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.generatedId()); - assertEquals(new ChangeRequest(dns, ZONE_INFO.name(), + ChangeRequest changeRequest = dns.getChangeRequest(ZONE_INFO.getName(), + CHANGE_REQUEST_COMPLETE.getGeneratedId()); + assertEquals(new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(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.generatedId()), EasyMock.capture(capturedOptions))) + EasyMock.expect(dnsRpcMock.getChangeRequest(EasyMock.eq(ZONE_INFO.getName()), + EasyMock.eq(CHANGE_REQUEST_COMPLETE.getGeneratedId()), 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.generatedId(), CHANGE_GET_FIELDS); - String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.rpcOption()); - assertEquals(new ChangeRequest(dns, ZONE_INFO.name(), + ChangeRequest changeRequest = dns.getChangeRequest(ZONE_INFO.getName(), + CHANGE_REQUEST_COMPLETE.getGeneratedId(), CHANGE_GET_FIELDS); + String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.getRpcOption()); + assertEquals(new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); @@ -245,28 +245,29 @@ public void testGetChangeRequestWithOptions() { @Test public void testApplyChangeRequest() { - EasyMock.expect(dnsRpcMock.applyChangeRequest(ZONE_INFO.name(), CHANGE_REQUEST_PARTIAL.toPb(), - EMPTY_RPC_OPTIONS)).andReturn(CHANGE_REQUEST_COMPLETE.toPb()); + EasyMock.expect(dnsRpcMock.applyChangeRequest(ZONE_INFO.getName(), + 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(), + ChangeRequest changeRequest = dns.applyChangeRequest(ZONE_INFO.getName(), CHANGE_REQUEST_PARTIAL); - assertEquals(new ChangeRequest(dns, ZONE_INFO.name(), + assertEquals(new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); } @Test public void testApplyChangeRequestWithOptions() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(dnsRpcMock.applyChangeRequest(EasyMock.eq(ZONE_INFO.name()), + EasyMock.expect(dnsRpcMock.applyChangeRequest(EasyMock.eq(ZONE_INFO.getName()), 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(), + ChangeRequest changeRequest = dns.applyChangeRequest(ZONE_INFO.getName(), CHANGE_REQUEST_PARTIAL, CHANGE_GET_FIELDS); - String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.rpcOption()); - assertEquals(new ChangeRequest(dns, ZONE_INFO.name(), + String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.getRpcOption()); + assertEquals(new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); @@ -275,16 +276,16 @@ public void testApplyChangeRequestWithOptions() { // lists @Test public void testListChangeRequests() { - EasyMock.expect(dnsRpcMock.listChangeRequests(ZONE_INFO.name(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(dnsRpcMock.listChangeRequests(ZONE_INFO.getName(), EMPTY_RPC_OPTIONS)) .andReturn(LIST_RESULT_OF_PB_CHANGES); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl - Page changeRequestPage = dns.listChangeRequests(ZONE_INFO.name()); + Page changeRequestPage = dns.listChangeRequests(ZONE_INFO.getName()); assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( - new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)))); assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( - new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_PARTIAL)))); assertEquals(2, Lists.newArrayList(changeRequestPage.values()).size()); } @@ -298,20 +299,21 @@ public void testListChangeRequestsWithOptions() { dns = options.service(); // creates DnsImpl Page changeRequestPage = dns.listChangeRequests(ZONE_NAME, CHANGE_LIST_OPTIONS); assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( - new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)))); assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( - new ChangeRequest(dns, ZONE_INFO.name(), + new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_PARTIAL)))); assertEquals(2, Lists.newArrayList(changeRequestPage.values()).size()); - Integer size = (Integer) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[0].rpcOption()); + Integer size = (Integer) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[0].getRpcOption()); assertEquals(MAX_SIZE, size); - String selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[1].rpcOption()); + String selector = + (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[1].getRpcOption()); assertEquals(PAGE_TOKEN, selector); - selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[2].rpcOption()); + selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[2].getRpcOption()); assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); - selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[3].rpcOption()); + selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[3].getRpcOption()); assertTrue(selector.contains(Dns.SortingOrder.ASCENDING.selector())); } @@ -338,24 +340,24 @@ public void testListZonesWithOptions() { assertEquals(1, Lists.newArrayList(zonePage.values()).size()); 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()); + Integer size = (Integer) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[0].getRpcOption()); assertEquals(MAX_SIZE, size); - String selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[1].rpcOption()); + String selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[1].getRpcOption()); assertEquals(PAGE_TOKEN, selector); - selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[2].rpcOption()); + selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[2].getRpcOption()); assertTrue(selector.contains(Dns.ZoneField.DESCRIPTION.selector())); assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); - selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[3].rpcOption()); + selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[3].getRpcOption()); assertEquals(DNS_NAME, selector); } @Test public void testListRecordSets() { - EasyMock.expect(dnsRpcMock.listRecordSets(ZONE_INFO.name(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(dnsRpcMock.listRecordSets(ZONE_INFO.getName(), EMPTY_RPC_OPTIONS)) .andReturn(LIST_OF_PB_DNS_RECORDS); EasyMock.replay(dnsRpcMock); dns = options.service(); // creates DnsImpl - Page dnsPage = dns.listRecordSets(ZONE_INFO.name()); + Page dnsPage = dns.listRecordSets(ZONE_INFO.getName()); assertEquals(2, Lists.newArrayList(dnsPage.values()).size()); assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD1)); assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD2)); @@ -372,18 +374,19 @@ public void testListRecordSetsWithOptions() { 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(RECORD_SET_LIST_OPTIONS[0].rpcOption()); + Integer size = + (Integer) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[0].getRpcOption()); assertEquals(MAX_SIZE, size); String selector = (String) capturedOptions.getValue() - .get(RECORD_SET_LIST_OPTIONS[1].rpcOption()); + .get(RECORD_SET_LIST_OPTIONS[1].getRpcOption()); assertEquals(PAGE_TOKEN, selector); - selector = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[2].rpcOption()); + selector = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[2].getRpcOption()); assertTrue(selector.contains(Dns.RecordSetField.NAME.selector())); assertTrue(selector.contains(Dns.RecordSetField.TTL.selector())); - selector = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[3].rpcOption()); - assertEquals(RECORD_SET_LIST_OPTIONS[3].value(), selector); + selector = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[3].getRpcOption()); + assertEquals(RECORD_SET_LIST_OPTIONS[3].getValue(), selector); String type = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[4] - .rpcOption()); - assertEquals(RECORD_SET_LIST_OPTIONS[4].value(), type); + .getRpcOption()); + assertEquals(RECORD_SET_LIST_OPTIONS[4].getValue(), type); } } diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsTest.java index 91d46e94262d..b5561235da45 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsTest.java @@ -34,31 +34,31 @@ public void testRecordSetListOption() { // dns name String dnsName = "some name"; Dns.RecordSetListOption recordSetListOption = Dns.RecordSetListOption.dnsName(dnsName); - assertEquals(dnsName, recordSetListOption.value()); - assertEquals(DnsRpc.Option.NAME, recordSetListOption.rpcOption()); + assertEquals(dnsName, recordSetListOption.getValue()); + assertEquals(DnsRpc.Option.NAME, recordSetListOption.getRpcOption()); // page token recordSetListOption = Dns.RecordSetListOption.pageToken(PAGE_TOKEN); - assertEquals(PAGE_TOKEN, recordSetListOption.value()); - assertEquals(DnsRpc.Option.PAGE_TOKEN, recordSetListOption.rpcOption()); + assertEquals(PAGE_TOKEN, recordSetListOption.getValue()); + assertEquals(DnsRpc.Option.PAGE_TOKEN, recordSetListOption.getRpcOption()); // page size recordSetListOption = Dns.RecordSetListOption.pageSize(PAGE_SIZE); - assertEquals(PAGE_SIZE, recordSetListOption.value()); - assertEquals(DnsRpc.Option.PAGE_SIZE, recordSetListOption.rpcOption()); + assertEquals(PAGE_SIZE, recordSetListOption.getValue()); + assertEquals(DnsRpc.Option.PAGE_SIZE, recordSetListOption.getRpcOption()); // record type RecordSet.Type recordType = RecordSet.Type.AAAA; recordSetListOption = Dns.RecordSetListOption.type(recordType); - assertEquals(recordType.name(), recordSetListOption.value()); - assertEquals(DnsRpc.Option.DNS_TYPE, recordSetListOption.rpcOption()); + assertEquals(recordType.name(), recordSetListOption.getValue()); + assertEquals(DnsRpc.Option.DNS_TYPE, recordSetListOption.getRpcOption()); // fields 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( + assertEquals(DnsRpc.Option.FIELDS, recordSetListOption.getRpcOption()); + assertTrue(recordSetListOption.getValue() instanceof String); + assertTrue(((String) recordSetListOption.getValue()).contains( Dns.RecordSetField.NAME.selector())); - assertTrue(((String) recordSetListOption.value()).contains( + assertTrue(((String) recordSetListOption.getValue()).contains( Dns.RecordSetField.TTL.selector())); - assertTrue(((String) recordSetListOption.value()).contains( + assertTrue(((String) recordSetListOption.getValue()).contains( Dns.RecordSetField.NAME.selector())); } @@ -66,10 +66,10 @@ public void testRecordSetListOption() { 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())); + assertEquals(DnsRpc.Option.FIELDS, fields.getRpcOption()); + assertTrue(fields.getValue() instanceof String); + assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.CREATION_TIME.selector())); + assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.DESCRIPTION.selector())); } @Test @@ -77,33 +77,33 @@ 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.NAME.selector())); + assertEquals(DnsRpc.Option.FIELDS, fields.getRpcOption()); + assertTrue(fields.getValue() instanceof String); + assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.CREATION_TIME.selector())); + assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.DESCRIPTION.selector())); + assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.NAME.selector())); // page token Dns.ZoneListOption option = Dns.ZoneListOption.pageToken(PAGE_TOKEN); - assertEquals(PAGE_TOKEN, option.value()); - assertEquals(DnsRpc.Option.PAGE_TOKEN, option.rpcOption()); + assertEquals(PAGE_TOKEN, option.getValue()); + assertEquals(DnsRpc.Option.PAGE_TOKEN, option.getRpcOption()); // page size option = Dns.ZoneListOption.pageSize(PAGE_SIZE); - assertEquals(PAGE_SIZE, option.value()); - assertEquals(DnsRpc.Option.PAGE_SIZE, option.rpcOption()); + assertEquals(PAGE_SIZE, option.getValue()); + assertEquals(DnsRpc.Option.PAGE_SIZE, option.getRpcOption()); // dnsName filter option = Dns.ZoneListOption.dnsName(DNS_NAME); - assertEquals(DNS_NAME, option.value()); - assertEquals(DnsRpc.Option.DNS_NAME, option.rpcOption()); + assertEquals(DNS_NAME, option.getValue()); + assertEquals(DnsRpc.Option.DNS_NAME, option.getRpcOption()); } @Test public void testProjectGetOption() { // fields 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())); - assertTrue(((String) fields.value()).contains(Dns.ProjectField.PROJECT_ID.selector())); + assertEquals(DnsRpc.Option.FIELDS, fields.getRpcOption()); + assertTrue(fields.getValue() instanceof String); + assertTrue(((String) fields.getValue()).contains(Dns.ProjectField.QUOTA.selector())); + assertTrue(((String) fields.getValue()).contains(Dns.ProjectField.PROJECT_ID.selector())); } @Test @@ -111,12 +111,12 @@ 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( + assertEquals(DnsRpc.Option.FIELDS, fields.getRpcOption()); + assertTrue(fields.getValue() instanceof String); + assertTrue(((String) fields.getValue()).contains( Dns.ChangeRequestField.START_TIME.selector())); - assertTrue(((String) fields.value()).contains(Dns.ChangeRequestField.STATUS.selector())); - assertTrue(((String) fields.value()).contains(Dns.ChangeRequestField.ID.selector())); + assertTrue(((String) fields.getValue()).contains(Dns.ChangeRequestField.STATUS.selector())); + assertTrue(((String) fields.getValue()).contains(Dns.ChangeRequestField.ID.selector())); } @Test @@ -124,23 +124,23 @@ 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( + assertEquals(DnsRpc.Option.FIELDS, fields.getRpcOption()); + assertTrue(fields.getValue() instanceof String); + assertTrue(((String) fields.getValue()).contains( Dns.ChangeRequestField.START_TIME.selector())); - assertTrue(((String) fields.value()).contains(Dns.ChangeRequestField.STATUS.selector())); - assertTrue(((String) fields.value()).contains(Dns.ChangeRequestField.ID.selector())); + assertTrue(((String) fields.getValue()).contains(Dns.ChangeRequestField.STATUS.selector())); + assertTrue(((String) fields.getValue()).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()); + assertEquals(PAGE_TOKEN, option.getValue()); + assertEquals(DnsRpc.Option.PAGE_TOKEN, option.getRpcOption()); // page size option = Dns.ChangeRequestListOption.pageSize(PAGE_SIZE); - assertEquals(PAGE_SIZE, option.value()); - assertEquals(DnsRpc.Option.PAGE_SIZE, option.rpcOption()); + assertEquals(PAGE_SIZE, option.getValue()); + assertEquals(DnsRpc.Option.PAGE_SIZE, option.getRpcOption()); // sort order option = Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING); - assertEquals(DnsRpc.Option.SORTING_ORDER, option.rpcOption()); - assertEquals(Dns.SortingOrder.ASCENDING.selector(), option.value()); + assertEquals(DnsRpc.Option.SORTING_ORDER, option.getRpcOption()); + assertEquals(Dns.SortingOrder.ASCENDING.selector(), option.getValue()); } } diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/OptionTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/OptionTest.java index 1e5be1287ceb..1b92ad65b0b4 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/OptionTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/OptionTest.java @@ -54,11 +54,11 @@ public void testHashCode() { @Test public void testConstructor() { - assertEquals(RPC_OPTION, OPTION.rpcOption()); - assertEquals(VALUE, OPTION.value()); + assertEquals(RPC_OPTION, OPTION.getRpcOption()); + assertEquals(VALUE, OPTION.getValue()); Option option = new Option(RPC_OPTION, null) {}; - assertEquals(RPC_OPTION, option.rpcOption()); - assertNull(option.value()); + assertEquals(RPC_OPTION, option.getRpcOption()); + assertNull(option.getValue()); thrown.expect(NullPointerException.class); new Option(null, VALUE) {}; } diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/ProjectInfoTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/ProjectInfoTest.java index 70086250e6dd..1bef06d2d705 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/ProjectInfoTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/ProjectInfoTest.java @@ -29,30 +29,59 @@ 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(); + private static final ProjectInfo PROJECT_INFO = ProjectInfo.newBuilder() + .setId(ID).setNumber(NUMBER).setQuota(QUOTA).build(); @Test public void testBuilder() { - ProjectInfo withId = ProjectInfo.builder().id(ID).build(); + ProjectInfo withId = ProjectInfo.newBuilder().setId(ID).build(); + assertEquals(ID, withId.getId()); + assertNull(withId.getNumber()); + assertNull(withId.getQuota()); + ProjectInfo withNumber = ProjectInfo.newBuilder().setNumber(NUMBER).build(); + assertEquals(NUMBER, withNumber.getNumber()); + assertNull(withNumber.getQuota()); + assertNull(withNumber.getId()); + ProjectInfo withQuota = ProjectInfo.newBuilder().setQuota(QUOTA).build(); + assertEquals(QUOTA, withQuota.getQuota()); + assertNull(withQuota.getId()); + assertNull(withQuota.getNumber()); + assertEquals(QUOTA, PROJECT_INFO.getQuota()); + assertEquals(NUMBER, PROJECT_INFO.getNumber()); + assertEquals(ID, PROJECT_INFO.getId()); + } + + @Test + public void testBuilderDeprecated() { + ProjectInfo withId = ProjectInfo.newBuilder().setId(ID).build(); assertEquals(ID, withId.id()); - assertNull(withId.number()); + assertNull(withId.getNumber()); assertNull(withId.quota()); - ProjectInfo withNumber = ProjectInfo.builder().number(NUMBER).build(); - assertEquals(NUMBER, withNumber.number()); + ProjectInfo withNumber = ProjectInfo.newBuilder().setNumber(NUMBER).build(); + assertEquals(NUMBER, withNumber.getNumber()); assertNull(withNumber.quota()); assertNull(withNumber.id()); - ProjectInfo withQuota = ProjectInfo.builder().quota(QUOTA).build(); + ProjectInfo withQuota = ProjectInfo.newBuilder().setQuota(QUOTA).build(); assertEquals(QUOTA, withQuota.quota()); assertNull(withQuota.id()); - assertNull(withQuota.number()); + assertNull(withQuota.getNumber()); assertEquals(QUOTA, PROJECT_INFO.quota()); - assertEquals(NUMBER, PROJECT_INFO.number()); + assertEquals(NUMBER, PROJECT_INFO.getNumber()); assertEquals(ID, PROJECT_INFO.id()); } @Test public void testQuotaConstructor() { + assertEquals(1, QUOTA.getZones()); + assertEquals(2, QUOTA.getResourceRecordsPerRrset()); + assertEquals(3, QUOTA.getRrsetAdditionsPerChange()); + assertEquals(4, QUOTA.getRrsetDeletionsPerChange()); + assertEquals(5, QUOTA.getRrsetsPerZone()); + assertEquals(6, QUOTA.getTotalRrdataSizePerChange()); + } + + @Test + public void testQuotaConstructorDeprecated() { assertEquals(1, QUOTA.zones()); assertEquals(2, QUOTA.resourceRecordsPerRrset()); assertEquals(3, QUOTA.rrsetAdditionsPerChange()); @@ -78,13 +107,22 @@ public void testSameHashCodeOnEqualsQuota() { @Test public void testEqualsAndNotEquals() { - ProjectInfo clone = ProjectInfo.builder().build(); + ProjectInfo clone = ProjectInfo.newBuilder().build(); assertNotEquals(PROJECT_INFO, clone); - clone = ProjectInfo.builder().id(PROJECT_INFO.id()).number(PROJECT_INFO.number()).build(); + clone = ProjectInfo.newBuilder() + .setId(PROJECT_INFO.getId()) + .setNumber(PROJECT_INFO.getNumber()) + .build(); assertNotEquals(PROJECT_INFO, clone); - clone = ProjectInfo.builder().id(PROJECT_INFO.id()).quota(PROJECT_INFO.quota()).build(); + clone = ProjectInfo.newBuilder() + .setId(PROJECT_INFO.getId()) + .setQuota(PROJECT_INFO.getQuota()) + .build(); assertNotEquals(PROJECT_INFO, clone); - clone = ProjectInfo.builder().number(PROJECT_INFO.number()).quota(PROJECT_INFO.quota()).build(); + clone = ProjectInfo.newBuilder() + .setNumber(PROJECT_INFO.getNumber()) + .setQuota(PROJECT_INFO.getQuota()) + .build(); assertNotEquals(PROJECT_INFO, clone); clone = ProjectInfo.fromPb(PROJECT_INFO.toPb()); assertEquals(PROJECT_INFO, clone); @@ -100,11 +138,11 @@ public void testSameHashCodeOnEquals() { @Test public void testToAndFromPb() { assertEquals(PROJECT_INFO, ProjectInfo.fromPb(PROJECT_INFO.toPb())); - ProjectInfo partial = ProjectInfo.builder().id(ID).build(); + ProjectInfo partial = ProjectInfo.newBuilder().setId(ID).build(); assertEquals(partial, ProjectInfo.fromPb(partial.toPb())); - partial = ProjectInfo.builder().number(NUMBER).build(); + partial = ProjectInfo.newBuilder().setNumber(NUMBER).build(); assertEquals(partial, ProjectInfo.fromPb(partial.toPb())); - partial = ProjectInfo.builder().quota(QUOTA).build(); + partial = ProjectInfo.newBuilder().setQuota(QUOTA).build(); assertEquals(partial, ProjectInfo.fromPb(partial.toPb())); assertNotEquals(PROJECT_INFO, partial); } diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/RecordSetTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/RecordSetTest.java index f5c515b6752d..2200e7844302 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/RecordSetTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/RecordSetTest.java @@ -32,12 +32,23 @@ public class RecordSetTest { private static final TimeUnit UNIT = TimeUnit.HOURS; private static final Integer UNIT_TTL = 1; private static final RecordSet.Type TYPE = RecordSet.Type.AAAA; - private static final RecordSet recordSet = RecordSet.builder(NAME, TYPE) + private static final RecordSet RECORD_SET = RecordSet.newBuilder(NAME, TYPE) + .setTtl(UNIT_TTL, UNIT) + .build(); + private static final RecordSet DEPRECATED_RECORD_SET = RecordSet.builder(NAME, TYPE) .ttl(UNIT_TTL, UNIT) .build(); @Test public void testDefaultDnsRecord() { + RecordSet recordSet = RecordSet.newBuilder(NAME, TYPE).build(); + assertEquals(0, recordSet.getRecords().size()); + assertEquals(TYPE, recordSet.getType()); + assertEquals(NAME, recordSet.getName()); + } + + @Test + public void testDefaultDnsRecordDeprecated() { RecordSet recordSet = RecordSet.builder(NAME, TYPE).build(); assertEquals(0, recordSet.records().size()); assertEquals(TYPE, recordSet.type()); @@ -46,14 +57,32 @@ public void testDefaultDnsRecord() { @Test public void testBuilder() { - assertEquals(NAME, recordSet.name()); - assertEquals(TTL, recordSet.ttl()); - assertEquals(TYPE, recordSet.type()); - assertEquals(0, recordSet.records().size()); + assertEquals(NAME, RECORD_SET.getName()); + assertEquals(TTL, RECORD_SET.getTtl()); + assertEquals(TYPE, RECORD_SET.getType()); + assertEquals(0, RECORD_SET.getRecords().size()); // verify that one can add records to the record set String testingRecord = "Testing recordSet"; String anotherTestingRecord = "Another recordSet 123"; - RecordSet anotherRecord = recordSet.toBuilder() + RecordSet anotherRecord = RECORD_SET.toBuilder() + .addRecord(testingRecord) + .addRecord(anotherTestingRecord) + .build(); + assertEquals(2, anotherRecord.getRecords().size()); + assertTrue(anotherRecord.getRecords().contains(testingRecord)); + assertTrue(anotherRecord.getRecords().contains(anotherTestingRecord)); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(NAME, DEPRECATED_RECORD_SET.name()); + assertEquals(TTL, DEPRECATED_RECORD_SET.ttl()); + assertEquals(TYPE, DEPRECATED_RECORD_SET.type()); + assertEquals(0, DEPRECATED_RECORD_SET.records().size()); + // verify that one can add records to the record set + String testingRecord = "Testing recordSet"; + String anotherTestingRecord = "Another recordSet 123"; + RecordSet anotherRecord = RECORD_SET.toBuilder() .addRecord(testingRecord) .addRecord(anotherTestingRecord) .build(); @@ -64,6 +93,26 @@ public void testBuilder() { @Test public void testValidTtl() { + try { + RecordSet.newBuilder(NAME, TYPE).setTtl(-1, TimeUnit.SECONDS); + fail("A negative value is not acceptable for ttl."); + } catch (IllegalArgumentException e) { + // expected + } + RecordSet.newBuilder(NAME, TYPE).setTtl(0, TimeUnit.SECONDS); + RecordSet.newBuilder(NAME, TYPE).setTtl(Integer.MAX_VALUE, TimeUnit.SECONDS); + try { + RecordSet.newBuilder(NAME, TYPE).setTtl(Integer.MAX_VALUE, TimeUnit.HOURS); + fail("This value is too large for int."); + } catch (IllegalArgumentException e) { + // expected + } + RecordSet record = RecordSet.newBuilder(NAME, TYPE).setTtl(UNIT_TTL, UNIT).build(); + assertEquals(TTL, record.getTtl()); + } + + @Test + public void testValidTtlDeprecated() { try { RecordSet.builder(NAME, TYPE).ttl(-1, TimeUnit.SECONDS); fail("A negative value is not acceptable for ttl."); @@ -84,45 +133,45 @@ public void testValidTtl() { @Test public void testEqualsAndNotEquals() { - RecordSet clone = recordSet.toBuilder().build(); - assertEquals(recordSet, clone); - clone = recordSet.toBuilder().addRecord("another recordSet").build(); - assertNotEquals(recordSet, clone); + RecordSet clone = RECORD_SET.toBuilder().build(); + assertEquals(RECORD_SET, clone); + clone = RECORD_SET.toBuilder().addRecord("another recordSet").build(); + assertNotEquals(RECORD_SET, clone); String differentName = "totally different name"; - 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); + clone = RECORD_SET.toBuilder().setName(differentName).build(); + assertNotEquals(RECORD_SET, clone); + clone = RECORD_SET.toBuilder().setTtl(RECORD_SET.getTtl() + 1, TimeUnit.SECONDS).build(); + assertNotEquals(RECORD_SET, clone); + clone = RECORD_SET.toBuilder().setType(RecordSet.Type.TXT).build(); + assertNotEquals(RECORD_SET, clone); } @Test public void testSameHashCodeOnEquals() { - int hash = recordSet.hashCode(); - RecordSet clone = recordSet.toBuilder().build(); + int hash = RECORD_SET.hashCode(); + RecordSet clone = RECORD_SET.toBuilder().build(); assertEquals(clone.hashCode(), hash); } @Test public void testToAndFromPb() { - assertEquals(recordSet, RecordSet.fromPb(recordSet.toPb())); - RecordSet partial = RecordSet.builder(NAME, TYPE).build(); + assertEquals(RECORD_SET, RecordSet.fromPb(RECORD_SET.toPb())); + RecordSet partial = RecordSet.newBuilder(NAME, TYPE).build(); assertEquals(partial, RecordSet.fromPb(partial.toPb())); - partial = RecordSet.builder(NAME, TYPE).addRecord("test").build(); + partial = RecordSet.newBuilder(NAME, TYPE).addRecord("test").build(); assertEquals(partial, RecordSet.fromPb(partial.toPb())); - partial = RecordSet.builder(NAME, TYPE).ttl(15, TimeUnit.SECONDS).build(); + partial = RecordSet.newBuilder(NAME, TYPE).setTtl(15, TimeUnit.SECONDS).build(); assertEquals(partial, RecordSet.fromPb(partial.toPb())); } @Test public void testToBuilder() { - assertEquals(recordSet, recordSet.toBuilder().build()); - RecordSet partial = RecordSet.builder(NAME, TYPE).build(); + assertEquals(RECORD_SET, RECORD_SET.toBuilder().build()); + RecordSet partial = RecordSet.newBuilder(NAME, TYPE).build(); assertEquals(partial, partial.toBuilder().build()); - partial = RecordSet.builder(NAME, TYPE).addRecord("test").build(); + partial = RecordSet.newBuilder(NAME, TYPE).addRecord("test").build(); assertEquals(partial, partial.toBuilder().build()); - partial = RecordSet.builder(NAME, TYPE).ttl(15, TimeUnit.SECONDS).build(); + partial = RecordSet.newBuilder(NAME, TYPE).setTtl(15, TimeUnit.SECONDS).build(); assertEquals(partial, partial.toBuilder().build()); } @@ -130,10 +179,10 @@ public void testToBuilder() { public void clearRecordSet() { // make sure that we are starting not empty RecordSet clone = - recordSet.toBuilder().addRecord("record").addRecord("another").build(); - assertNotEquals(0, clone.records().size()); + RECORD_SET.toBuilder().addRecord("record").addRecord("another").build(); + assertNotEquals(0, clone.getRecords().size()); clone = clone.toBuilder().clearRecords().build(); - assertEquals(0, clone.records().size()); + assertEquals(0, clone.getRecords().size()); clone.toPb(); // verify that pb allows it } @@ -141,9 +190,9 @@ public void clearRecordSet() { public void removeFromRecordSet() { String recordString = "record"; // make sure that we are starting not empty - RecordSet clone = recordSet.toBuilder().addRecord(recordString).build(); - assertNotEquals(0, clone.records().size()); + RecordSet clone = RECORD_SET.toBuilder().addRecord(recordString).build(); + assertNotEquals(0, clone.getRecords().size()); clone = clone.toBuilder().removeRecord(recordString).build(); - assertEquals(0, clone.records().size()); + assertEquals(0, clone.getRecords().size()); } } diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java index 2115c9dd98bf..15af4d07c6a9 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java @@ -22,8 +22,6 @@ import com.google.cloud.RetryParams; import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableList; - import java.io.Serializable; import java.math.BigInteger; import java.util.concurrent.TimeUnit; @@ -32,18 +30,19 @@ public class SerializationTest extends BaseSerializationTest { private static final ZoneInfo FULL_ZONE_INFO = Zone.of("some zone name", "www.example.com", "some descriptions").toBuilder() - .creationTimeMillis(132L) - .generatedId("123333") - .nameServers(ImmutableList.of("server 1", "server 2")) - .nameServerSet("specificationstring") + .setCreationTimeMillis(132L) + .setGeneratedId("123333") + .setNameServers(ImmutableList.of("server 1", "server 2")) + .setNameServerSet("specificationstring") .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") - .number(new BigInteger("2343245")) - .quota(new ProjectInfo.Quota(12, 13, 14, 15, 16, 17)) + private static final ProjectInfo PARTIAL_PROJECT_INFO = + ProjectInfo.newBuilder().setId("13").build(); + private static final ProjectInfo FULL_PROJECT_INFO = ProjectInfo.newBuilder() + .setId("342") + .setNumber(new BigInteger("2343245")) + .setQuota(new ProjectInfo.Quota(12, 13, 14, 15, 16, 17)) .build(); private static final Dns.ZoneListOption ZONE_LIST_OPTION = Dns.ZoneListOption.dnsName("www.example.com."); @@ -66,23 +65,24 @@ public class SerializationTest extends BaseSerializationTest { private static final Zone PARTIAL_ZONE = new Zone(DNS, new ZoneInfo.BuilderImpl(PARTIAL_ZONE_INFO)); private static final ChangeRequestInfo CHANGE_REQUEST_INFO_PARTIAL = - ChangeRequest.builder().build(); + ChangeRequest.newBuilder().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(); + RecordSet.newBuilder("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) + RecordSet.newBuilder("www.sadfa.com", RecordSet.Type.A) + .setTtl(12, TimeUnit.HOURS) .addRecord("record") .build(); - private static final ChangeRequestInfo CHANGE_REQUEST_INFO_COMPLETE = ChangeRequestInfo.builder() - .add(RECORD_SET_COMPLETE) - .delete(RECORD_SET_PARTIAL) - .status(ChangeRequest.Status.PENDING) - .generatedId("some id") - .startTimeMillis(132L) - .build(); + private static final ChangeRequestInfo CHANGE_REQUEST_INFO_COMPLETE = + ChangeRequestInfo.newBuilder() + .add(RECORD_SET_COMPLETE) + .delete(RECORD_SET_PARTIAL) + .setStatus(ChangeRequest.Status.PENDING) + .setGeneratedId("some id") + .setStartTime(132L) + .build(); private static final ChangeRequest CHANGE_REQUEST_COMPLETE = new ChangeRequest(DNS, "name", new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_INFO_COMPLETE)); diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/ZoneInfoTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/ZoneInfoTest.java index 215d377f6a67..7de2cdac1d57 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/ZoneInfoTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/ZoneInfoTest.java @@ -43,26 +43,40 @@ public class ZoneInfoTest { 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.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() - .creationTimeMillis(CREATION_TIME_MILLIS) - .generatedId(GENERATED_ID) - .nameServerSet(NAME_SERVER_SET) - .nameServers(NAME_SERVERS) + .setCreationTimeMillis(CREATION_TIME_MILLIS) + .setGeneratedId(GENERATED_ID) + .setNameServerSet(NAME_SERVER_SET) + .setNameServers(NAME_SERVERS) .build(); @Test public void testOf() { ZoneInfo partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION); - assertTrue(partial.nameServers().isEmpty()); - assertEquals(NAME, partial.name()); - assertNull(partial.generatedId()); - assertNull(partial.creationTimeMillis()); - assertNull(partial.nameServerSet()); - assertEquals(DESCRIPTION, partial.description()); - assertEquals(DNS_NAME, partial.dnsName()); + assertTrue(partial.getNameServers().isEmpty()); + assertEquals(NAME, partial.getName()); + assertNull(partial.getGeneratedId()); + assertNull(partial.getCreationTimeMillis()); + assertNull(partial.getNameServerSet()); + assertEquals(DESCRIPTION, partial.getDescription()); + assertEquals(DNS_NAME, partial.getDnsName()); } @Test public void testBuilder() { + assertEquals(3, INFO.getNameServers().size()); + assertEquals(NS1, INFO.getNameServers().get(0)); + assertEquals(NS2, INFO.getNameServers().get(1)); + assertEquals(NS3, INFO.getNameServers().get(2)); + assertEquals(NAME, INFO.getName()); + assertEquals(GENERATED_ID, INFO.getGeneratedId()); + assertEquals(CREATION_TIME_MILLIS, INFO.getCreationTimeMillis()); + assertEquals(NAME_SERVER_SET, INFO.getNameServerSet()); + assertEquals(DESCRIPTION, INFO.getDescription()); + assertEquals(DNS_NAME, INFO.getDnsName()); + } + + @Test + public void testBuilderDeprecated() { assertEquals(3, INFO.nameServers().size()); assertEquals(NS1, INFO.nameServers().get(0)); assertEquals(NS2, INFO.nameServers().get(1)); @@ -81,20 +95,20 @@ public void testEqualsAndNotEquals() { assertEquals(INFO, clone); List moreServers = Lists.newLinkedList(NAME_SERVERS); moreServers.add(NS1); - clone = INFO.toBuilder().nameServers(moreServers).build(); + clone = INFO.toBuilder().setNameServers(moreServers).build(); assertNotEquals(INFO, clone); String differentName = "totally different name"; - clone = INFO.toBuilder().name(differentName).build(); + clone = INFO.toBuilder().setName(differentName).build(); assertNotEquals(INFO, clone); - clone = INFO.toBuilder().creationTimeMillis(INFO.creationTimeMillis() + 1).build(); + clone = INFO.toBuilder().setCreationTimeMillis(INFO.getCreationTimeMillis() + 1).build(); assertNotEquals(INFO, clone); - clone = INFO.toBuilder().description(INFO.description() + "aaaa").build(); + clone = INFO.toBuilder().setDescription(INFO.getDescription() + "aaaa").build(); assertNotEquals(INFO, clone); - clone = INFO.toBuilder().dnsName(differentName).build(); + clone = INFO.toBuilder().setDnsName(differentName).build(); assertNotEquals(INFO, clone); - clone = INFO.toBuilder().generatedId(INFO.generatedId() + "1111").build(); + clone = INFO.toBuilder().setGeneratedId(INFO.getGeneratedId() + "1111").build(); assertNotEquals(INFO, clone); - clone = INFO.toBuilder().nameServerSet(INFO.nameServerSet() + "salt").build(); + clone = INFO.toBuilder().setNameServerSet(INFO.getNameServerSet() + "salt").build(); assertNotEquals(INFO, clone); } @@ -111,17 +125,17 @@ public void testToBuilder() { ZoneInfo partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION); assertEquals(partial, partial.toBuilder().build()); partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() - .generatedId(GENERATED_ID) + .setGeneratedId(GENERATED_ID) .build(); assertEquals(partial, partial.toBuilder().build()); partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() - .creationTimeMillis(CREATION_TIME_MILLIS).build(); + .setCreationTimeMillis(CREATION_TIME_MILLIS).build(); assertEquals(partial, partial.toBuilder().build()); List nameServers = new LinkedList<>(); nameServers.add(NS1); - partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().nameServers(nameServers).build(); + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().setNameServers(nameServers).build(); assertEquals(partial, partial.toBuilder().build()); - partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().nameServerSet(NAME_SERVER_SET) + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().setNameServerSet(NAME_SERVER_SET) .build(); assertEquals(partial, partial.toBuilder().build()); } @@ -132,25 +146,25 @@ public void testToAndFromPb() { ZoneInfo partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() - .generatedId(GENERATED_ID) + .setGeneratedId(GENERATED_ID) .build(); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder() - .creationTimeMillis(CREATION_TIME_MILLIS).build(); + .setCreationTimeMillis(CREATION_TIME_MILLIS).build(); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); List nameServers = new LinkedList<>(); nameServers.add(NS1); - partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().nameServers(nameServers).build(); + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().setNameServers(nameServers).build(); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); - partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().nameServerSet(NAME_SERVER_SET) + partial = ZoneInfo.of(NAME, DNS_NAME, DESCRIPTION).toBuilder().setNameServerSet(NAME_SERVER_SET) .build(); assertEquals(partial, ZoneInfo.fromPb(partial.toPb())); } @Test public void testEmptyNameServers() { - ZoneInfo clone = INFO.toBuilder().nameServers(new LinkedList()).build(); - assertTrue(clone.nameServers().isEmpty()); + ZoneInfo clone = INFO.toBuilder().setNameServers(new LinkedList()).build(); + assertTrue(clone.getNameServers().isEmpty()); clone.toPb(); // test that this is allowed } diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/ZoneTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/ZoneTest.java index aefc716bf46a..05846d120fd6 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/ZoneTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/ZoneTest.java @@ -45,12 +45,12 @@ public class ZoneTest { private static final String ZONE_ID = "123"; private static final ZoneInfo ZONE_INFO = Zone.of(ZONE_NAME, "example.com", "description") .toBuilder() - .generatedId(ZONE_ID) - .creationTimeMillis(123478946464L) + .setGeneratedId(ZONE_ID) + .setCreationTimeMillis(123478946464L) .build(); private static final ZoneInfo NO_ID_INFO = ZoneInfo.of(ZONE_NAME, "another-example.com", "description").toBuilder() - .creationTimeMillis(893123464L) + .setCreationTimeMillis(893123464L) .build(); private static final Dns.ZoneOption ZONE_FIELD_OPTIONS = Dns.ZoneOption.fields(Dns.ZoneField.CREATION_TIME); @@ -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 = - ChangeRequestInfo.builder().generatedId("someid").build(); + ChangeRequestInfo.newBuilder().setGeneratedId("someid").build(); private static final ChangeRequestInfo CHANGE_REQUEST_NO_ID = - ChangeRequestInfo.builder().build(); + ChangeRequestInfo.newBuilder().build(); private static final DnsException EXCEPTION = new DnsException(-1, "message", null); private static final DnsOptions OPTIONS = createStrictMock(DnsOptions.class); @@ -80,7 +80,7 @@ public void setUp() throws Exception { 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())); + CHANGE_REQUEST.toBuilder().setStartTime(123465L).build())); reset(dns); } @@ -91,6 +91,14 @@ public void tearDown() throws Exception { @Test public void testConstructor() { + replay(dns); + assertEquals(ZONE_INFO.toPb(), zone.toPb()); + assertNotNull(zone.getDns()); + assertEquals(dns, zone.getDns()); + } + + @Test + public void testConstructorDeprecated() { replay(dns); assertEquals(ZONE_INFO.toPb(), zone.toPb()); assertNotNull(zone.dns()); @@ -175,10 +183,10 @@ public void reloadByNameAndFound() { expect(dns.getZone(ZONE_NAME, ZONE_FIELD_OPTIONS)).andReturn(zone); replay(dns); Zone result = zoneNoId.reload(); - assertSame(zone.dns(), result.dns()); + assertSame(zone.getDns(), result.getDns()); assertEquals(zone, result); result = zone.reload(); - assertSame(zone.dns(), result.dns()); + assertSame(zone.getDns(), result.getDns()); assertEquals(zone, result); zoneNoId.reload(ZONE_FIELD_OPTIONS); // check options zone.reload(ZONE_FIELD_OPTIONS); // check options @@ -287,52 +295,52 @@ public void applyNullChangeRequest() { @Test public void getChangeAndZoneFoundByName() { - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.generatedId())) + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.getGeneratedId())) .andReturn(changeRequestAfter).times(2); // again for options - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.generatedId(), + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.getGeneratedId(), CHANGE_REQUEST_FIELD_OPTIONS)).andReturn(changeRequestAfter).times(2); replay(dns); - ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.generatedId()); + ChangeRequest result = zoneNoId.getChangeRequest(CHANGE_REQUEST.getGeneratedId()); assertEquals(changeRequestAfter, result); - result = zone.getChangeRequest(CHANGE_REQUEST.generatedId()); + result = zone.getChangeRequest(CHANGE_REQUEST.getGeneratedId()); assertEquals(changeRequestAfter, result); // check options - result = zoneNoId.getChangeRequest(CHANGE_REQUEST.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS); + result = zoneNoId.getChangeRequest(CHANGE_REQUEST.getGeneratedId(), CHANGE_REQUEST_FIELD_OPTIONS); assertEquals(changeRequestAfter, result); - result = zone.getChangeRequest(CHANGE_REQUEST.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS); + result = zone.getChangeRequest(CHANGE_REQUEST.getGeneratedId(), CHANGE_REQUEST_FIELD_OPTIONS); assertEquals(changeRequestAfter, result); } @Test public void getChangeAndZoneNotFoundByName() { - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.generatedId())).andThrow(EXCEPTION) + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.getGeneratedId())).andThrow(EXCEPTION) .times(2); // again for options - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.generatedId(), + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.getGeneratedId(), CHANGE_REQUEST_FIELD_OPTIONS)).andThrow(EXCEPTION).times(2); replay(dns); try { - zoneNoId.getChangeRequest(CHANGE_REQUEST.generatedId()); + zoneNoId.getChangeRequest(CHANGE_REQUEST.getGeneratedId()); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } try { - zone.getChangeRequest(CHANGE_REQUEST.generatedId()); + zone.getChangeRequest(CHANGE_REQUEST.getGeneratedId()); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } // check options try { - zoneNoId.getChangeRequest(CHANGE_REQUEST.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS); + zoneNoId.getChangeRequest(CHANGE_REQUEST.getGeneratedId(), CHANGE_REQUEST_FIELD_OPTIONS); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected } try { - zone.getChangeRequest(CHANGE_REQUEST.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS); + zone.getChangeRequest(CHANGE_REQUEST.getGeneratedId(), CHANGE_REQUEST_FIELD_OPTIONS); fail("Parent container not found, should throw an exception."); } catch (DnsException e) { // expected @@ -341,16 +349,18 @@ public void getChangeAndZoneNotFoundByName() { @Test public void getChangedWhichDoesNotExistZoneFound() { - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.generatedId())).andReturn(null).times(2); + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.getGeneratedId())) + .andReturn(null).times(2); // again for options - expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.generatedId(), + expect(dns.getChangeRequest(ZONE_NAME, CHANGE_REQUEST.getGeneratedId(), CHANGE_REQUEST_FIELD_OPTIONS)).andReturn(null).times(2); replay(dns); - assertNull(zoneNoId.getChangeRequest(CHANGE_REQUEST.generatedId())); - assertNull(zone.getChangeRequest(CHANGE_REQUEST.generatedId())); - assertNull( - zoneNoId.getChangeRequest(CHANGE_REQUEST.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS)); - assertNull(zone.getChangeRequest(CHANGE_REQUEST.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS)); + assertNull(zoneNoId.getChangeRequest(CHANGE_REQUEST.getGeneratedId())); + assertNull(zone.getChangeRequest(CHANGE_REQUEST.getGeneratedId())); + assertNull(zoneNoId.getChangeRequest(CHANGE_REQUEST.getGeneratedId(), + CHANGE_REQUEST_FIELD_OPTIONS)); + assertNull(zone.getChangeRequest(CHANGE_REQUEST.getGeneratedId(), + CHANGE_REQUEST_FIELD_OPTIONS)); } @Test @@ -386,25 +396,26 @@ public void getNullChangeRequest() { public void getChangeRequestWithNoId() { replay(dns); // no calls expected try { - zone.getChangeRequest(CHANGE_REQUEST_NO_ID.generatedId()); + zone.getChangeRequest(CHANGE_REQUEST_NO_ID.getGeneratedId()); fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected } try { - zone.getChangeRequest(CHANGE_REQUEST_NO_ID.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS); + zone.getChangeRequest(CHANGE_REQUEST_NO_ID.getGeneratedId(), CHANGE_REQUEST_FIELD_OPTIONS); fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected } try { - zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID.generatedId()); + zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID.getGeneratedId()); fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected } try { - zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID.generatedId(), CHANGE_REQUEST_FIELD_OPTIONS); + zoneNoId.getChangeRequest(CHANGE_REQUEST_NO_ID.getGeneratedId(), + CHANGE_REQUEST_FIELD_OPTIONS); fail("Cannot get ChangeRequest by null id."); } catch (NullPointerException e) { // expected @@ -484,18 +495,42 @@ public void testBuilder() { expect(dns.options()).andReturn(OPTIONS).times(8); replay(dns); assertNotEquals(zone, zone.toBuilder() - .generatedId(new BigInteger(zone.generatedId()).add(BigInteger.ONE).toString()) + .setGeneratedId(new BigInteger(zone.getGeneratedId()).add(BigInteger.ONE).toString()) + .build()); + assertNotEquals(zone, zone.toBuilder().setDnsName(zone.getName() + "aaaa").build()); + assertNotEquals(zone, + zone.toBuilder().setNameServerSet(zone.getNameServerSet() + "aaaa").build()); + assertNotEquals(zone, + zone.toBuilder().setNameServers(ImmutableList.of("nameserverpppp")).build()); + assertNotEquals(zone, zone.toBuilder().setDnsName(zone.getDnsName() + "aaaa").build()); + assertNotEquals(zone, zone.toBuilder().setCreationTimeMillis(zone.getCreationTimeMillis() + 1) + .build()); + Zone.Builder builder = zone.toBuilder(); + builder.setGeneratedId(ZONE_ID) + .setDnsName("example.com") + .setCreationTimeMillis(123478946464L) + .build(); + assertEquals(zone, builder.build()); + } + + @Test + public void testBuilderDeprecated() { + // one for each build() call because it invokes a constructor + expect(dns.options()).andReturn(OPTIONS).times(8); + replay(dns); + assertNotEquals(zone, zone.toBuilder() + .setGeneratedId(new BigInteger(zone.generatedId()).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().setNameServerSet(zone.nameServerSet() + "aaaa").build()); + assertNotEquals(zone, zone.toBuilder().setNameServers(ImmutableList.of("nameserverpppp")).build()); assertNotEquals(zone, zone.toBuilder().dnsName(zone.dnsName() + "aaaa").build()); - assertNotEquals(zone, zone.toBuilder().creationTimeMillis(zone.creationTimeMillis() + 1) + assertNotEquals(zone, zone.toBuilder().setCreationTimeMillis(zone.creationTimeMillis() + 1) .build()); Zone.Builder builder = zone.toBuilder(); - builder.generatedId(ZONE_ID) + builder.setGeneratedId(ZONE_ID) .dnsName("example.com") - .creationTimeMillis(123478946464L) + .setCreationTimeMillis(123478946464L) .build(); assertEquals(zone, builder.build()); } diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/it/ITDnsTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/it/ITDnsTest.java index 68e3bcfa0678..f3dabf2fdfcb 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/it/ITDnsTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/it/ITDnsTest.java @@ -75,20 +75,20 @@ public class ITDnsTest { private static final ZoneInfo ZONE_DNS_NO_PERIOD = ZoneInfo.of(ZONE_NAME1, ZONE_DNS_NAME_NO_PERIOD, ZONE_DESCRIPTION1); 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) + RecordSet.newBuilder("www." + ZONE1.getDnsName(), RecordSet.Type.A) + .setRecords(ImmutableList.of("123.123.55.1")) + .setTtl(25, TimeUnit.SECONDS) .build(); 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) + RecordSet.newBuilder("www." + ZONE1.getDnsName(), RecordSet.Type.AAAA) + .setRecords(ImmutableList.of("ed:ed:12:aa:36:3:3:105")) + .setTtl(25, TimeUnit.SECONDS) .build(); - private static final ChangeRequestInfo CHANGE_ADD_ZONE1 = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_ADD_ZONE1 = ChangeRequest.newBuilder() .add(A_RECORD_ZONE1) .add(AAAA_RECORD_ZONE1) .build(); - private static final ChangeRequestInfo CHANGE_DELETE_ZONE1 = ChangeRequest.builder() + private static final ChangeRequestInfo CHANGE_DELETE_ZONE1 = ChangeRequest.newBuilder() .delete(A_RECORD_ZONE1) .delete(AAAA_RECORD_ZONE1) .build(); @@ -107,20 +107,21 @@ private static void clear() { when the list has been retrieved and executing the subsequent delete operation. */ Iterator iterator = zone.listChangeRequests().iterateAll(); while (iterator.hasNext()) { - waitForChangeToComplete(zoneName, iterator.next().generatedId()); + waitForChangeToComplete(zoneName, iterator.next().getGeneratedId()); } 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())) { + if (!ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA).contains( + recordSet.getType())) { toDelete.add(recordSet); } } if (!toDelete.isEmpty()) { ChangeRequest deletion = - zone.applyChangeRequest(ChangeRequest.builder().deletions(toDelete).build()); - waitForChangeToComplete(zone.name(), deletion.generatedId()); + zone.applyChangeRequest(ChangeRequest.newBuilder().setDeletions(toDelete).build()); + waitForChangeToComplete(zone.getName(), deletion.getGeneratedId()); } zone.delete(); } @@ -131,7 +132,7 @@ private static List filter(Iterator iterator) { List result = new LinkedList<>(); while (iterator.hasNext()) { Zone zone = iterator.next(); - if (ZONE_NAMES.contains(zone.name())) { + if (ZONE_NAMES.contains(zone.getName())) { result.add(zone); } } @@ -149,10 +150,10 @@ public static void after() { } private static void assertEqChangesIgnoreStatus(ChangeRequest expected, ChangeRequest actual) { - assertEquals(expected.additions(), actual.additions()); - assertEquals(expected.deletions(), actual.deletions()); - assertEquals(expected.generatedId(), actual.generatedId()); - assertEquals(expected.startTimeMillis(), actual.startTimeMillis()); + assertEquals(expected.getAdditions(), actual.getAdditions()); + assertEquals(expected.getDeletions(), actual.getDeletions()); + assertEquals(expected.getGeneratedId(), actual.getGeneratedId()); + assertEquals(expected.getStartTimeMillis(), actual.getStartTimeMillis()); } private static void waitForChangeToComplete(String zoneName, String changeId) { @@ -175,28 +176,28 @@ private static void waitForChangeToComplete(ChangeRequest changeRequest) { public void testCreateValidZone() { try { 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.generatedId()); - Zone retrieved = DNS.getZone(ZONE1.name()); + assertEquals(ZONE1.getDescription(), created.getDescription()); + assertEquals(ZONE1.getDnsName(), created.getDnsName()); + assertEquals(ZONE1.getName(), created.getName()); + assertNotNull(created.getCreationTimeMillis()); + assertNotNull(created.getNameServers()); + assertNull(created.getNameServerSet()); + assertNotNull(created.getGeneratedId()); + Zone retrieved = DNS.getZone(ZONE1.getName()); 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.generatedId()); - retrieved = DNS.getZone(ZONE_EMPTY_DESCRIPTION.name()); + assertEquals(ZONE_EMPTY_DESCRIPTION.getDescription(), created.getDescription()); + assertEquals(ZONE_EMPTY_DESCRIPTION.getDnsName(), created.getDnsName()); + assertEquals(ZONE_EMPTY_DESCRIPTION.getName(), created.getName()); + assertNotNull(created.getCreationTimeMillis()); + assertNotNull(created.getNameServers()); + assertNull(created.getNameServerSet()); + assertNotNull(created.getGeneratedId()); + retrieved = DNS.getZone(ZONE_EMPTY_DESCRIPTION.getName()); assertEquals(created, retrieved); } finally { - DNS.delete(ZONE1.name()); - DNS.delete(ZONE_EMPTY_DESCRIPTION.name()); + DNS.delete(ZONE1.getName()); + DNS.delete(ZONE_EMPTY_DESCRIPTION.getName()); } } @@ -218,8 +219,8 @@ public void testCreateZoneWithErrors() { assertFalse(ex.retryable()); } } finally { - DNS.delete(ZONE_NAME_ERROR.name()); - DNS.delete(ZONE_DNS_NO_PERIOD.name()); + DNS.delete(ZONE_NAME_ERROR.getName()); + DNS.delete(ZONE_DNS_NO_PERIOD.getName()); } } @@ -227,80 +228,80 @@ public void testCreateZoneWithErrors() { public void testCreateZoneWithOptions() { try { Zone created = DNS.create(ZONE1, Dns.ZoneOption.fields(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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNotNull(created.getCreationTimeMillis()); + assertNull(created.getDescription()); + assertNull(created.getDnsName()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertEquals(ZONE1.getDescription(), created.getDescription()); + assertNull(created.getDnsName()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertEquals(ZONE1.getDnsName(), created.getDnsName()); + assertNull(created.getDescription()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); // we did not set it + assertNull(created.getGeneratedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertFalse(created.getNameServers().isEmpty()); + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created.delete(); created = DNS.create(ZONE1, Dns.ZoneOption.fields(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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertNotNull(created.getNameServers()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNotNull(created.getGeneratedId()); created.delete(); // combination of multiple things created = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.ZONE_ID, ZoneField.NAME_SERVERS, ZoneField.NAME_SERVER_SET, 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertEquals(ZONE1.getDescription(), created.getDescription()); + assertFalse(created.getNameServers().isEmpty()); + assertNull(created.getNameServerSet()); // we did not set it + assertNotNull(created.getGeneratedId()); } finally { - DNS.delete(ZONE1.name()); + DNS.delete(ZONE1.getName()); } } @@ -308,74 +309,74 @@ public void testCreateZoneWithOptions() { public void testGetZone() { try { DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); - Zone created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(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.generatedId()); - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(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.generatedId()); - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(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.generatedId()); - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(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.generatedId()); - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(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.generatedId()); - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(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.generatedId()); - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(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.generatedId()); + Zone created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.CREATION_TIME)); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNotNull(created.getCreationTimeMillis()); + assertNull(created.getDescription()); + assertNull(created.getDnsName()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); + created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.DESCRIPTION)); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertEquals(ZONE1.getDescription(), created.getDescription()); + assertNull(created.getDnsName()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); + created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.DNS_NAME)); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertEquals(ZONE1.getDnsName(), created.getDnsName()); + assertNull(created.getDescription()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); + created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME)); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); + created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME_SERVER_SET)); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); // we did not set it + assertNull(created.getGeneratedId()); + created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME_SERVERS)); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertFalse(created.getNameServers().isEmpty()); + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); + created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.ZONE_ID)); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertNotNull(created.getNameServers()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNotNull(created.getGeneratedId()); // combination of multiple things - created = DNS.getZone(ZONE1.name(), Dns.ZoneOption.fields(ZoneField.ZONE_ID, + created = DNS.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.ZONE_ID, ZoneField.NAME_SERVERS, ZoneField.NAME_SERVER_SET, 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertEquals(ZONE1.getDescription(), created.getDescription()); + assertFalse(created.getNameServers().isEmpty()); + assertNull(created.getNameServerSet()); // we did not set it + assertNotNull(created.getGeneratedId()); } finally { - DNS.delete(ZONE1.name()); + DNS.delete(ZONE1.getName()); } } @@ -423,74 +424,74 @@ public void testListZones() { assertFalse(ex.retryable()); } // ok name - zones = filter(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName())).iterateAll()); + zones = filter(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName())).iterateAll()); assertEquals(1, zones.size()); // field options - Iterator zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + Iterator zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(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(zone.generatedId()); + assertNull(zone.getCreationTimeMillis()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServerSet()); + assertTrue(zone.getNameServers().isEmpty()); + assertNotNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); - zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(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.generatedId()); + assertNotNull(zone.getCreationTimeMillis()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServerSet()); + assertTrue(zone.getNameServers().isEmpty()); + assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); - zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(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.generatedId()); + assertNull(zone.getCreationTimeMillis()); + assertNotNull(zone.getName()); + assertNotNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServerSet()); + assertTrue(zone.getNameServers().isEmpty()); + assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); - zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(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.generatedId()); + assertNull(zone.getCreationTimeMillis()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNotNull(zone.getDescription()); + assertNull(zone.getNameServerSet()); + assertTrue(zone.getNameServers().isEmpty()); + assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); - zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.NAME_SERVERS)).iterateAll(); zone = zoneIterator.next(); - assertNull(zone.creationTimeMillis()); - assertNotNull(zone.name()); - assertNull(zone.dnsName()); - assertNull(zone.description()); - assertNull(zone.nameServerSet()); - assertFalse(zone.nameServers().isEmpty()); - assertNull(zone.generatedId()); + assertNull(zone.getCreationTimeMillis()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServerSet()); + assertFalse(zone.getNameServers().isEmpty()); + assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); - zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + zoneIterator = DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(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 google-cloud - assertTrue(zone.nameServers().isEmpty()); - assertNull(zone.generatedId()); + assertNull(zone.getCreationTimeMillis()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServerSet()); // we cannot set it using google-cloud + assertTrue(zone.getNameServers().isEmpty()); + assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); // several combined zones = filter(DNS.listZones(Dns.ZoneListOption.fields(ZoneField.ZONE_ID, @@ -498,17 +499,17 @@ public void testListZones() { 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.generatedId()); + assertNull(current.getCreationTimeMillis()); + assertNotNull(current.getName()); + assertNull(current.getDnsName()); + assertNotNull(current.getDescription()); + assertNull(current.getNameServerSet()); + assertTrue(zone.getNameServers().isEmpty()); + assertNotNull(current.getGeneratedId()); } } finally { - DNS.delete(ZONE1.name()); - DNS.delete(ZONE_EMPTY_DESCRIPTION.name()); + DNS.delete(ZONE1.getName()); + DNS.delete(ZONE_EMPTY_DESCRIPTION.getName()); } } @@ -516,11 +517,11 @@ public void testListZones() { public void testDeleteZone() { try { Zone created = DNS.create(ZONE1); - assertEquals(created, DNS.getZone(ZONE1.name())); - DNS.delete(ZONE1.name()); - assertNull(DNS.getZone(ZONE1.name())); + assertEquals(created, DNS.getZone(ZONE1.getName())); + DNS.delete(ZONE1.getName()); + assertNull(DNS.getZone(ZONE1.getName())); } finally { - DNS.delete(ZONE1.name()); + DNS.delete(ZONE1.getName()); } } @@ -528,64 +529,64 @@ public void testDeleteZone() { public void testCreateChange() { try { DNS.create(ZONE1, Dns.ZoneOption.fields(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()); - assertNotNull(created.generatedId()); + ChangeRequest created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); + assertEquals(CHANGE_ADD_ZONE1.getAdditions(), created.getAdditions()); + assertNotNull(created.getStartTimeMillis()); + assertTrue(created.getDeletions().isEmpty()); + assertNotNull(created.getGeneratedId()); assertTrue(ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE) .contains(created.status())); - assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.name(), "1")); + assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.getName(), "1")); waitForChangeToComplete(created); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); // with options - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ID)); - assertTrue(created.additions().isEmpty()); - assertNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertNotNull(created.generatedId()); + assertTrue(created.getAdditions().isEmpty()); + assertNull(created.getStartTimeMillis()); + assertTrue(created.getDeletions().isEmpty()); + assertNotNull(created.getGeneratedId()); assertNull(created.status()); waitForChangeToComplete(created); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS)); - assertTrue(created.additions().isEmpty()); - assertNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertNotNull(created.generatedId()); + assertTrue(created.getAdditions().isEmpty()); + assertNull(created.getStartTimeMillis()); + assertTrue(created.getDeletions().isEmpty()); + assertNotNull(created.getGeneratedId()); assertNotNull(created.status()); waitForChangeToComplete(created); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME)); - assertTrue(created.additions().isEmpty()); - assertNotNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertNotNull(created.generatedId()); + assertTrue(created.getAdditions().isEmpty()); + assertNotNull(created.getStartTimeMillis()); + assertTrue(created.getDeletions().isEmpty()); + assertNotNull(created.getGeneratedId()); assertNull(created.status()); waitForChangeToComplete(created); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS)); - assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); - assertNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertNotNull(created.generatedId()); + assertEquals(CHANGE_ADD_ZONE1.getAdditions(), created.getAdditions()); + assertNull(created.getStartTimeMillis()); + assertTrue(created.getDeletions().isEmpty()); + assertNotNull(created.getGeneratedId()); assertNull(created.status()); // finishes with delete otherwise we cannot delete the zone waitForChangeToComplete(created); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1, + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS)); waitForChangeToComplete(created); - assertEquals(CHANGE_DELETE_ZONE1.deletions(), created.deletions()); - assertNull(created.startTimeMillis()); - assertTrue(created.additions().isEmpty()); - assertNotNull(created.generatedId()); + assertEquals(CHANGE_DELETE_ZONE1.getDeletions(), created.getDeletions()); + assertNull(created.getStartTimeMillis()); + assertTrue(created.getAdditions().isEmpty()); + assertNotNull(created.getGeneratedId()); assertNull(created.status()); waitForChangeToComplete(created); } finally { @@ -597,12 +598,12 @@ public void testCreateChange() { public void testInvalidChangeRequest() { Zone zone = DNS.create(ZONE1); RecordSet validA = - RecordSet.builder("subdomain." + zone.dnsName(), RecordSet.Type.A) - .records(ImmutableList.of("0.255.1.5")) + RecordSet.newBuilder("subdomain." + zone.getDnsName(), RecordSet.Type.A) + .setRecords(ImmutableList.of("0.255.1.5")) .build(); boolean recordAdded = false; try { - ChangeRequestInfo validChange = ChangeRequest.builder().add(validA).build(); + ChangeRequestInfo validChange = ChangeRequest.newBuilder().add(validA).build(); zone.applyChangeRequest(validChange); recordAdded = true; try { @@ -614,8 +615,8 @@ public void testInvalidChangeRequest() { assertEquals(409, ex.code()); } // delete with field mismatch - RecordSet mismatch = validA.toBuilder().ttl(20, TimeUnit.SECONDS).build(); - ChangeRequestInfo deletion = ChangeRequest.builder().delete(mismatch).build(); + RecordSet mismatch = validA.toBuilder().setTtl(20, TimeUnit.SECONDS).build(); + ChangeRequestInfo deletion = ChangeRequest.newBuilder().delete(mismatch).build(); try { zone.applyChangeRequest(deletion); fail("Deleted a record set without a complete match."); @@ -630,16 +631,16 @@ public void testInvalidChangeRequest() { LinkedList additions = new LinkedList<>(); while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); - if (recordSet.type() == RecordSet.Type.SOA) { + if (recordSet.getType() == RecordSet.Type.SOA) { deletions.add(recordSet); // the subdomain is necessary to get 400 instead of 412 - RecordSet copy = recordSet.toBuilder().name("x." + recordSet.name()).build(); + RecordSet copy = recordSet.toBuilder().setName("x." + recordSet.getName()).build(); additions.add(copy); break; } } - deletion = deletion.toBuilder().deletions(deletions).build(); - ChangeRequestInfo addition = ChangeRequest.builder().additions(additions).build(); + deletion = deletion.toBuilder().setDeletions(deletions).build(); + ChangeRequestInfo addition = ChangeRequest.newBuilder().setAdditions(additions).build(); try { zone.applyChangeRequest(deletion); fail("Deleted SOA."); @@ -658,9 +659,9 @@ public void testInvalidChangeRequest() { } } finally { if (recordAdded) { - ChangeRequestInfo deletion = ChangeRequest.builder().delete(validA).build(); + ChangeRequestInfo deletion = ChangeRequest.newBuilder().delete(validA).build(); ChangeRequest request = zone.applyChangeRequest(deletion); - waitForChangeToComplete(zone.name(), request.generatedId()); + waitForChangeToComplete(zone.getName(), request.getGeneratedId()); } zone.delete(); } @@ -671,7 +672,7 @@ public void testListChanges() { try { // no such zone exists try { - DNS.listChangeRequests(ZONE1.name()); + DNS.listChangeRequests(ZONE1.getName()); fail(); } catch (DnsException ex) { // expected @@ -681,22 +682,22 @@ public void testListChanges() { // zone exists but has no changes DNS.create(ZONE1); ImmutableList changes = ImmutableList.copyOf( - DNS.listChangeRequests(ZONE1.name()).iterateAll()); + DNS.listChangeRequests(ZONE1.getName()).iterateAll()); assertEquals(1, changes.size()); // default change creating SOA and NS // zone has changes - ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - waitForChangeToComplete(ZONE1.name(), change.generatedId()); - change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitForChangeToComplete(ZONE1.name(), change.generatedId()); - change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - waitForChangeToComplete(ZONE1.name(), change.generatedId()); - change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitForChangeToComplete(ZONE1.name(), change.generatedId()); - changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name()).iterateAll()); + ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); + waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); + change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); + waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); + change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); + waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); + change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); + waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.getName()).iterateAll()); assertEquals(5, changes.size()); // error in options try { - DNS.listChangeRequests(ZONE1.name(), Dns.ChangeRequestListOption.pageSize(0)); + DNS.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(0)); fail(); } catch (DnsException ex) { // expected @@ -704,7 +705,7 @@ public void testListChanges() { assertFalse(ex.retryable()); } try { - DNS.listChangeRequests(ZONE1.name(), Dns.ChangeRequestListOption.pageSize(-1)); + DNS.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(-1)); fail(); } catch (DnsException ex) { // expected @@ -713,10 +714,10 @@ public void testListChanges() { } // sorting order ImmutableList ascending = ImmutableList.copyOf(DNS.listChangeRequests( - ZONE1.name(), + ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)).iterateAll()); ImmutableList descending = ImmutableList.copyOf(DNS.listChangeRequests( - ZONE1.name(), + ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.DESCENDING)).iterateAll()); int size = 5; assertEquals(size, descending.size()); @@ -725,50 +726,50 @@ public void testListChanges() { assertEquals(descending.get(i), ascending.get(size - i - 1)); } // field options - changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.ADDITIONS)).iterateAll()); change = changes.get(1); - assertEquals(CHANGE_ADD_ZONE1.additions(), change.additions()); - assertTrue(change.deletions().isEmpty()); - assertNotNull(change.generatedId()); - assertNull(change.startTimeMillis()); + assertEquals(CHANGE_ADD_ZONE1.getAdditions(), change.getAdditions()); + assertTrue(change.getDeletions().isEmpty()); + assertNotNull(change.getGeneratedId()); + assertNull(change.getStartTimeMillis()); assertNull(change.status()); - changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.DELETIONS)).iterateAll()); change = changes.get(2); - assertTrue(change.additions().isEmpty()); - assertNotNull(change.deletions()); - assertNotNull(change.generatedId()); - assertNull(change.startTimeMillis()); + assertTrue(change.getAdditions().isEmpty()); + assertNotNull(change.getDeletions()); + assertNotNull(change.getGeneratedId()); + assertNull(change.getStartTimeMillis()); assertNull(change.status()); - changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.ID)).iterateAll()); change = changes.get(1); - assertTrue(change.additions().isEmpty()); - assertTrue(change.deletions().isEmpty()); - assertNotNull(change.generatedId()); - assertNull(change.startTimeMillis()); + assertTrue(change.getAdditions().isEmpty()); + assertTrue(change.getDeletions().isEmpty()); + assertNotNull(change.getGeneratedId()); + assertNull(change.getStartTimeMillis()); assertNull(change.status()); - changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.START_TIME)).iterateAll()); change = changes.get(1); - assertTrue(change.additions().isEmpty()); - assertTrue(change.deletions().isEmpty()); - assertNotNull(change.generatedId()); - assertNotNull(change.startTimeMillis()); + assertTrue(change.getAdditions().isEmpty()); + assertTrue(change.getDeletions().isEmpty()); + assertNotNull(change.getGeneratedId()); + assertNotNull(change.getStartTimeMillis()); assertNull(change.status()); - changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.name(), + changes = ImmutableList.copyOf(DNS.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.STATUS)).iterateAll()); change = changes.get(1); - assertTrue(change.additions().isEmpty()); - assertTrue(change.deletions().isEmpty()); - assertNotNull(change.generatedId()); - assertNull(change.startTimeMillis()); + assertTrue(change.getAdditions().isEmpty()); + assertTrue(change.getDeletions().isEmpty()); + assertNotNull(change.getGeneratedId()); + assertNull(change.getStartTimeMillis()); assertEquals(ChangeRequest.Status.DONE, change.status()); } finally { clear(); @@ -780,45 +781,45 @@ public void testGetChange() { try { Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); - ChangeRequest retrieved = DNS.getChangeRequest(zone.name(), created.generatedId()); + ChangeRequest retrieved = DNS.getChangeRequest(zone.getName(), created.getGeneratedId()); assertEqChangesIgnoreStatus(created, retrieved); - waitForChangeToComplete(zone.name(), created.generatedId()); + waitForChangeToComplete(zone.getName(), created.getGeneratedId()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); // with options created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ID)); - retrieved = DNS.getChangeRequest(zone.name(), created.generatedId(), + retrieved = DNS.getChangeRequest(zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.ID)); assertEqChangesIgnoreStatus(created, retrieved); - waitForChangeToComplete(zone.name(), created.generatedId()); + waitForChangeToComplete(zone.getName(), created.getGeneratedId()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS)); - retrieved = DNS.getChangeRequest(zone.name(), created.generatedId(), + retrieved = DNS.getChangeRequest(zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS)); assertEqChangesIgnoreStatus(created, retrieved); - waitForChangeToComplete(zone.name(), created.generatedId()); + waitForChangeToComplete(zone.getName(), created.getGeneratedId()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME)); - retrieved = DNS.getChangeRequest(zone.name(), created.generatedId(), + retrieved = DNS.getChangeRequest(zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME)); assertEqChangesIgnoreStatus(created, retrieved); - waitForChangeToComplete(zone.name(), created.generatedId()); + waitForChangeToComplete(zone.getName(), created.getGeneratedId()); zone.applyChangeRequest(CHANGE_DELETE_ZONE1); created = zone.applyChangeRequest(CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS)); - retrieved = DNS.getChangeRequest(zone.name(), created.generatedId(), + retrieved = DNS.getChangeRequest(zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS)); assertEqChangesIgnoreStatus(created, retrieved); - waitForChangeToComplete(zone.name(), created.generatedId()); + waitForChangeToComplete(zone.getName(), created.getGeneratedId()); // finishes with delete otherwise we cannot delete the zone created = zone.applyChangeRequest(CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS)); - retrieved = DNS.getChangeRequest(zone.name(), created.generatedId(), + retrieved = DNS.getChangeRequest(zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS)); assertEqChangesIgnoreStatus(created, retrieved); - waitForChangeToComplete(zone.name(), created.generatedId()); + waitForChangeToComplete(zone.getName(), created.getGeneratedId()); } finally { clear(); } @@ -828,17 +829,17 @@ public void testGetChange() { public void testGetProject() { // fetches all fields ProjectInfo project = DNS.getProject(); - assertNotNull(project.quota()); + assertNotNull(project.getQuota()); // options project = DNS.getProject(Dns.ProjectOption.fields(ProjectField.QUOTA)); - assertNotNull(project.quota()); + assertNotNull(project.getQuota()); project = DNS.getProject(Dns.ProjectOption.fields(ProjectField.PROJECT_ID)); - assertNull(project.quota()); + assertNull(project.getQuota()); project = DNS.getProject(Dns.ProjectOption.fields(ProjectField.PROJECT_NUMBER)); - assertNull(project.quota()); + assertNull(project.getQuota()); project = DNS.getProject(Dns.ProjectOption.fields(ProjectField.PROJECT_NUMBER, ProjectField.QUOTA, ProjectField.PROJECT_ID)); - assertNotNull(project.quota()); + assertNotNull(project.getQuota()); } @Test @@ -846,87 +847,87 @@ public void testListDnsRecords() { try { Zone zone = DNS.create(ZONE1); ImmutableList recordSets = ImmutableList.copyOf( - DNS.listRecordSets(zone.name()).iterateAll()); + DNS.listRecordSets(zone.getName()).iterateAll()); assertEquals(2, recordSets.size()); ImmutableList defaultRecords = ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA); for (RecordSet recordSet : recordSets) { - assertTrue(defaultRecords.contains(recordSet.type())); + assertTrue(defaultRecords.contains(recordSet.getType())); } // field options - Iterator recordSetIterator = DNS.listRecordSets(zone.name(), + Iterator recordSetIterator = DNS.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.TTL)).iterateAll(); int counter = 0; 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()); + assertEquals(recordSets.get(counter).getTtl(), recordSet.getTtl()); + assertEquals(recordSets.get(counter).getName(), recordSet.getName()); + assertEquals(recordSets.get(counter).getType(), recordSet.getType()); + assertTrue(recordSet.getRecords().isEmpty()); counter++; } assertEquals(2, counter); - recordSetIterator = DNS.listRecordSets(zone.name(), + recordSetIterator = DNS.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.NAME)).iterateAll(); counter = 0; 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()); + assertEquals(recordSets.get(counter).getName(), recordSet.getName()); + assertEquals(recordSets.get(counter).getType(), recordSet.getType()); + assertTrue(recordSet.getRecords().isEmpty()); + assertNull(recordSet.getTtl()); counter++; } assertEquals(2, counter); - recordSetIterator = DNS.listRecordSets(zone.name(), + recordSetIterator = DNS.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.DNS_RECORDS)) .iterateAll(); counter = 0; 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()); + assertEquals(recordSets.get(counter).getRecords(), recordSet.getRecords()); + assertEquals(recordSets.get(counter).getName(), recordSet.getName()); + assertEquals(recordSets.get(counter).getType(), recordSet.getType()); + assertNull(recordSet.getTtl()); counter++; } assertEquals(2, counter); - recordSetIterator = DNS.listRecordSets(zone.name(), + recordSetIterator = DNS.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.TYPE), Dns.RecordSetListOption.pageSize(1)).iterateAll(); // also test paging counter = 0; 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()); + assertEquals(recordSets.get(counter).getType(), recordSet.getType()); + assertEquals(recordSets.get(counter).getName(), recordSet.getName()); + assertTrue(recordSet.getRecords().isEmpty()); + assertNull(recordSet.getTtl()); counter++; } assertEquals(2, counter); // test page size - Page recordSetPage = DNS.listRecordSets(zone.name(), + Page recordSetPage = DNS.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(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.generatedId()); - recordSetIterator = DNS.listRecordSets(ZONE1.name(), - Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.name())).iterateAll(); + ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); + waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); + recordSetIterator = DNS.listRecordSets(ZONE1.getName(), + Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.getName())).iterateAll(); counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); - assertTrue(ImmutableList.of(A_RECORD_ZONE1.type(), AAAA_RECORD_ZONE1.type()) - .contains(recordSet.type())); + assertTrue(ImmutableList.of(A_RECORD_ZONE1.getType(), AAAA_RECORD_ZONE1.getType()) + .contains(recordSet.getType())); counter++; } assertEquals(2, counter); // test type filter - waitForChangeToComplete(ZONE1.name(), change.generatedId()); - recordSetIterator = DNS.listRecordSets(ZONE1.name(), - Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.name()), - Dns.RecordSetListOption.type(A_RECORD_ZONE1.type())).iterateAll(); + waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); + recordSetIterator = DNS.listRecordSets(ZONE1.getName(), + Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.getName()), + Dns.RecordSetListOption.type(A_RECORD_ZONE1.getType())).iterateAll(); counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); @@ -938,8 +939,8 @@ public void testListDnsRecords() { // check wrong arguments try { // name is not set - DNS.listRecordSets(ZONE1.name(), - Dns.RecordSetListOption.type(A_RECORD_ZONE1.type())); + DNS.listRecordSets(ZONE1.getName(), + Dns.RecordSetListOption.type(A_RECORD_ZONE1.getType())); fail(); } catch (DnsException ex) { // expected @@ -947,7 +948,7 @@ public void testListDnsRecords() { assertFalse(ex.retryable()); } try { - DNS.listRecordSets(ZONE1.name(), Dns.RecordSetListOption.pageSize(0)); + DNS.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(0)); fail(); } catch (DnsException ex) { // expected @@ -955,14 +956,14 @@ public void testListDnsRecords() { assertFalse(ex.retryable()); } try { - DNS.listRecordSets(ZONE1.name(), Dns.RecordSetListOption.pageSize(-1)); + DNS.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(-1)); fail(); } catch (DnsException ex) { // expected assertEquals(400, ex.code()); assertFalse(ex.retryable()); } - waitForChangeToComplete(ZONE1.name(), change.generatedId()); + waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); } finally { clear(); } @@ -994,24 +995,24 @@ public void testListZonesBatch() { DnsBatchResult> okSize = batch.listZones(Dns.ZoneListOption.pageSize(1)); DnsBatchResult> nameError = batch.listZones(Dns.ZoneListOption.dnsName("aaaaa")); DnsBatchResult> okName = - batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName())); + batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName())); DnsBatchResult> idResult = - batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.ZONE_ID)); DnsBatchResult> timeResult = - batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.CREATION_TIME)); DnsBatchResult> dnsNameResult = - batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.DNS_NAME)); DnsBatchResult> descriptionResult = - batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.DESCRIPTION)); DnsBatchResult> nameServersResult = - batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.NAME_SERVERS)); DnsBatchResult> nameServerSetResult = - batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.dnsName()), + batch.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName()), Dns.ZoneListOption.fields(ZoneField.NAME_SERVER_SET)); DnsBatchResult> combinationResult = batch.listZones(Dns.ZoneListOption.fields(ZoneField.ZONE_ID, ZoneField.DESCRIPTION), @@ -1055,79 +1056,79 @@ public void testListZonesBatch() { // field options Iterator zoneIterator = idResult.get().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(zone.generatedId()); + assertNull(zone.getCreationTimeMillis()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServerSet()); + assertTrue(zone.getNameServers().isEmpty()); + assertNotNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = timeResult.get().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.generatedId()); + assertNotNull(zone.getCreationTimeMillis()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServerSet()); + assertTrue(zone.getNameServers().isEmpty()); + assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = dnsNameResult.get().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.generatedId()); + assertNull(zone.getCreationTimeMillis()); + assertNotNull(zone.getName()); + assertNotNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServerSet()); + assertTrue(zone.getNameServers().isEmpty()); + assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = descriptionResult.get().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.generatedId()); + assertNull(zone.getCreationTimeMillis()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNotNull(zone.getDescription()); + assertNull(zone.getNameServerSet()); + assertTrue(zone.getNameServers().isEmpty()); + assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = nameServersResult.get().iterateAll(); zone = zoneIterator.next(); - assertNull(zone.creationTimeMillis()); - assertNotNull(zone.name()); - assertNull(zone.dnsName()); - assertNull(zone.description()); - assertNull(zone.nameServerSet()); - assertFalse(zone.nameServers().isEmpty()); - assertNull(zone.generatedId()); + assertNull(zone.getCreationTimeMillis()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServerSet()); + assertFalse(zone.getNameServers().isEmpty()); + assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); zoneIterator = nameServerSetResult.get().iterateAll(); zone = zoneIterator.next(); - assertNull(zone.creationTimeMillis()); - assertNotNull(zone.name()); - assertNull(zone.dnsName()); - assertNull(zone.description()); - assertNull(zone.nameServerSet()); // we cannot set it using google-cloud - assertTrue(zone.nameServers().isEmpty()); - assertNull(zone.generatedId()); + assertNull(zone.getCreationTimeMillis()); + assertNotNull(zone.getName()); + assertNull(zone.getDnsName()); + assertNull(zone.getDescription()); + assertNull(zone.getNameServerSet()); // we cannot set it using google-cloud + assertTrue(zone.getNameServers().isEmpty()); + assertNull(zone.getGeneratedId()); assertFalse(zoneIterator.hasNext()); // several combined zones = filter(combinationResult.get().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.generatedId()); + assertNull(current.getCreationTimeMillis()); + assertNotNull(current.getName()); + assertNull(current.getDnsName()); + assertNotNull(current.getDescription()); + assertNull(current.getNameServerSet()); + assertTrue(zone.getNameServers().isEmpty()); + assertNotNull(current.getGeneratedId()); } } finally { - DNS.delete(ZONE1.name()); - DNS.delete(ZONE_EMPTY_DESCRIPTION.name()); + DNS.delete(ZONE1.getName()); + DNS.delete(ZONE_EMPTY_DESCRIPTION.getName()); } } @@ -1139,28 +1140,28 @@ public void testCreateValidZoneBatch() { DnsBatchResult partialZoneResult = batch.createZone(ZONE_EMPTY_DESCRIPTION); batch.submit(); Zone created = completeZoneResult.get(); - 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.generatedId()); - Zone retrieved = DNS.getZone(ZONE1.name()); + assertEquals(ZONE1.getDescription(), created.getDescription()); + assertEquals(ZONE1.getDnsName(), created.getDnsName()); + assertEquals(ZONE1.getName(), created.getName()); + assertNotNull(created.getCreationTimeMillis()); + assertNotNull(created.getNameServers()); + assertNull(created.getNameServerSet()); + assertNotNull(created.getGeneratedId()); + Zone retrieved = DNS.getZone(ZONE1.getName()); assertEquals(created, retrieved); created = partialZoneResult.get(); - 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.generatedId()); - retrieved = DNS.getZone(ZONE_EMPTY_DESCRIPTION.name()); + assertEquals(ZONE_EMPTY_DESCRIPTION.getDescription(), created.getDescription()); + assertEquals(ZONE_EMPTY_DESCRIPTION.getDnsName(), created.getDnsName()); + assertEquals(ZONE_EMPTY_DESCRIPTION.getName(), created.getName()); + assertNotNull(created.getCreationTimeMillis()); + assertNotNull(created.getNameServers()); + assertNull(created.getNameServerSet()); + assertNotNull(created.getGeneratedId()); + retrieved = DNS.getZone(ZONE_EMPTY_DESCRIPTION.getName()); assertEquals(created, retrieved); } finally { - DNS.delete(ZONE1.name()); - DNS.delete(ZONE_EMPTY_DESCRIPTION.name()); + DNS.delete(ZONE1.getName()); + DNS.delete(ZONE_EMPTY_DESCRIPTION.getName()); } } @@ -1186,8 +1187,8 @@ public void testCreateZoneWithErrorsBatch() { assertFalse(ex.retryable()); } } finally { - DNS.delete(ZONE_NAME_ERROR.name()); - DNS.delete(ZONE_DNS_NO_PERIOD.name()); + DNS.delete(ZONE_NAME_ERROR.getName()); + DNS.delete(ZONE_DNS_NO_PERIOD.getName()); } } @@ -1199,85 +1200,85 @@ public void testCreateZoneWithOptionsBatch() { batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.CREATION_TIME)); batch.submit(); Zone created = batchResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNotNull(created.getCreationTimeMillis()); + assertNull(created.getDescription()); + assertNull(created.getDnsName()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.DESCRIPTION)); batch.submit(); created = batchResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertEquals(ZONE1.getDescription(), created.getDescription()); + assertNull(created.getDnsName()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.DNS_NAME)); batch.submit(); created = batchResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertEquals(ZONE1.getDnsName(), created.getDnsName()); + assertNull(created.getDescription()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); batch.submit(); created = batchResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME_SERVER_SET)); batch.submit(); created = batchResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); // we did not set it + assertNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME_SERVERS)); batch.submit(); created = batchResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertFalse(created.getNameServers().isEmpty()); + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.ZONE_ID)); batch.submit(); created = batchResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertNotNull(created.getNameServers()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNotNull(created.getGeneratedId()); created.delete(); batch = DNS.batch(); batchResult = batch.createZone(ZONE1, Dns.ZoneOption.fields(ZoneField.ZONE_ID, @@ -1285,15 +1286,15 @@ public void testCreateZoneWithOptionsBatch() { batch.submit(); // combination of multiple things created = batchResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertEquals(ZONE1.getDescription(), created.getDescription()); + assertFalse(created.getNameServers().isEmpty()); + assertNull(created.getNameServerSet()); // we did not set it + assertNotNull(created.getGeneratedId()); } finally { - DNS.delete(ZONE1.name()); + DNS.delete(ZONE1.getName()); } } @@ -1303,90 +1304,90 @@ public void testGetZoneBatch() { DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); DnsBatch batch = DNS.batch(); DnsBatchResult timeResult = - batch.getZone(ZONE1.name(), Dns.ZoneOption.fields(ZoneField.CREATION_TIME)); + batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.CREATION_TIME)); DnsBatchResult descriptionResult = - batch.getZone(ZONE1.name(), Dns.ZoneOption.fields(ZoneField.DESCRIPTION)); + batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.DESCRIPTION)); DnsBatchResult dnsNameResult = - batch.getZone(ZONE1.name(), Dns.ZoneOption.fields(ZoneField.DNS_NAME)); + batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.DNS_NAME)); DnsBatchResult nameResult = - batch.getZone(ZONE1.name(), Dns.ZoneOption.fields(ZoneField.NAME)); + batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME)); DnsBatchResult nameServerSetResult = - batch.getZone(ZONE1.name(), Dns.ZoneOption.fields(ZoneField.NAME_SERVER_SET)); + batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME_SERVER_SET)); DnsBatchResult nameServersResult = - batch.getZone(ZONE1.name(), Dns.ZoneOption.fields(ZoneField.NAME_SERVERS)); + batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.NAME_SERVERS)); DnsBatchResult idResult = - batch.getZone(ZONE1.name(), Dns.ZoneOption.fields(ZoneField.ZONE_ID)); - DnsBatchResult combinationResult = batch.getZone(ZONE1.name(), + batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.ZONE_ID)); + DnsBatchResult combinationResult = batch.getZone(ZONE1.getName(), Dns.ZoneOption.fields(ZoneField.ZONE_ID, ZoneField.NAME_SERVERS, ZoneField.NAME_SERVER_SET, ZoneField.DESCRIPTION)); batch.submit(); Zone created = timeResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNotNull(created.getCreationTimeMillis()); + assertNull(created.getDescription()); + assertNull(created.getDnsName()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created = descriptionResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertEquals(ZONE1.getDescription(), created.getDescription()); + assertNull(created.getDnsName()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created = dnsNameResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertEquals(ZONE1.getDnsName(), created.getDnsName()); + assertNull(created.getDescription()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created = nameResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created = nameServerSetResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNull(created.getNameServerSet()); // we did not set it + assertNull(created.getGeneratedId()); created = nameServersResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertFalse(created.getNameServers().isEmpty()); + assertNull(created.getNameServerSet()); + assertNull(created.getGeneratedId()); created = idResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertNull(created.getDescription()); + assertNotNull(created.getNameServers()); + assertTrue(created.getNameServers().isEmpty()); // never returns null + assertNotNull(created.getGeneratedId()); // combination of multiple things created = combinationResult.get(); - 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.generatedId()); + assertEquals(ZONE1.getName(), created.getName()); // always returned + assertNull(created.getCreationTimeMillis()); + assertNull(created.getDnsName()); + assertEquals(ZONE1.getDescription(), created.getDescription()); + assertFalse(created.getNameServers().isEmpty()); + assertNull(created.getNameServerSet()); // we did not set it + assertNotNull(created.getGeneratedId()); } finally { - DNS.delete(ZONE1.name()); + DNS.delete(ZONE1.getName()); } } @@ -1394,14 +1395,14 @@ public void testGetZoneBatch() { public void testDeleteZoneBatch() { try { Zone created = DNS.create(ZONE1); - assertEquals(created, DNS.getZone(ZONE1.name())); + assertEquals(created, DNS.getZone(ZONE1.getName())); DnsBatch batch = DNS.batch(); - DnsBatchResult result = batch.deleteZone(ZONE1.name()); + DnsBatchResult result = batch.deleteZone(ZONE1.getName()); batch.submit(); - assertNull(DNS.getZone(ZONE1.name())); + assertNull(DNS.getZone(ZONE1.getName())); assertTrue(result.get()); } finally { - DNS.delete(ZONE1.name()); + DNS.delete(ZONE1.getName()); } } @@ -1420,11 +1421,11 @@ public void testGetProjectBatch() { batch.getProject(Dns.ProjectOption.fields(ProjectField.PROJECT_NUMBER, ProjectField.QUOTA, ProjectField.PROJECT_ID)); batch.submit(); - assertNotNull(result.get().quota()); - assertNotNull(resultQuota.get().quota()); - assertNull(resultId.get().quota()); - assertNull(resultNumber.get().quota()); - assertNotNull(resultCombination.get().quota()); + assertNotNull(result.get().getQuota()); + assertNotNull(resultQuota.get().getQuota()); + assertNull(resultId.get().getQuota()); + assertNull(resultNumber.get().getQuota()); + assertNotNull(resultCombination.get().getQuota()); } @Test @@ -1433,81 +1434,81 @@ public void testCreateChangeBatch() { DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); DnsBatch batch = DNS.batch(); DnsBatchResult result = - batch.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); + batch.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); batch.submit(); ChangeRequest created = result.get(); - assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); - assertNotNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertNotNull(created.generatedId()); + assertEquals(CHANGE_ADD_ZONE1.getAdditions(), created.getAdditions()); + assertNotNull(created.getStartTimeMillis()); + assertTrue(created.getDeletions().isEmpty()); + assertNotNull(created.getGeneratedId()); assertTrue(ImmutableList.of(ChangeRequest.Status.PENDING, ChangeRequest.Status.DONE) .contains(created.status())); - assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.name(), "1")); + assertEqChangesIgnoreStatus(created, DNS.getChangeRequest(ZONE1.getName(), "1")); waitForChangeToComplete(created); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); // with options batch = DNS.batch(); - result = batch.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + result = batch.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ID)); batch.submit(); created = result.get(); - assertTrue(created.additions().isEmpty()); - assertNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertNotNull(created.generatedId()); + assertTrue(created.getAdditions().isEmpty()); + assertNull(created.getStartTimeMillis()); + assertTrue(created.getDeletions().isEmpty()); + assertNotNull(created.getGeneratedId()); assertNull(created.status()); waitForChangeToComplete(created); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); batch = DNS.batch(); - result = batch.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + result = batch.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS)); batch.submit(); created = result.get(); - assertTrue(created.additions().isEmpty()); - assertNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertNotNull(created.generatedId()); + assertTrue(created.getAdditions().isEmpty()); + assertNull(created.getStartTimeMillis()); + assertTrue(created.getDeletions().isEmpty()); + assertNotNull(created.getGeneratedId()); assertNotNull(created.status()); waitForChangeToComplete(created); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); batch = DNS.batch(); - result = batch.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + result = batch.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME)); batch.submit(); created = result.get(); - assertTrue(created.additions().isEmpty()); - assertNotNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertNotNull(created.generatedId()); + assertTrue(created.getAdditions().isEmpty()); + assertNotNull(created.getStartTimeMillis()); + assertTrue(created.getDeletions().isEmpty()); + assertNotNull(created.getGeneratedId()); assertNull(created.status()); waitForChangeToComplete(created); - created = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); + created = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); waitForChangeToComplete(created); batch = DNS.batch(); - result = batch.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1, + result = batch.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS)); batch.submit(); created = result.get(); - assertEquals(CHANGE_ADD_ZONE1.additions(), created.additions()); - assertNull(created.startTimeMillis()); - assertTrue(created.deletions().isEmpty()); - assertNotNull(created.generatedId()); + assertEquals(CHANGE_ADD_ZONE1.getAdditions(), created.getAdditions()); + assertNull(created.getStartTimeMillis()); + assertTrue(created.getDeletions().isEmpty()); + assertNotNull(created.getGeneratedId()); assertNull(created.status()); // finishes with delete otherwise we cannot delete the zone waitForChangeToComplete(created); batch = DNS.batch(); - result = batch.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1, + result = batch.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS)); batch.submit(); created = result.get(); waitForChangeToComplete(created); - assertEquals(CHANGE_DELETE_ZONE1.deletions(), created.deletions()); - assertNull(created.startTimeMillis()); - assertTrue(created.additions().isEmpty()); - assertNotNull(created.generatedId()); + assertEquals(CHANGE_DELETE_ZONE1.getDeletions(), created.getDeletions()); + assertNull(created.getStartTimeMillis()); + assertTrue(created.getAdditions().isEmpty()); + assertNotNull(created.getGeneratedId()); assertNull(created.status()); waitForChangeToComplete(created); } finally { @@ -1520,68 +1521,68 @@ public void testGetChangeBatch() { try { Zone zone = DNS.create(ZONE1, Dns.ZoneOption.fields(ZoneField.NAME)); ChangeRequest created = zone.applyChangeRequest(CHANGE_ADD_ZONE1); - waitForChangeToComplete(zone.name(), created.generatedId()); + waitForChangeToComplete(zone.getName(), created.getGeneratedId()); DnsBatch batch = DNS.batch(); DnsBatchResult completeResult = - batch.getChangeRequest(zone.name(), created.generatedId()); + batch.getChangeRequest(zone.getName(), created.getGeneratedId()); DnsBatchResult idResult = - batch.getChangeRequest(zone.name(), created.generatedId(), + batch.getChangeRequest(zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.ID)); DnsBatchResult statusResult = - batch.getChangeRequest(zone.name(), created.generatedId(), + batch.getChangeRequest(zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.STATUS)); DnsBatchResult timeResult = - batch.getChangeRequest(zone.name(), created.generatedId(), + batch.getChangeRequest(zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.START_TIME)); DnsBatchResult additionsResult = - batch.getChangeRequest(zone.name(), created.generatedId(), + batch.getChangeRequest(zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.ADDITIONS)); batch.submit(); assertEqChangesIgnoreStatus(created, completeResult.get()); // with options ChangeRequest retrieved = idResult.get(); - assertEquals(created.generatedId(), retrieved.generatedId()); - assertEquals(0, retrieved.additions().size()); - assertEquals(0, retrieved.deletions().size()); - assertNull(retrieved.startTimeMillis()); + assertEquals(created.getGeneratedId(), retrieved.getGeneratedId()); + assertEquals(0, retrieved.getAdditions().size()); + assertEquals(0, retrieved.getDeletions().size()); + assertNull(retrieved.getStartTimeMillis()); assertNull(retrieved.status()); retrieved = statusResult.get(); - assertEquals(created.generatedId(), retrieved.generatedId()); - assertEquals(0, retrieved.additions().size()); - assertEquals(0, retrieved.deletions().size()); - assertNull(retrieved.startTimeMillis()); + assertEquals(created.getGeneratedId(), retrieved.getGeneratedId()); + assertEquals(0, retrieved.getAdditions().size()); + assertEquals(0, retrieved.getDeletions().size()); + assertNull(retrieved.getStartTimeMillis()); assertEquals(ChangeRequestInfo.Status.DONE, retrieved.status()); retrieved = timeResult.get(); - assertEquals(created.generatedId(), retrieved.generatedId()); - assertEquals(0, retrieved.additions().size()); - assertEquals(0, retrieved.deletions().size()); - assertEquals(created.startTimeMillis(), retrieved.startTimeMillis()); + assertEquals(created.getGeneratedId(), retrieved.getGeneratedId()); + assertEquals(0, retrieved.getAdditions().size()); + assertEquals(0, retrieved.getDeletions().size()); + assertEquals(created.getStartTimeMillis(), retrieved.getStartTimeMillis()); assertNull(retrieved.status()); retrieved = additionsResult.get(); - assertEquals(created.generatedId(), retrieved.generatedId()); - assertEquals(2, retrieved.additions().size()); - assertTrue(retrieved.additions().contains(A_RECORD_ZONE1)); - assertTrue(retrieved.additions().contains(AAAA_RECORD_ZONE1)); - assertEquals(0, retrieved.deletions().size()); - assertNull(retrieved.startTimeMillis()); + assertEquals(created.getGeneratedId(), retrieved.getGeneratedId()); + assertEquals(2, retrieved.getAdditions().size()); + assertTrue(retrieved.getAdditions().contains(A_RECORD_ZONE1)); + assertTrue(retrieved.getAdditions().contains(AAAA_RECORD_ZONE1)); + assertEquals(0, retrieved.getDeletions().size()); + assertNull(retrieved.getStartTimeMillis()); assertNull(retrieved.status()); // finishes with delete otherwise we cannot delete the zone created = zone.applyChangeRequest(CHANGE_DELETE_ZONE1, Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS)); batch = DNS.batch(); DnsBatchResult deletionsResult = - batch.getChangeRequest(zone.name(), created.generatedId(), + batch.getChangeRequest(zone.getName(), created.getGeneratedId(), Dns.ChangeRequestOption.fields(ChangeRequestField.DELETIONS)); batch.submit(); retrieved = deletionsResult.get(); - assertEquals(created.generatedId(), retrieved.generatedId()); - assertEquals(0, retrieved.additions().size()); - assertEquals(2, retrieved.deletions().size()); - assertTrue(retrieved.deletions().contains(AAAA_RECORD_ZONE1)); - assertTrue(retrieved.deletions().contains(A_RECORD_ZONE1)); - assertNull(retrieved.startTimeMillis()); + assertEquals(created.getGeneratedId(), retrieved.getGeneratedId()); + assertEquals(0, retrieved.getAdditions().size()); + assertEquals(2, retrieved.getDeletions().size()); + assertTrue(retrieved.getDeletions().contains(AAAA_RECORD_ZONE1)); + assertTrue(retrieved.getDeletions().contains(A_RECORD_ZONE1)); + assertNull(retrieved.getStartTimeMillis()); assertNull(retrieved.status()); - waitForChangeToComplete(zone.name(), created.generatedId()); + waitForChangeToComplete(zone.getName(), created.getGeneratedId()); } finally { clear(); } @@ -1591,7 +1592,7 @@ public void testGetChangeBatch() { public void testListChangesBatch() { try { DnsBatch batch = DNS.batch(); - DnsBatchResult> result = batch.listChangeRequests(ZONE1.name()); + DnsBatchResult> result = batch.listChangeRequests(ZONE1.getName()); batch.submit(); try { result.get(); @@ -1604,37 +1605,42 @@ public void testListChangesBatch() { // zone exists but has no changes DNS.create(ZONE1); batch = DNS.batch(); - result = batch.listChangeRequests(ZONE1.name()); + result = batch.listChangeRequests(ZONE1.getName()); batch.submit(); assertEquals(1, Iterables.size(result.get().values())); // default change creating SOA and NS // zone has changes - ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - waitForChangeToComplete(ZONE1.name(), change.generatedId()); - change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_DELETE_ZONE1); - waitForChangeToComplete(ZONE1.name(), change.generatedId()); + ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); + waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); + change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_DELETE_ZONE1); + waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); batch = DNS.batch(); - result = batch.listChangeRequests(ZONE1.name()); - DnsBatchResult> errorPageSize = batch.listChangeRequests(ZONE1.name(), + result = batch.listChangeRequests(ZONE1.getName()); + DnsBatchResult> errorPageSize = batch.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(0)); - DnsBatchResult> errorPageNegative = batch.listChangeRequests(ZONE1.name(), - Dns.ChangeRequestListOption.pageSize(-1)); - DnsBatchResult> resultAscending = batch.listChangeRequests(ZONE1.name(), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)); - DnsBatchResult> resultDescending = batch.listChangeRequests(ZONE1.name(), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.DESCENDING)); - DnsBatchResult> resultAdditions = batch.listChangeRequests(ZONE1.name(), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(ChangeRequestField.ADDITIONS)); - DnsBatchResult> resultDeletions = batch.listChangeRequests(ZONE1.name(), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(ChangeRequestField.DELETIONS)); - DnsBatchResult> resultId = batch.listChangeRequests(ZONE1.name(), - Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), - Dns.ChangeRequestListOption.fields(ChangeRequestField.ID)); - DnsBatchResult> resultTime = batch.listChangeRequests(ZONE1.name(), + DnsBatchResult> errorPageNegative = + batch.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(-1)); + DnsBatchResult> resultAscending = + batch.listChangeRequests(ZONE1.getName(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING)); + DnsBatchResult> resultDescending = + batch.listChangeRequests(ZONE1.getName(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.DESCENDING)); + DnsBatchResult> resultAdditions = + batch.listChangeRequests(ZONE1.getName(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(ChangeRequestField.ADDITIONS)); + DnsBatchResult> resultDeletions = + batch.listChangeRequests(ZONE1.getName(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(ChangeRequestField.DELETIONS)); + DnsBatchResult> resultId = + batch.listChangeRequests(ZONE1.getName(), + Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), + Dns.ChangeRequestListOption.fields(ChangeRequestField.ID)); + DnsBatchResult> resultTime = batch.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.START_TIME)); - DnsBatchResult> resultStatus = batch.listChangeRequests(ZONE1.name(), + DnsBatchResult> resultStatus = batch.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.STATUS)); batch.submit(); @@ -1669,34 +1675,34 @@ public void testListChangesBatch() { } // field options change = Iterables.get(resultAdditions.get().values(), 1); - assertEquals(CHANGE_ADD_ZONE1.additions(), change.additions()); - assertTrue(change.deletions().isEmpty()); - assertNotNull(change.generatedId()); - assertNull(change.startTimeMillis()); + assertEquals(CHANGE_ADD_ZONE1.getAdditions(), change.getAdditions()); + assertTrue(change.getDeletions().isEmpty()); + assertNotNull(change.getGeneratedId()); + assertNull(change.getStartTimeMillis()); assertNull(change.status()); change = Iterables.get(resultDeletions.get().values(), 2); - assertTrue(change.additions().isEmpty()); - assertNotNull(change.deletions()); - assertNotNull(change.generatedId()); - assertNull(change.startTimeMillis()); + assertTrue(change.getAdditions().isEmpty()); + assertNotNull(change.getDeletions()); + assertNotNull(change.getGeneratedId()); + assertNull(change.getStartTimeMillis()); assertNull(change.status()); change = Iterables.get(resultId.get().values(), 1); - assertTrue(change.additions().isEmpty()); - assertTrue(change.deletions().isEmpty()); - assertNotNull(change.generatedId()); - assertNull(change.startTimeMillis()); + assertTrue(change.getAdditions().isEmpty()); + assertTrue(change.getDeletions().isEmpty()); + assertNotNull(change.getGeneratedId()); + assertNull(change.getStartTimeMillis()); assertNull(change.status()); change = Iterables.get(resultTime.get().values(), 1); - assertTrue(change.additions().isEmpty()); - assertTrue(change.deletions().isEmpty()); - assertNotNull(change.generatedId()); - assertNotNull(change.startTimeMillis()); + assertTrue(change.getAdditions().isEmpty()); + assertTrue(change.getDeletions().isEmpty()); + assertNotNull(change.getGeneratedId()); + assertNotNull(change.getStartTimeMillis()); assertNull(change.status()); change = Iterables.get(resultStatus.get().values(), 1); - assertTrue(change.additions().isEmpty()); - assertTrue(change.deletions().isEmpty()); - assertNotNull(change.generatedId()); - assertNull(change.startTimeMillis()); + assertTrue(change.getAdditions().isEmpty()); + assertTrue(change.getDeletions().isEmpty()); + assertNotNull(change.getGeneratedId()); + assertNull(change.getStartTimeMillis()); assertEquals(ChangeRequest.Status.DONE, change.status()); } finally { clear(); @@ -1708,24 +1714,24 @@ public void testListDnsRecordSetsBatch() { try { Zone zone = DNS.create(ZONE1); DnsBatch batch = DNS.batch(); - DnsBatchResult> result = batch.listRecordSets(zone.name()); + DnsBatchResult> result = batch.listRecordSets(zone.getName()); batch.submit(); ImmutableList recordSets = ImmutableList.copyOf(result.get().iterateAll()); assertEquals(2, recordSets.size()); ImmutableList defaultRecords = ImmutableList.of(RecordSet.Type.NS, RecordSet.Type.SOA); for (RecordSet recordSet : recordSets) { - assertTrue(defaultRecords.contains(recordSet.type())); + assertTrue(defaultRecords.contains(recordSet.getType())); } // field options batch = DNS.batch(); - DnsBatchResult> ttlResult = batch.listRecordSets(zone.name(), + DnsBatchResult> ttlResult = batch.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.TTL)); - DnsBatchResult> nameResult = batch.listRecordSets(zone.name(), + DnsBatchResult> nameResult = batch.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.NAME)); - DnsBatchResult> recordsResult = batch.listRecordSets(zone.name(), + DnsBatchResult> recordsResult = batch.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.DNS_RECORDS)); - DnsBatchResult> pageSizeResult = batch.listRecordSets(zone.name(), + DnsBatchResult> pageSizeResult = batch.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.TYPE), Dns.RecordSetListOption.pageSize(1)); batch.submit(); @@ -1733,10 +1739,10 @@ public void testListDnsRecordSetsBatch() { int counter = 0; 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()); + assertEquals(recordSets.get(counter).getTtl(), recordSet.getTtl()); + assertEquals(recordSets.get(counter).getName(), recordSet.getName()); + assertEquals(recordSets.get(counter).getType(), recordSet.getType()); + assertTrue(recordSet.getRecords().isEmpty()); counter++; } assertEquals(2, counter); @@ -1744,10 +1750,10 @@ public void testListDnsRecordSetsBatch() { counter = 0; 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()); + assertEquals(recordSets.get(counter).getName(), recordSet.getName()); + assertEquals(recordSets.get(counter).getType(), recordSet.getType()); + assertTrue(recordSet.getRecords().isEmpty()); + assertNull(recordSet.getTtl()); counter++; } assertEquals(2, counter); @@ -1755,10 +1761,10 @@ public void testListDnsRecordSetsBatch() { counter = 0; 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()); + assertEquals(recordSets.get(counter).getRecords(), recordSet.getRecords()); + assertEquals(recordSets.get(counter).getName(), recordSet.getName()); + assertEquals(recordSets.get(counter).getType(), recordSet.getType()); + assertNull(recordSet.getTtl()); counter++; } assertEquals(2, counter); @@ -1766,10 +1772,10 @@ public void testListDnsRecordSetsBatch() { counter = 0; 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()); + assertEquals(recordSets.get(counter).getType(), recordSet.getType()); + assertEquals(recordSets.get(counter).getName(), recordSet.getName()); + assertTrue(recordSet.getRecords().isEmpty()); + assertNull(recordSet.getTtl()); counter++; } assertEquals(2, counter); @@ -1777,26 +1783,26 @@ public void testListDnsRecordSetsBatch() { Page recordSetPage = pageSizeResult.get(); assertEquals(1, ImmutableList.copyOf(recordSetPage.values().iterator()).size()); // test name filter - ChangeRequest change = DNS.applyChangeRequest(ZONE1.name(), CHANGE_ADD_ZONE1); - waitForChangeToComplete(ZONE1.name(), change.generatedId()); + ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); + waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); batch = DNS.batch(); - result = batch.listRecordSets(ZONE1.name(), - Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.name())); + result = batch.listRecordSets(ZONE1.getName(), + Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.getName())); batch.submit(); recordSetIterator = result.get().iterateAll(); counter = 0; while (recordSetIterator.hasNext()) { RecordSet recordSet = recordSetIterator.next(); - assertTrue(ImmutableList.of(A_RECORD_ZONE1.type(), AAAA_RECORD_ZONE1.type()) - .contains(recordSet.type())); + assertTrue(ImmutableList.of(A_RECORD_ZONE1.getType(), AAAA_RECORD_ZONE1.getType()) + .contains(recordSet.getType())); counter++; } assertEquals(2, counter); // test type filter batch = DNS.batch(); - result = batch.listRecordSets(ZONE1.name(), - Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.name()), - Dns.RecordSetListOption.type(A_RECORD_ZONE1.type())); + result = batch.listRecordSets(ZONE1.getName(), + Dns.RecordSetListOption.dnsName(A_RECORD_ZONE1.getName()), + Dns.RecordSetListOption.type(A_RECORD_ZONE1.getType())); batch.submit(); recordSetIterator = result.get().iterateAll(); counter = 0; @@ -1807,12 +1813,12 @@ public void testListDnsRecordSetsBatch() { } assertEquals(1, counter); batch = DNS.batch(); - DnsBatchResult> noNameError = batch.listRecordSets(ZONE1.name(), - Dns.RecordSetListOption.type(A_RECORD_ZONE1.type())); + DnsBatchResult> noNameError = batch.listRecordSets(ZONE1.getName(), + Dns.RecordSetListOption.type(A_RECORD_ZONE1.getType())); DnsBatchResult> zeroSizeError = - batch.listRecordSets(ZONE1.name(), Dns.RecordSetListOption.pageSize(0)); + batch.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(0)); DnsBatchResult> negativeSizeError = - batch.listRecordSets(ZONE1.name(), Dns.RecordSetListOption.pageSize(-1)); + batch.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(-1)); batch.submit(); // check wrong arguments try { @@ -1840,7 +1846,7 @@ public void testListDnsRecordSetsBatch() { assertEquals(400, ex.code()); assertFalse(ex.retryable()); } - waitForChangeToComplete(ZONE1.name(), change.generatedId()); + waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); } finally { clear(); } @@ -1865,17 +1871,17 @@ public void testBatchCombined() { // expected } batch.submit(); - assertNotNull(zoneResult.get().creationTimeMillis()); - assertEquals(ZONE1.dnsName(), zoneResult.get().dnsName()); - assertEquals(ZONE1.description(), zoneResult.get().description()); - assertFalse(zoneResult.get().nameServers().isEmpty()); - assertNull(zoneResult.get().nameServerSet()); // we did not set it - assertNotNull(zoneResult.get().generatedId()); - assertNotNull(projectResult.get().quota()); + assertNotNull(zoneResult.get().getCreationTimeMillis()); + assertEquals(ZONE1.getDnsName(), zoneResult.get().getDnsName()); + assertEquals(ZONE1.getDescription(), zoneResult.get().getDescription()); + assertFalse(zoneResult.get().getNameServers().isEmpty()); + assertNull(zoneResult.get().getNameServerSet()); // we did not set it + assertNotNull(zoneResult.get().getGeneratedId()); + assertNotNull(projectResult.get().getQuota()); assertEquals(2, Iterables.size(pageResult.get().values())); assertNotNull(changeRequestResult.get()); } finally { - DNS.delete(ZONE1.name()); + DNS.delete(ZONE1.getName()); } } } diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/testing/LocalDnsHelperTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/testing/LocalDnsHelperTest.java index 6831485f821e..fd9ee2126013 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/testing/LocalDnsHelperTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/testing/LocalDnsHelperTest.java @@ -74,8 +74,8 @@ public class LocalDnsHelperTest { private static final Change CHANGE_COMPLEX = new Change(); private static final LocalDnsHelper LOCAL_DNS_HELPER = LocalDnsHelper.create(0L); 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 static final DnsRpc RPC = new DefaultDnsRpc(LOCAL_DNS_HELPER.getOptions()); + private static final String REAL_PROJECT_ID = LOCAL_DNS_HELPER.getOptions().projectId(); private Map optionsMap; private static abstract class FailExpectedCallback implements RpcBatch.Callback { diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/DnsExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/DnsExample.java index 65b6178ae486..783cccb699d6 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/DnsExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/DnsExample.java @@ -87,7 +87,7 @@ public void run(Dns dns, String... args) { 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.generatedId()); + zone.getName(), zone.getGeneratedId()); } @Override @@ -201,16 +201,17 @@ public void run(Dns dns, String... args) { if (args.length > 3) { ttl = Integer.parseInt(args[3]); } - RecordSet recordSet = RecordSet.builder(recordName, RecordSet.Type.A) - .records(ImmutableList.of(ip)) - .ttl(ttl, TimeUnit.SECONDS) + RecordSet recordSet = RecordSet.newBuilder(recordName, RecordSet.Type.A) + .setRecords(ImmutableList.of(ip)) + .setTtl(ttl, TimeUnit.SECONDS) .build(); - ChangeRequestInfo changeRequest = ChangeRequest.builder() + ChangeRequestInfo changeRequest = ChangeRequest.newBuilder() .delete(recordSet) .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.generatedId()); + + "submitted and assigned ID %s.%n", recordName, zoneName, + changeRequest.getGeneratedId()); System.out.print("Waiting for deletion to happen..."); waitForChangeToFinish(dns, zoneName, changeRequest); System.out.printf("%nThe deletion has been completed.%n"); @@ -248,14 +249,15 @@ public void run(Dns dns, String... args) { if (args.length > 3) { ttl = Integer.parseInt(args[3]); } - RecordSet recordSet = RecordSet.builder(recordName, RecordSet.Type.A) - .records(ImmutableList.of(ip)) - .ttl(ttl, TimeUnit.SECONDS) + RecordSet recordSet = RecordSet.newBuilder(recordName, RecordSet.Type.A) + .setRecords(ImmutableList.of(ip)) + .setTtl(ttl, TimeUnit.SECONDS) .build(); - ChangeRequestInfo changeRequest = ChangeRequest.builder().add(recordSet).build(); + ChangeRequestInfo changeRequest = ChangeRequest.newBuilder().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.generatedId()); + + "submitted and assigned ID %s.%n", recordName, zoneName, + changeRequest.getGeneratedId()); System.out.print("Waiting for addition to happen..."); waitForChangeToFinish(dns, zoneName, changeRequest); System.out.printf("The addition has been completed.%n"); @@ -291,8 +293,8 @@ public void run(Dns dns, String... args) { System.out.printf("Record sets for zone %s:%n", zoneName); while (iterator.hasNext()) { RecordSet recordSet = iterator.next(); - System.out.printf("%nRecord name: %s%nTTL: %s%nRecords: %s%n", recordSet.name(), - recordSet.ttl(), Joiner.on(", ").join(recordSet.records())); + System.out.printf("%nRecord name: %s%nTTL: %s%nRecords: %s%n", recordSet.getName(), + recordSet.getTtl(), Joiner.on(", ").join(recordSet.getRecords())); } } else { System.out.printf("Zone %s has no record sets records.%n", zoneName); @@ -331,11 +333,11 @@ public void run(Dns dns, String... args) { System.out.printf("Change requests for zone %s:%n", zoneName); while (iterator.hasNext()) { ChangeRequest change = iterator.next(); - System.out.printf("%nID: %s%n", change.generatedId()); + System.out.printf("%nID: %s%n", change.getGeneratedId()); System.out.printf("Status: %s%n", change.status()); - System.out.printf("Started: %s%n", FORMATTER.print(change.startTimeMillis())); - System.out.printf("Deletions: %s%n", Joiner.on(", ").join(change.deletions())); - System.out.printf("Additions: %s%n", Joiner.on(", ").join(change.additions())); + System.out.printf("Started: %s%n", FORMATTER.print(change.getStartTimeMillis())); + System.out.printf("Deletions: %s%n", Joiner.on(", ").join(change.getDeletions())); + System.out.printf("Additions: %s%n", Joiner.on(", ").join(change.getAdditions())); } } else { System.out.printf("Zone %s has no change requests.%n", zoneName); @@ -401,16 +403,16 @@ private static class GetProjectAction implements DnsAction { @Override public void run(Dns dns, String... args) { ProjectInfo project = dns.getProject(); - ProjectInfo.Quota quota = project.quota(); + ProjectInfo.Quota quota = project.getQuota(); System.out.printf("Project id: %s%nQuota:%n", dns.options().projectId()); - System.out.printf("\tZones: %d%n", quota.zones()); - System.out.printf("\tRecord sets per zone: %d%n", quota.rrsetsPerZone()); + System.out.printf("\tZones: %d%n", quota.getZones()); + System.out.printf("\tRecord sets per zone: %d%n", quota.getRrsetsPerZone()); System.out.printf("\tRecord sets per DNS record: %d%n", - quota.resourceRecordsPerRrset()); - System.out.printf("\tAdditions per change: %d%n", quota.rrsetAdditionsPerChange()); - System.out.printf("\tDeletions per change: %d%n", quota.rrsetDeletionsPerChange()); + quota.getResourceRecordsPerRrset()); + System.out.printf("\tAdditions per change: %d%n", quota.getRrsetAdditionsPerChange()); + System.out.printf("\tDeletions per change: %d%n", quota.getRrsetDeletionsPerChange()); System.out.printf("\tTotal data size per change: %d%n", - quota.totalRrdataSizePerChange()); + quota.getTotalRrdataSizePerChange()); } @Override @@ -435,11 +437,11 @@ public boolean check(String... args) { } private static void printZone(Zone zone) { - System.out.printf("%nName: %s%n", zone.name()); - System.out.printf("ID: %s%n", zone.generatedId()); - System.out.printf("Description: %s%n", zone.description()); - System.out.printf("Created: %s%n", FORMATTER.print(zone.creationTimeMillis())); - System.out.printf("Name servers: %s%n", Joiner.on(", ").join(zone.nameServers())); + System.out.printf("%nName: %s%n", zone.getName()); + System.out.printf("ID: %s%n", zone.getGeneratedId()); + System.out.printf("Description: %s%n", zone.getDescription()); + System.out.printf("Created: %s%n", FORMATTER.print(zone.getCreationTimeMillis())); + System.out.printf("Name servers: %s%n", Joiner.on(", ").join(zone.getNameServers())); } private static ChangeRequestInfo waitForChangeToFinish(Dns dns, String zoneName, @@ -452,7 +454,7 @@ private static ChangeRequestInfo waitForChangeToFinish(Dns dns, String zoneName, } catch (InterruptedException e) { System.err.println("Thread was interrupted while waiting."); } - current = dns.getChangeRequest(zoneName, current.generatedId()); + current = dns.getChangeRequest(zoneName, current.getGeneratedId()); } return current; } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateOrUpdateRecordSets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateOrUpdateRecordSets.java index b49cdeede5fb..997e35e6a8e6 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateOrUpdateRecordSets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateOrUpdateRecordSets.java @@ -49,20 +49,21 @@ public static void main(String... args) { // Prepare a www.. type A record set with ttl of 24 hours String ip = "12.13.14.15"; - RecordSet toCreate = RecordSet.builder("www." + zone.dnsName(), RecordSet.Type.A) - .ttl(24, TimeUnit.HOURS) + RecordSet toCreate = RecordSet.newBuilder("www." + zone.getDnsName(), RecordSet.Type.A) + .setTtl(24, TimeUnit.HOURS) .addRecord(ip) .build(); // Make a change - ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder().add(toCreate); + ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.newBuilder().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 recordSetIterator = zone.listRecordSets().iterateAll(); while (recordSetIterator.hasNext()) { RecordSet current = recordSetIterator.next(); - if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) { + if (toCreate.getName().equals(current.getName()) + && toCreate.getType().equals(current.getType())) { changeBuilder.delete(current); } } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateZone.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateZone.java index f205cc0d2c9a..57939ca9e07a 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateZone.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateZone.java @@ -46,6 +46,6 @@ public static void main(String... args) { // Create zone in Google Cloud DNS Zone zone = dns.create(zoneInfo); - System.out.printf("Zone was created and assigned ID %s.%n", zone.generatedId()); + System.out.printf("Zone was created and assigned ID %s.%n", zone.getGeneratedId()); } } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/DeleteZone.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/DeleteZone.java index 317daf0c2e7d..1202c66b51ac 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/DeleteZone.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/DeleteZone.java @@ -48,18 +48,19 @@ public static void main(String... args) { Iterator recordIterator = dns.listRecordSets(zoneName).iterateAll(); // Make a change for deleting the records - ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder(); + ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.newBuilder(); while (recordIterator.hasNext()) { RecordSet current = recordIterator.next(); // SOA and NS records cannot be deleted - if (!RecordSet.Type.SOA.equals(current.type()) && !RecordSet.Type.NS.equals(current.type())) { + if (!RecordSet.Type.SOA.equals(current.getType()) + && !RecordSet.Type.NS.equals(current.getType())) { changeBuilder.delete(current); } } // Build and apply the change request to our zone if it contains records to delete ChangeRequestInfo changeRequest = changeBuilder.build(); - if (!changeRequest.deletions().isEmpty()) { + if (!changeRequest.getDeletions().isEmpty()) { ChangeRequest pendingRequest = dns.applyChangeRequest(zoneName, changeRequest); // Wait for the change request to complete diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java index 1afceefeea23..1cfa768c220e 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java @@ -51,30 +51,31 @@ public static void main(String... args) { // Create zone in Google Cloud DNS Zone zone = dns.create(zoneInfo); - System.out.printf("Zone was created and assigned ID %s.%n", zone.generatedId()); + System.out.printf("Zone was created and assigned ID %s.%n", zone.getGeneratedId()); // Print assigned name servers - List nameServers = zone.nameServers(); + List nameServers = zone.getNameServers(); 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"; - RecordSet toCreate = RecordSet.builder("www.someexampledomain.com.", RecordSet.Type.A) - .ttl(24, TimeUnit.HOURS) + RecordSet toCreate = RecordSet.newBuilder("www.someexampledomain.com.", RecordSet.Type.A) + .setTtl(24, TimeUnit.HOURS) .addRecord(ip) .build(); // Make a change - ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.builder().add(toCreate); + ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.newBuilder().add(toCreate); // Verify the type A record does not exist yet. // If it does exist, we will overwrite it with our prepared record. Iterator recordSetIterator = zone.listRecordSets().iterateAll(); while (recordSetIterator.hasNext()) { RecordSet current = recordSetIterator.next(); - if (toCreate.name().equals(current.name()) && toCreate.type().equals(current.type())) { + if (toCreate.getName().equals(current.getName()) + && toCreate.getType().equals(current.getType())) { changeBuilder.delete(current); } } @@ -89,7 +90,7 @@ public static void main(String... args) { } catch (InterruptedException e) { System.err.println("The thread was interrupted while waiting..."); } - changeRequest = dns.getChangeRequest(zone.name(), changeRequest.generatedId()); + changeRequest = dns.getChangeRequest(zone.getName(), changeRequest.getGeneratedId()); } System.out.println("The change request has been applied."); @@ -103,31 +104,32 @@ public static void main(String... args) { // List the record sets in a particular zone recordSetIterator = zone.listRecordSets().iterateAll(); - System.out.println(String.format("Record sets inside %s:", zone.name())); + System.out.println(String.format("Record sets inside %s:", zone.getName())); while (recordSetIterator.hasNext()) { System.out.println(recordSetIterator.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())); + System.out.println(String.format("The history of changes in %s:", zone.getName())); while (changeIterator.hasNext()) { System.out.println(changeIterator.next()); } // Make a change for deleting the record sets - changeBuilder = ChangeRequestInfo.builder(); + changeBuilder = ChangeRequestInfo.newBuilder(); while (recordSetIterator.hasNext()) { RecordSet current = recordSetIterator.next(); // SOA and NS records cannot be deleted - if (!RecordSet.Type.SOA.equals(current.type()) && !RecordSet.Type.NS.equals(current.type())) { + if (!RecordSet.Type.SOA.equals(current.getType()) + && !RecordSet.Type.NS.equals(current.getType())) { 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()) { + if (!changeRequest.getDeletions().isEmpty()) { ChangeRequest pendingRequest = dns.applyChangeRequest(zoneName, changeRequest); // Wait for the change request to complete From f283895625413ed79d939891f700e9faed9e00cf Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Fri, 21 Oct 2016 08:06:43 +0200 Subject: [PATCH 13/32] Rename setters/getters/builders for Storage classes to meet proto conventions (#1308) * Rename setters/getters/builders for Storage classes to meet proto conventions * Favor renaming over deprecation for package-private methods * Update TESTING.md to catch RemoteStorageHelper renaming * Update ITBigQueryTest to match Storage renaming * Update google-cloud-nio to match Storage renaming * Fix RemoteStorageHelper class javadoc * Make deprecated methods call renamed ones --- README.md | 4 +- TESTING.md | 2 +- .../cloud/bigquery/it/ITBigQueryTest.java | 8 +- .../nio/CloudStorageFileSystemProvider.java | 50 +- .../nio/CloudStorageObjectAttributes.java | 26 +- .../contrib/nio/CloudStorageReadChannel.java | 4 +- .../contrib/nio/CloudStoragePathTest.java | 10 +- .../nio/CloudStorageReadChannelTest.java | 2 +- .../storage/contrib/nio/it/ITGcsNio.java | 4 +- .../examples/storage/StorageExample.java | 43 +- .../storage/snippets/BlobSnippets.java | 20 +- .../storage/snippets/BucketSnippets.java | 2 +- .../CreateAndListBucketsAndBlobs.java | 2 +- .../examples/storage/snippets/CreateBlob.java | 2 +- .../storage/snippets/StorageSnippets.java | 54 +- .../examples/storage/snippets/UpdateBlob.java | 2 +- .../storage/snippets/ITBlobSnippets.java | 12 +- .../storage/snippets/ITBucketSnippets.java | 18 +- .../storage/snippets/ITStorageSnippets.java | 76 +-- google-cloud-storage/README.md | 2 +- .../java/com/google/cloud/storage/Acl.java | 163 ++++- .../java/com/google/cloud/storage/Blob.java | 218 ++++--- .../java/com/google/cloud/storage/BlobId.java | 30 +- .../com/google/cloud/storage/BlobInfo.java | 575 +++++++++++++++--- .../java/com/google/cloud/storage/Bucket.java | 218 ++++--- .../com/google/cloud/storage/BucketInfo.java | 366 ++++++++++- .../com/google/cloud/storage/CopyWriter.java | 62 +- .../java/com/google/cloud/storage/Cors.java | 92 ++- .../java/com/google/cloud/storage/Option.java | 4 +- .../com/google/cloud/storage/Storage.java | 312 ++++++++-- .../com/google/cloud/storage/StorageImpl.java | 93 +-- .../google/cloud/storage/package-info.java | 4 +- .../storage/testing/RemoteStorageHelper.java | 18 +- .../cloud/storage/testing/package-info.java | 2 +- .../com/google/cloud/storage/AclTest.java | 89 ++- .../com/google/cloud/storage/BlobIdTest.java | 11 +- .../google/cloud/storage/BlobInfoTest.java | 343 +++++++---- .../com/google/cloud/storage/BlobTest.java | 245 +++++--- .../google/cloud/storage/BucketInfoTest.java | 173 ++++-- .../com/google/cloud/storage/BucketTest.java | 186 +++--- .../google/cloud/storage/CopyRequestTest.java | 67 +- .../google/cloud/storage/CopyWriterTest.java | 69 ++- .../com/google/cloud/storage/CorsTest.java | 18 + .../com/google/cloud/storage/OptionTest.java | 8 +- .../cloud/storage/SerializationTest.java | 8 +- .../cloud/storage/StorageBatchTest.java | 19 +- .../google/cloud/storage/StorageImplTest.java | 314 +++++----- .../cloud/storage/it/ITStorageTest.java | 557 ++++++++--------- .../testing/RemoteStorageHelperTest.java | 23 +- 49 files changed, 3238 insertions(+), 1392 deletions(-) diff --git a/README.md b/README.md index 6ce14f2c6447..fe73f9e44561 100644 --- a/README.md +++ b/README.md @@ -548,7 +548,7 @@ import com.google.cloud.storage.StorageOptions; Storage storage = StorageOptions.defaultInstance().service(); BlobId blobId = BlobId.of("bucket", "blob_name"); -BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); +BlobInfo blobInfo = BlobInfo.newBuiler(blobId).setContentType("text/plain").build(); Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8)); ``` The second snippet shows how to update a Storage blob if it exists. Complete source code can be @@ -569,7 +569,7 @@ Storage storage = StorageOptions.defaultInstance().service(); BlobId blobId = BlobId.of("bucket", "blob_name"); Blob blob = storage.get(blobId); if (blob != null) { - byte[] prevContent = blob.content(); + byte[] prevContent = blob.getContent(); System.out.println(new String(prevContent, UTF_8)); WritableByteChannel channel = blob.writer(); channel.write(ByteBuffer.wrap("Updated content".getBytes(UTF_8))); diff --git a/TESTING.md b/TESTING.md index d3a0b18c1247..7d37f1c7d466 100644 --- a/TESTING.md +++ b/TESTING.md @@ -258,7 +258,7 @@ Here is an example that uses the `RemoteStorageHelper` to create a bucket. ```java RemoteStorageHelper helper = RemoteStorageHelper.create(PROJECT_ID, new FileInputStream("/path/to/my/JSON/key.json")); - Storage storage = helper.options().service(); + Storage storage = helper.getOptions().service(); String bucket = RemoteStorageHelper.generateBucketName(); storage.create(BucketInfo.of(bucket)); ``` diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java index 6eb4d6a6a7b7..367935d298bb 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java @@ -194,11 +194,13 @@ public static void beforeClass() throws InterruptedException, TimeoutException { RemoteBigQueryHelper bigqueryHelper = RemoteBigQueryHelper.create(); RemoteStorageHelper storageHelper = RemoteStorageHelper.create(); bigquery = bigqueryHelper.options().service(); - storage = storageHelper.options().service(); + storage = storageHelper.getOptions().service(); storage.create(BucketInfo.of(BUCKET)); - storage.create(BlobInfo.builder(BUCKET, LOAD_FILE).contentType("text/plain").build(), + storage.create(BlobInfo.newBuilder(BUCKET, LOAD_FILE).setContentType("text/plain").build(), CSV_CONTENT.getBytes(StandardCharsets.UTF_8)); - storage.create(BlobInfo.builder(BUCKET, JSON_LOAD_FILE).contentType("application/json").build(), + storage.create(BlobInfo.newBuilder(BUCKET, JSON_LOAD_FILE) + .setContentType("application/json") + .build(), JSON_CONTENT.getBytes(StandardCharsets.UTF_8)); DatasetInfo info = DatasetInfo.builder(DATASET).description(DESCRIPTION).build(); bigquery.create(info); diff --git a/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemProvider.java b/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemProvider.java index ceb3428ea24a..dc95dacca4c1 100644 --- a/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemProvider.java +++ b/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemProvider.java @@ -106,7 +106,7 @@ private static class LazyPathIterator extends AbstractIterator { @Override protected Path computeNext() { while (blobIterator.hasNext()) { - Path path = fileSystem.getPath(blobIterator.next().name()); + Path path = fileSystem.getPath(blobIterator.next().getName()); try { if (filter.accept(path)) { return path; @@ -266,20 +266,20 @@ private SeekableByteChannel newWriteChannel(Path path, Set throw new CloudStoragePseudoDirectoryException(cloudPath); } BlobId file = cloudPath.getBlobId(); - BlobInfo.Builder infoBuilder = BlobInfo.builder(file); + BlobInfo.Builder infoBuilder = BlobInfo.newBuilder(file); List writeOptions = new ArrayList<>(); List acls = new ArrayList<>(); HashMap metas = new HashMap<>(); for (OpenOption option : options) { if (option instanceof OptionMimeType) { - infoBuilder.contentType(((OptionMimeType) option).mimeType()); + infoBuilder.setContentType(((OptionMimeType) option).mimeType()); } else if (option instanceof OptionCacheControl) { - infoBuilder.cacheControl(((OptionCacheControl) option).cacheControl()); + infoBuilder.setCacheControl(((OptionCacheControl) option).cacheControl()); } else if (option instanceof OptionContentDisposition) { - infoBuilder.contentDisposition(((OptionContentDisposition) option).contentDisposition()); + infoBuilder.setContentDisposition(((OptionContentDisposition) option).contentDisposition()); } else if (option instanceof OptionContentEncoding) { - infoBuilder.contentEncoding(((OptionContentEncoding) option).contentEncoding()); + infoBuilder.setContentEncoding(((OptionContentEncoding) option).contentEncoding()); } else if (option instanceof OptionUserMetadata) { OptionUserMetadata opMeta = (OptionUserMetadata) option; metas.put(opMeta.key(), opMeta.value()); @@ -317,10 +317,10 @@ private SeekableByteChannel newWriteChannel(Path path, Set } if (!metas.isEmpty()) { - infoBuilder.metadata(metas); + infoBuilder.setMetadata(metas); } if (!acls.isEmpty()) { - infoBuilder.acl(acls); + infoBuilder.setAcl(acls); } try { @@ -391,7 +391,7 @@ public void copy(Path source, Path target, CopyOption... options) throws IOExcep boolean setContentDisposition = false; CloudStoragePath toPath = CloudStorageUtil.checkPath(target); - BlobInfo.Builder tgtInfoBuilder = BlobInfo.builder(toPath.getBlobId()).contentType(""); + BlobInfo.Builder tgtInfoBuilder = BlobInfo.newBuilder(toPath.getBlobId()).setContentType(""); int blockSize = -1; for (CopyOption option : options) { @@ -411,16 +411,16 @@ public void copy(Path source, Path target, CopyOption... options) throws IOExcep if (option instanceof OptionBlockSize) { blockSize = ((OptionBlockSize) option).size(); } else if (option instanceof OptionMimeType) { - tgtInfoBuilder.contentType(((OptionMimeType) option).mimeType()); + tgtInfoBuilder.setContentType(((OptionMimeType) option).mimeType()); setContentType = true; } else if (option instanceof OptionCacheControl) { - tgtInfoBuilder.cacheControl(((OptionCacheControl) option).cacheControl()); + tgtInfoBuilder.setCacheControl(((OptionCacheControl) option).cacheControl()); setCacheControl = true; } else if (option instanceof OptionContentEncoding) { - tgtInfoBuilder.contentEncoding(((OptionContentEncoding) option).contentEncoding()); + tgtInfoBuilder.setContentEncoding(((OptionContentEncoding) option).contentEncoding()); setContentEncoding = true; } else if (option instanceof OptionContentDisposition) { - tgtInfoBuilder.contentDisposition( + tgtInfoBuilder.setContentDisposition( ((OptionContentDisposition) option).contentDisposition()); setContentDisposition = true; } else { @@ -467,31 +467,31 @@ public void copy(Path source, Path target, CopyOption... options) throws IOExcep throw new NoSuchFileException(fromPath.toString()); } if (!setCacheControl) { - tgtInfoBuilder.cacheControl(blobInfo.cacheControl()); + tgtInfoBuilder.setCacheControl(blobInfo.getCacheControl()); } if (!setContentType) { - tgtInfoBuilder.contentType(blobInfo.contentType()); + tgtInfoBuilder.setContentType(blobInfo.getContentType()); } if (!setContentEncoding) { - tgtInfoBuilder.contentEncoding(blobInfo.contentEncoding()); + tgtInfoBuilder.setContentEncoding(blobInfo.getContentEncoding()); } if (!setContentDisposition) { - tgtInfoBuilder.contentDisposition(blobInfo.contentDisposition()); + tgtInfoBuilder.setContentDisposition(blobInfo.getContentDisposition()); } - tgtInfoBuilder.acl(blobInfo.acl()); - tgtInfoBuilder.metadata(blobInfo.metadata()); + tgtInfoBuilder.setAcl(blobInfo.getAcl()); + tgtInfoBuilder.setMetadata(blobInfo.getMetadata()); } BlobInfo tgtInfo = tgtInfoBuilder.build(); Storage.CopyRequest.Builder copyReqBuilder = - Storage.CopyRequest.builder().source(fromPath.getBlobId()); + Storage.CopyRequest.newBuilder().setSource(fromPath.getBlobId()); if (wantReplaceExisting) { - copyReqBuilder = copyReqBuilder.target(tgtInfo); + copyReqBuilder = copyReqBuilder.setTarget(tgtInfo); } else { - copyReqBuilder = copyReqBuilder.target(tgtInfo, Storage.BlobTargetOption.doesNotExist()); + copyReqBuilder = copyReqBuilder.setTarget(tgtInfo, Storage.BlobTargetOption.doesNotExist()); } CopyWriter copyWriter = storage.copy(copyReqBuilder.build()); - copyWriter.result(); + copyWriter.getResult(); } catch (StorageException oops) { throw asIoException(oops); } @@ -551,9 +551,9 @@ public A readAttributes( } BlobInfo blobInfo = storage.get(cloudPath.getBlobId()); // null size indicate a file that we haven't closed yet, so GCS treats it as not there yet. - if (null == blobInfo || blobInfo.size() == null) { + if (null == blobInfo || blobInfo.getSize() == null) { throw new NoSuchFileException( - cloudPath.getBlobId().bucket() + "/" + cloudPath.getBlobId().name()); + cloudPath.getBlobId().getBucket() + "/" + cloudPath.getBlobId().getName()); } CloudStorageObjectAttributes ret; ret = new CloudStorageObjectAttributes(blobInfo); diff --git a/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageObjectAttributes.java b/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageObjectAttributes.java index 56f02749c727..e9553533ceca 100644 --- a/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageObjectAttributes.java +++ b/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageObjectAttributes.java @@ -45,15 +45,15 @@ final class CloudStorageObjectAttributes implements CloudStorageFileAttributes { @Override public long size() { - return info.size(); + return info.getSize(); } @Override public FileTime creationTime() { - if (info.updateTime() == null) { + if (info.getUpdateTime() == null) { return CloudStorageFileSystem.FILE_TIME_UNKNOWN; } - return FileTime.fromMillis(info.updateTime()); + return FileTime.fromMillis(info.getUpdateTime()); } @Override @@ -63,40 +63,40 @@ public FileTime lastModifiedTime() { @Override public Optional etag() { - return Optional.fromNullable(info.etag()); + return Optional.fromNullable(info.getEtag()); } @Override public Optional mimeType() { - return Optional.fromNullable(info.contentType()); + return Optional.fromNullable(info.getContentType()); } @Override public Optional> acl() { - return Optional.fromNullable(info.acl()); + return Optional.fromNullable(info.getAcl()); } @Override public Optional cacheControl() { - return Optional.fromNullable(info.cacheControl()); + return Optional.fromNullable(info.getCacheControl()); } @Override public Optional contentEncoding() { - return Optional.fromNullable(info.contentEncoding()); + return Optional.fromNullable(info.getContentEncoding()); } @Override public Optional contentDisposition() { - return Optional.fromNullable(info.contentDisposition()); + return Optional.fromNullable(info.getContentDisposition()); } @Override public ImmutableMap userMetadata() { - if (null == info.metadata()) { + if (null == info.getMetadata()) { return ImmutableMap.of(); } - return ImmutableMap.copyOf(info.metadata()); + return ImmutableMap.copyOf(info.getMetadata()); } @Override @@ -126,7 +126,9 @@ public FileTime lastAccessTime() { @Override public Object fileKey() { - return info.blobId().bucket() + info.blobId().name() + info.blobId().generation(); + return info.getBlobId().getBucket() + + info.getBlobId().getName() + + info.getBlobId().getGeneration(); } @Override diff --git a/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageReadChannel.java b/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageReadChannel.java index bd9cb9def6c5..99aeda874c80 100644 --- a/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageReadChannel.java +++ b/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageReadChannel.java @@ -143,8 +143,8 @@ private void checkOpen() throws ClosedChannelException { private static long fetchSize(Storage gcsStorage, BlobId file) throws IOException { BlobInfo blobInfo = gcsStorage.get(file); if (blobInfo == null) { - throw new NoSuchFileException(String.format("gs://%s/%s", file.bucket(), file.name())); + throw new NoSuchFileException(String.format("gs://%s/%s", file.getBucket(), file.getName())); } - return blobInfo.size(); + return blobInfo.getSize(); } } diff --git a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStoragePathTest.java b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStoragePathTest.java index 95d5df729ce5..6b38288cda2e 100644 --- a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStoragePathTest.java +++ b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStoragePathTest.java @@ -76,14 +76,14 @@ public void testGetGcsFilename_empty_notAllowed() throws IOException { @Test public void testGetGcsFilename_stripsPrefixSlash() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { - assertThat(fs.getPath("/hi").getBlobId().name()).isEqualTo("hi"); + assertThat(fs.getPath("/hi").getBlobId().getName()).isEqualTo("hi"); } } @Test public void testGetGcsFilename_overrideStripPrefixSlash_doesntStripPrefixSlash() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle", stripPrefixSlash(false))) { - assertThat(fs.getPath("/hi").getBlobId().name()).isEqualTo("/hi"); + assertThat(fs.getPath("/hi").getBlobId().getName()).isEqualTo("/hi"); } } @@ -91,14 +91,14 @@ public void testGetGcsFilename_overrideStripPrefixSlash_doesntStripPrefixSlash() public void testGetGcsFilename_extraSlashes_throwsIae() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { thrown.expect(IllegalArgumentException.class); - fs.getPath("a//b").getBlobId().name(); + fs.getPath("a//b").getBlobId().getName(); } } @Test public void testGetGcsFilename_overridepermitEmptyPathComponents() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle", permitEmptyPathComponents(true))) { - assertThat(fs.getPath("a//b").getBlobId().name()).isEqualTo("a//b"); + assertThat(fs.getPath("a//b").getBlobId().getName()).isEqualTo("a//b"); } } @@ -106,7 +106,7 @@ public void testGetGcsFilename_overridepermitEmptyPathComponents() throws IOExce public void testGetGcsFilename_freaksOutOnExtraSlashesAndDotDirs() throws IOException { try (CloudStorageFileSystem fs = CloudStorageFileSystem.forBucket("doodle")) { thrown.expect(IllegalArgumentException.class); - fs.getPath("a//b/..").getBlobId().name(); + fs.getPath("a//b/..").getBlobId().getName(); } } diff --git a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageReadChannelTest.java b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageReadChannelTest.java index ac42be8cd155..526a45eae430 100644 --- a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageReadChannelTest.java +++ b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageReadChannelTest.java @@ -59,7 +59,7 @@ public class CloudStorageReadChannelTest { @Before public void before() throws IOException { - when(metadata.size()).thenReturn(42L); + when(metadata.getSize()).thenReturn(42L); when(gcsStorage.get(file)).thenReturn(metadata); when(gcsStorage.reader(eq(file))).thenReturn(gcsChannel); when(gcsChannel.isOpen()).thenReturn(true); diff --git a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/it/ITGcsNio.java b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/it/ITGcsNio.java index 6a0cf0a9113e..e874dcfaced3 100644 --- a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/it/ITGcsNio.java +++ b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/it/ITGcsNio.java @@ -98,7 +98,7 @@ public class ITGcsNio { public static void beforeClass() throws IOException { // loads the credentials from local disk as par README RemoteStorageHelper gcsHelper = RemoteStorageHelper.create(); - storageOptions = gcsHelper.options(); + storageOptions = gcsHelper.getOptions(); storage = storageOptions.service(); // create and populate test bucket storage.create(BucketInfo.of(BUCKET)); @@ -121,7 +121,7 @@ private static byte[] randomContents(int size) { } private static void fillFile(Storage storage, String fname, int size) throws IOException { - storage.create(BlobInfo.builder(BUCKET, fname).build(), randomContents(size)); + storage.create(BlobInfo.newBuilder(BUCKET, fname).build(), randomContents(size)); } @Test diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java index 9d7548058b4f..8eb63d541df3 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java @@ -54,7 +54,6 @@ import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; -import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -182,9 +181,9 @@ private static class InfoAction extends BlobsAction { @Override public void run(Storage storage, BlobId... blobIds) { if (blobIds.length == 1) { - if (blobIds[0].name().isEmpty()) { + if (blobIds[0].getName().isEmpty()) { // get Bucket - Bucket bucket = storage.get(blobIds[0].bucket()); + Bucket bucket = storage.get(blobIds[0].getBucket()); if (bucket == null) { System.out.println("No such bucket"); return; @@ -229,7 +228,8 @@ public String params() { * If more than one blob is supplied a Batch operation would be used to delete all requested * blobs in a single RPC. * - * @see Objects: delete + * @see + * Objects: delete */ private static class DeleteAction extends BlobsAction { @Override @@ -296,7 +296,8 @@ public String params() { /** * This class demonstrates how to create a new Blob or to update its content. * - * @see Objects: insert + * @see + * Objects: insert */ private static class UploadAction extends StorageAction> { @Override @@ -337,7 +338,7 @@ Tuple parse(String... args) throws IOException { Path path = Paths.get(args[0]); String contentType = Files.probeContentType(path); String blob = args.length < 3 ? path.getFileName().toString() : args[2]; - return Tuple.of(path, BlobInfo.builder(args[1], blob).contentType(contentType).build()); + return Tuple.of(path, BlobInfo.newBuilder(args[1], blob).setContentType(contentType).build()); } @Override @@ -370,9 +371,9 @@ private void run(Storage storage, BlobId blobId, Path downloadTo) throws IOExcep if (downloadTo != null) { writeTo = new PrintStream(new FileOutputStream(downloadTo.toFile())); } - if (blob.size() < 1_000_000) { + if (blob.getSize() < 1_000_000) { // Blob is small read all its content in one request - byte[] content = blob.content(); + byte[] content = blob.getContent(); writeTo.write(content); } else { // When Blob size is big or unknown use the blob's channel reader. @@ -425,7 +426,7 @@ private static class CopyAction extends StorageAction { @Override public void run(Storage storage, CopyRequest request) { CopyWriter copyWriter = storage.copy(request); - System.out.printf("Copied %s%n", copyWriter.result()); + System.out.printf("Copied %s%n", copyWriter.getResult()); } @Override @@ -445,7 +446,8 @@ public String params() { /** * This class demonstrates how to use the compose command. * - * @see Objects: compose + * @see + * Objects: compose */ private static class ComposeAction extends StorageAction { @Override @@ -459,8 +461,8 @@ ComposeRequest parse(String... args) { if (args.length < 3) { throw new IllegalArgumentException(); } - ComposeRequest.Builder request = ComposeRequest.builder(); - request.target(BlobInfo.builder(args[0], args[args.length - 1]).build()); + ComposeRequest.Builder request = ComposeRequest.newBuilder(); + request.setTarget(BlobInfo.newBuilder(args[0], args[args.length - 1]).build()); for (int i = 1; i < args.length - 1; i++) { request.addSource(args[i]); } @@ -476,7 +478,8 @@ public String params() { /** * This class demonstrates how to update a blob's metadata. * - * @see Objects: update + * @see + * Objects: update */ private static class UpdateMetadataAction extends StorageAction>> { @@ -493,7 +496,7 @@ private void run(Storage storage, BlobId blobId, Map metadata) { System.out.println("No such object"); return; } - Blob updateBlob = blob.toBuilder().metadata(metadata).build().update(); + Blob updateBlob = blob.toBuilder().setMetadata(metadata).build().update(); System.out.printf("Updated %s%n", updateBlob); } @@ -539,7 +542,7 @@ public void run(Storage storage, Tuple } private void run(Storage storage, ServiceAccountAuthCredentials cred, BlobInfo blobInfo) { - Blob blob = storage.get(blobInfo.blobId()); + Blob blob = storage.get(blobInfo.getBlobId()); System.out.printf("Signed URL: %s%n", blob.signUrl(1, TimeUnit.DAYS, SignUrlOption.signWith(cred))); } @@ -555,7 +558,7 @@ Tuple parse(String... args) throws IOEx keystore.load(Files.newInputStream(Paths.get(args[0])), PASSWORD); PrivateKey privateKey = (PrivateKey) keystore.getKey("privatekey", PASSWORD); ServiceAccountAuthCredentials cred = AuthCredentials.createFor(args[1], privateKey); - return Tuple.of(cred, BlobInfo.builder(BlobId.of(args[2], args[3])).build()); + return Tuple.of(cred, BlobInfo.newBuilder(BlobId.of(args[2], args[3])).build()); } @Override @@ -576,14 +579,14 @@ private abstract static class AclAction extends StorageAction public void run(Storage storage, Tuple params) { BlobId blobId = params.x(); Acl acl = params.y(); - if (blobId.name().isEmpty()) { - Bucket bucket = storage.get(blobId.bucket()); + if (blobId.getName().isEmpty()) { + Bucket bucket = storage.get(blobId.getBucket()); if (bucket == null) { - System.out.printf("Bucket %s does not exist%n", blobId.bucket()); + System.out.printf("Bucket %s does not exist%n", blobId.getBucket()); return; } acl = bucket.createAcl(acl); - System.out.printf("Added ACL %s to bucket %s%n", acl, blobId.bucket()); + System.out.printf("Added ACL %s to bucket %s%n", acl, blobId.getBucket()); } else { Blob blob = storage.get(blobId); if (blob == null) { diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/BlobSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/BlobSnippets.java index d382f9c8f09a..18c2519e38a2 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/BlobSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/BlobSnippets.java @@ -77,11 +77,11 @@ public boolean exists() { * Example of reading all bytes of the blob, if its generation matches the * {@link Blob#generation()} value, otherwise a {@link StorageException} is thrown. */ - // [TARGET content(BlobSourceOption...)] - public byte[] content() { - // [START content] - byte[] content = blob.content(BlobSourceOption.generationMatch()); - // [END content] + // [TARGET getContent(BlobSourceOption...)] + public byte[] getContent() { + // [START getContent] + byte[] content = blob.getContent(BlobSourceOption.generationMatch()); + // [END getContent] return content; } @@ -108,8 +108,8 @@ public Blob update() { // [START update] Map newMetadata = new HashMap<>(); newMetadata.put("key", "value"); - blob.toBuilder().metadata(null).build().update(); - Blob updatedBlob = blob.toBuilder().metadata(newMetadata).build().update(); + blob.toBuilder().setMetadata(null).build().update(); + Blob updatedBlob = blob.toBuilder().setMetadata(newMetadata).build().update(); // [END update] return updatedBlob; } @@ -140,7 +140,7 @@ public boolean delete() { public Blob copyToId(String bucketName, String blobName) { // [START copyToId] CopyWriter copyWriter = blob.copyTo(BlobId.of(bucketName, blobName)); - Blob copiedBlob = copyWriter.result(); + Blob copiedBlob = copyWriter.getResult(); // [END copyToId] return copiedBlob; } @@ -153,7 +153,7 @@ public Blob copyToId(String bucketName, String blobName) { public Blob copyToBucket(String bucketName) { // [START copyToBucket] CopyWriter copyWriter = blob.copyTo(bucketName); - Blob copiedBlob = copyWriter.result(); + Blob copiedBlob = copyWriter.getResult(); // [END copyToBucket] return copiedBlob; } @@ -167,7 +167,7 @@ public Blob copyToBucket(String bucketName) { public Blob copyToStrings(String bucketName, String blobName) { // [START copyToStrings] CopyWriter copyWriter = blob.copyTo(bucketName, blobName); - Blob copiedBlob = copyWriter.result(); + Blob copiedBlob = copyWriter.getResult(); // [END copyToStrings] return copiedBlob; } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/BucketSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/BucketSnippets.java index 4328aef09b22..eab4b3a1e788 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/BucketSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/BucketSnippets.java @@ -87,7 +87,7 @@ public Bucket reload() { // [TARGET update(BucketTargetOption...)] public Bucket update() { // [START update] - Bucket updatedBucket = bucket.toBuilder().versioningEnabled(true).build().update(); + Bucket updatedBucket = bucket.toBuilder().setVersioningEnabled(true).build().update(); // [END update] return updatedBucket; } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateAndListBucketsAndBlobs.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateAndListBucketsAndBlobs.java index 922afd7047c3..b34cf8b70895 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateAndListBucketsAndBlobs.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateAndListBucketsAndBlobs.java @@ -51,7 +51,7 @@ public static void main(String... args) { Blob blob = bucket.create("my_blob_name", "a simple blob".getBytes(UTF_8), "text/plain"); // Read the blob content from the server - String blobContent = new String(blob.content(), UTF_8); + String blobContent = new String(blob.getContent(), UTF_8); // List all your buckets Iterator bucketIterator = storage.list().iterateAll(); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateBlob.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateBlob.java index afe07b0e5206..b63989ce97b3 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateBlob.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateBlob.java @@ -38,7 +38,7 @@ public class CreateBlob { public static void main(String... args) { Storage storage = StorageOptions.defaultInstance().service(); BlobId blobId = BlobId.of("bucket", "blob_name"); - BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); + BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8)); } } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/StorageSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/StorageSnippets.java index 8cc262ea0a5c..fb6d8567a004 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/StorageSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/StorageSnippets.java @@ -99,7 +99,7 @@ public Bucket createBucket(String bucketName) { public Blob createBlob(String bucketName, String blobName) { // [START createBlob] BlobId blobId = BlobId.of(bucketName, blobName); - BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); + BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); Blob blob = storage.create(blobInfo); // [END createBlob] return blob; @@ -114,7 +114,7 @@ public Blob createBlob(String bucketName, String blobName) { public Blob createBlobFromByteArray(String bucketName, String blobName) { // [START createBlobFromByteArray] BlobId blobId = BlobId.of(bucketName, blobName); - BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); + BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); Blob blob = storage.create(blobInfo, "Hello, World!".getBytes(UTF_8)); // [END createBlobFromByteArray] return blob; @@ -130,7 +130,7 @@ public Blob createBlobFromInputStream(String bucketName, String blobName) { // [START createBlobFromInputStream] InputStream content = new ByteArrayInputStream("Hello, World!".getBytes(UTF_8)); BlobId blobId = BlobId.of(bucketName, blobName); - BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); + BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); Blob blob = storage.create(blobInfo, content); // [END createBlobFromInputStream] return blob; @@ -243,7 +243,7 @@ public Page listBlobsWithDirectoryAndPrefix(String bucketName, String dire // [VARIABLE "my_unique_bucket"] public Bucket updateBucket(String bucketName) { // [START updateBucket] - BucketInfo bucketInfo = BucketInfo.builder(bucketName).versioningEnabled(true).build(); + BucketInfo bucketInfo = BucketInfo.newBuilder(bucketName).setVersioningEnabled(true).build(); Bucket bucket = storage.update(bucketInfo); // [END updateBucket] return bucket; @@ -259,9 +259,9 @@ public Blob updateBlob(String bucketName, String blobName) { // [START updateBlob] Map newMetadata = new HashMap<>(); newMetadata.put("key", "value"); - storage.update(BlobInfo.builder(bucketName, blobName).metadata(null).build()); - Blob blob = storage.update(BlobInfo.builder(bucketName, blobName) - .metadata(newMetadata) + storage.update(BlobInfo.newBuilder(bucketName, blobName).setMetadata(null).build()); + Blob blob = storage.update(BlobInfo.newBuilder(bucketName, blobName) + .setMetadata(newMetadata) .build()); // [END updateBlob] return blob; @@ -277,7 +277,7 @@ public Blob updateBlob(String bucketName, String blobName) { public Blob updateBlobWithMetageneration(String bucketName, String blobName) { // [START updateBlobWithMetageneration] Blob blob = storage.get(bucketName, blobName); - BlobInfo updatedInfo = blob.toBuilder().contentType("text/plain").build(); + BlobInfo updatedInfo = blob.toBuilder().setContentType("text/plain").build(); storage.update(updatedInfo, BlobTargetOption.metagenerationMatch()); // [END updateBlobWithMetageneration] return blob; @@ -378,9 +378,9 @@ public Blob composeBlobs(String bucketName, String blobName, String sourceBlob1, String sourceBlob2) { // [START composeBlobs] BlobId blobId = BlobId.of(bucketName, blobName); - BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); - ComposeRequest request = ComposeRequest.builder() - .target(blobInfo) + BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); + ComposeRequest request = ComposeRequest.newBuilder() + .setTarget(blobInfo) .addSource(sourceBlob1) .addSource(sourceBlob2) .build(); @@ -398,11 +398,11 @@ public Blob composeBlobs(String bucketName, String blobName, String sourceBlob1, // [VARIABLE "copy_blob_name"] public Blob copyBlob(String bucketName, String blobName, String copyBlobName) { // [START copyBlob] - CopyRequest request = CopyRequest.builder() - .source(BlobId.of(bucketName, blobName)) - .target(BlobId.of(bucketName, copyBlobName)) + CopyRequest request = CopyRequest.newBuilder() + .setSource(BlobId.of(bucketName, blobName)) + .setTarget(BlobId.of(bucketName, copyBlobName)) .build(); - Blob blob = storage.copy(request).result(); + Blob blob = storage.copy(request).getResult(); // [END copyBlob] return blob; } @@ -416,15 +416,15 @@ public Blob copyBlob(String bucketName, String blobName, String copyBlobName) { // [VARIABLE "copy_blob_name"] public Blob copyBlobInChunks(String bucketName, String blobName, String copyBlobName) { // [START copyBlobInChunks] - CopyRequest request = CopyRequest.builder() - .source(BlobId.of(bucketName, blobName)) - .target(BlobId.of(bucketName, copyBlobName)) + CopyRequest request = CopyRequest.newBuilder() + .setSource(BlobId.of(bucketName, blobName)) + .setTarget(BlobId.of(bucketName, copyBlobName)) .build(); CopyWriter copyWriter = storage.copy(request); while (!copyWriter.isDone()) { copyWriter.copyChunk(); } - Blob blob = copyWriter.result(); + Blob blob = copyWriter.getResult(); // [END copyBlobInChunks] return blob; } @@ -483,7 +483,7 @@ public void error(StorageException exception) { // delete failed } }); - batch.update(BlobInfo.builder(secondBlob).contentType("text/plain").build()); + batch.update(BlobInfo.newBuilder(secondBlob).setContentType("text/plain").build()); StorageBatchResult result = batch.get(secondBlob); batch.submit(); Blob blob = result.get(); // returns get result or throws StorageException @@ -540,7 +540,7 @@ public void writer(String bucketName, String blobName) throws IOException { // [START writer] BlobId blobId = BlobId.of(bucketName, blobName); byte[] content = "Hello, World!".getBytes(UTF_8); - BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); + BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); try (WriteChannel writer = storage.writer(blobInfo)) { try { writer.write(ByteBuffer.wrap(content, 0, content.length)); @@ -560,7 +560,7 @@ public void writer(String bucketName, String blobName) throws IOException { // [VARIABLE "my_blob_name"] public URL signUrl(String bucketName, String blobName) { // [START signUrl] - URL signedUrl = storage.signUrl(BlobInfo.builder(bucketName, blobName).build(), 14, + URL signedUrl = storage.signUrl(BlobInfo.newBuilder(bucketName, blobName).build(), 14, TimeUnit.DAYS); // [END signUrl] return signedUrl; @@ -578,7 +578,7 @@ public URL signUrl(String bucketName, String blobName) { public URL signUrlWithSigner(String bucketName, String blobName, String keyPath) throws IOException { // [START signUrlWithSigner] - URL signedUrl = storage.signUrl(BlobInfo.builder(bucketName, blobName).build(), + URL signedUrl = storage.signUrl(BlobInfo.newBuilder(bucketName, blobName).build(), 14, TimeUnit.DAYS, SignUrlOption.signWith( AuthCredentials.createForJson(new FileInputStream(keyPath)))); // [END signUrlWithSigner] @@ -630,8 +630,8 @@ public List batchUpdate(String bucketName, String blobName1, String blobNa Blob firstBlob = storage.get(bucketName, blobName1); Blob secondBlob = storage.get(bucketName, blobName2); List updatedBlobs = storage.update( - firstBlob.toBuilder().contentType("text/plain").build(), - secondBlob.toBuilder().contentType("text/plain").build()); + firstBlob.toBuilder().setContentType("text/plain").build(), + secondBlob.toBuilder().setContentType("text/plain").build()); // [END batchUpdate] return updatedBlobs; } @@ -648,8 +648,8 @@ public List batchUpdateIterable(String bucketName, String blobName1, Strin Blob firstBlob = storage.get(bucketName, blobName1); Blob secondBlob = storage.get(bucketName, blobName2); List blobs = new LinkedList<>(); - blobs.add(firstBlob.toBuilder().contentType("text/plain").build()); - blobs.add(secondBlob.toBuilder().contentType("text/plain").build()); + blobs.add(firstBlob.toBuilder().setContentType("text/plain").build()); + blobs.add(secondBlob.toBuilder().setContentType("text/plain").build()); List updatedBlobs = storage.update(blobs); // [END batchUpdateIterable] return updatedBlobs; diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/UpdateBlob.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/UpdateBlob.java index c645ba1e4a54..ed081928f911 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/UpdateBlob.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/UpdateBlob.java @@ -43,7 +43,7 @@ public static void main(String... args) throws IOException { BlobId blobId = BlobId.of("bucket", "blob_name"); Blob blob = storage.get(blobId); if (blob != null) { - byte[] prevContent = blob.content(); + byte[] prevContent = blob.getContent(); System.out.println(new String(prevContent, UTF_8)); WritableByteChannel channel = blob.writer(); channel.write(ByteBuffer.wrap("Updated content".getBytes(UTF_8))); diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBlobSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBlobSnippets.java index 9fcfb2a4a416..9e998fb0038f 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBlobSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBlobSnippets.java @@ -69,9 +69,9 @@ public class ITBlobSnippets { @BeforeClass public static void beforeClass() { RemoteStorageHelper helper = RemoteStorageHelper.create(); - storage = helper.options().service(); + storage = helper.getOptions().service(); storage.create(BucketInfo.of(BUCKET)); - blob = storage.create(BlobInfo.builder(BUCKET, BLOB).build()); + blob = storage.create(BlobInfo.newBuilder(BUCKET, BLOB).build()); } @AfterClass @@ -88,7 +88,7 @@ public static void afterClass() throws ExecutionException, InterruptedException public void testBlob() throws IOException { BlobSnippets blobSnippets = new BlobSnippets(blob); assertTrue(blobSnippets.exists()); - assertArrayEquals(EMPTY_CONTENT, blobSnippets.content()); + assertArrayEquals(EMPTY_CONTENT, blobSnippets.getContent()); try { assertNotNull(blobSnippets.reload()); fail("Expected StorageException to be thrown"); @@ -96,7 +96,7 @@ public void testBlob() throws IOException { // expected } Blob updatedBlob = blobSnippets.update(); - assertEquals(ImmutableMap.of("key", "value"), updatedBlob.metadata()); + assertEquals(ImmutableMap.of("key", "value"), updatedBlob.getMetadata()); Blob copiedBlob = blobSnippets.copyToStrings(BUCKET, "copyBlob"); assertNotNull(copiedBlob); copiedBlob.delete(); @@ -122,11 +122,11 @@ public void testBlob() throws IOException { assertArrayEquals(CONTENT, readBytes); } assertFalse(blobSnippets.delete()); - blobSnippets = new BlobSnippets(storage.get(blob.bucket(), blob.name())); + blobSnippets = new BlobSnippets(storage.get(blob.getBucket(), blob.getName())); assertNull(blobSnippets.getAcl()); assertNotNull(blobSnippets.createAcl()); Acl updatedAcl = blobSnippets.updateAcl(); - assertEquals(Acl.Role.OWNER, updatedAcl.role()); + assertEquals(Acl.Role.OWNER, updatedAcl.getRole()); Set acls = Sets.newHashSet(blobSnippets.listAcls()); assertTrue(acls.contains(updatedAcl)); assertTrue(blobSnippets.deleteAcl()); diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBucketSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBucketSnippets.java index 87e8b40fbdff..8aa29bab769e 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBucketSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBucketSnippets.java @@ -66,7 +66,7 @@ public class ITBucketSnippets { @BeforeClass public static void beforeClass() { RemoteStorageHelper helper = RemoteStorageHelper.create(); - storage = helper.options().service(); + storage = helper.getOptions().service(); bucketSnippets = new BucketSnippets(storage.create(BucketInfo.of(BUCKET))); } @@ -104,19 +104,19 @@ public void testBucket() throws InterruptedException { assertTrue(blobSet.contains(blob2)); assertTrue(blobSet.contains(blob3)); assertTrue(blobSet.contains(blob4)); - blob1 = bucketSnippets.getBlob(BLOB1, blob1.generation()); - assertEquals(BLOB1, blob1.name()); + blob1 = bucketSnippets.getBlob(BLOB1, blob1.getGeneration()); + assertEquals(BLOB1, blob1.getName()); List blobs = bucketSnippets.getBlobFromStrings(BLOB2, BLOB3); - assertEquals(BLOB2, blobs.get(0).name()); - assertEquals(BLOB3, blobs.get(1).name()); + assertEquals(BLOB2, blobs.get(0).getName()); + assertEquals(BLOB3, blobs.get(1).getName()); blobs = bucketSnippets.getBlobFromStringIterable(BLOB3, BLOB4); - assertEquals(BLOB3, blobs.get(0).name()); - assertEquals(BLOB4, blobs.get(1).name()); + assertEquals(BLOB3, blobs.get(0).getName()); + assertEquals(BLOB4, blobs.get(1).getName()); // test ACLs assertNull(bucketSnippets.getAcl()); assertNotNull(bucketSnippets.createAcl()); Acl updatedAcl = bucketSnippets.updateAcl(); - assertEquals(Role.OWNER, updatedAcl.role()); + assertEquals(Role.OWNER, updatedAcl.getRole()); Set acls = Sets.newHashSet(bucketSnippets.listAcls()); assertTrue(acls.contains(updatedAcl)); assertTrue(bucketSnippets.deleteAcl()); @@ -125,7 +125,7 @@ public void testBucket() throws InterruptedException { assertNull(bucketSnippets.getDefaultAcl()); assertNotNull(bucketSnippets.createDefaultAcl()); updatedAcl = bucketSnippets.updateDefaultAcl(); - assertEquals(Role.OWNER, updatedAcl.role()); + assertEquals(Role.OWNER, updatedAcl.getRole()); acls = Sets.newHashSet(bucketSnippets.listDefaultAcls()); assertTrue(acls.contains(updatedAcl)); assertTrue(bucketSnippets.deleteDefaultAcl()); diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITStorageSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITStorageSnippets.java index fcb00fae6134..d454c911b09b 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITStorageSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITStorageSnippets.java @@ -74,7 +74,7 @@ public class ITStorageSnippets { @BeforeClass public static void beforeClass() { RemoteStorageHelper helper = RemoteStorageHelper.create(); - storage = helper.options().service(); + storage = helper.getOptions().service(); storageSnippets = new StorageSnippets(storage); storageSnippets.createBucket(BUCKET); } @@ -110,7 +110,7 @@ public void testBlob() throws InterruptedException { Set blobNames = new HashSet<>(); Iterator blobIterator = blobs.iterateAll(); while (blobIterator.hasNext()) { - blobNames.add(blobIterator.next().name()); + blobNames.add(blobIterator.next().getName()); } assertTrue(blobNames.contains(blobName)); assertTrue(blobNames.contains("directory/copy-blob")); @@ -137,7 +137,8 @@ public void testCreateCopyAndGetBlob() { } catch (StorageException ex) { // expected } - assertTrue(storageSnippets.deleteBlobFromIdWithGeneration(BUCKET, blobName, blob.generation())); + assertTrue( + storageSnippets.deleteBlobFromIdWithGeneration(BUCKET, blobName, blob.getGeneration())); copiedBlob.delete(); } @@ -147,7 +148,7 @@ public void testCreateBlobFromInputStream() { storageSnippets.createBlobFromInputStream(BUCKET, "test-create-blob-from-input-stream"); assertNotNull(blob); assertTrue(storageSnippets.deleteBlobFromIdWithGeneration( - BUCKET, "test-create-blob-from-input-stream", blob.generation())); + BUCKET, "test-create-blob-from-input-stream", blob.getGeneration())); } @Test @@ -165,7 +166,7 @@ public void testListBucketsWithSizeAndPrefix() throws InterruptedException { } Iterator bucketIterator = buckets.iterateAll(); while (bucketIterator.hasNext()) { - assertTrue(bucketIterator.next().name().startsWith(BUCKET)); + assertTrue(bucketIterator.next().getName().startsWith(BUCKET)); } } @@ -185,8 +186,8 @@ public void testComposeBlobs() { String blobName = "my_blob_name"; String sourceBlobName1 = "source_blob_1"; String sourceBlobName2 = "source_blob_2"; - BlobInfo blobInfo1 = BlobInfo.builder(BUCKET, sourceBlobName1).build(); - BlobInfo blobInfo2 = BlobInfo.builder(BUCKET, sourceBlobName2).build(); + BlobInfo blobInfo1 = BlobInfo.newBuilder(BUCKET, sourceBlobName1).build(); + BlobInfo blobInfo2 = BlobInfo.newBuilder(BUCKET, sourceBlobName2).build(); storage.create(blobInfo1); storage.create(blobInfo2); assertNotNull(storageSnippets.composeBlobs(BUCKET, blobName, sourceBlobName1, sourceBlobName2)); @@ -197,10 +198,11 @@ public void testReadWriteAndSignUrl() throws IOException { String blobName = "text-read-write-sign-url"; byte[] content = "Hello, World!".getBytes(UTF_8); Blob blob = storage.create( - BlobInfo.builder(BUCKET, blobName).build(), content); - assertArrayEquals(content, storageSnippets.readBlobFromId(BUCKET, blobName, blob.generation())); + BlobInfo.newBuilder(BUCKET, blobName).build(), content); assertArrayEquals(content, - storageSnippets.readBlobFromStringsWithGeneration(BUCKET, blobName, blob.generation())); + storageSnippets.readBlobFromId(BUCKET, blobName, blob.getGeneration())); + assertArrayEquals(content, + storageSnippets.readBlobFromStringsWithGeneration(BUCKET, blobName, blob.getGeneration())); storageSnippets.readerFromId(BUCKET, blobName); storageSnippets.readerFromStrings(BUCKET, blobName); storageSnippets.writer(BUCKET, blobName); @@ -225,16 +227,16 @@ public void testReadWriteAndSignUrl() throws IOException { public void testBatch() throws IOException { String blobName1 = "test-batch1"; String blobName2 = "test-batch2"; - storage.create(BlobInfo.builder(BUCKET, blobName1).build()); - storage.create(BlobInfo.builder(BUCKET, blobName2).build()); + storage.create(BlobInfo.newBuilder(BUCKET, blobName1).build()); + storage.create(BlobInfo.newBuilder(BUCKET, blobName2).build()); List blobs = storageSnippets.batchGet(BUCKET, blobName1, blobName2); - assertEquals(blobName1, blobs.get(0).name()); - assertEquals(blobName2, blobs.get(1).name()); + assertEquals(blobName1, blobs.get(0).getName()); + assertEquals(blobName2, blobs.get(1).getName()); blobs = storageSnippets.batchUpdate(BUCKET, blobName1, blobName2); - assertEquals(blobName1, blobs.get(0).name()); - assertEquals(blobName2, blobs.get(1).name()); - assertEquals("text/plain", blobs.get(0).contentType()); - assertEquals("text/plain", blobs.get(1).contentType()); + assertEquals(blobName1, blobs.get(0).getName()); + assertEquals(blobName2, blobs.get(1).getName()); + assertEquals("text/plain", blobs.get(0).getContentType()); + assertEquals("text/plain", blobs.get(1).getContentType()); assertNotNull(storageSnippets.batch(BUCKET, blobName1, blobName2)); List deleted = storageSnippets.batchDelete(BUCKET, blobName1, blobName2); assertFalse(deleted.get(0)); @@ -245,16 +247,16 @@ public void testBatch() throws IOException { public void testBatchIterable() throws IOException { String blobName1 = "test-batch-iterable1"; String blobName2 = "test-batch-iterable2"; - storage.create(BlobInfo.builder(BUCKET, blobName1).build()); - storage.create(BlobInfo.builder(BUCKET, blobName2).build()); + storage.create(BlobInfo.newBuilder(BUCKET, blobName1).build()); + storage.create(BlobInfo.newBuilder(BUCKET, blobName2).build()); List blobs = storageSnippets.batchGetIterable(BUCKET, blobName1, blobName2); - assertEquals(blobName1, blobs.get(0).name()); - assertEquals(blobName2, blobs.get(1).name()); + assertEquals(blobName1, blobs.get(0).getName()); + assertEquals(blobName2, blobs.get(1).getName()); blobs = storageSnippets.batchUpdateIterable(BUCKET, blobName1, blobName2); - assertEquals(blobName1, blobs.get(0).name()); - assertEquals(blobName2, blobs.get(1).name()); - assertEquals("text/plain", blobs.get(0).contentType()); - assertEquals("text/plain", blobs.get(1).contentType()); + assertEquals(blobName1, blobs.get(0).getName()); + assertEquals(blobName2, blobs.get(1).getName()); + assertEquals("text/plain", blobs.get(0).getContentType()); + assertEquals("text/plain", blobs.get(1).getContentType()); assertNotNull(storageSnippets.batch(BUCKET, blobName1, blobName2)); List deleted = storageSnippets.batchDeleteIterable(BUCKET, blobName1, blobName2); assertFalse(deleted.get(0)); @@ -267,7 +269,7 @@ public void testBucketAcl() { assertFalse(storageSnippets.deleteBucketAcl(BUCKET)); assertNotNull(storageSnippets.createBucketAcl(BUCKET)); Acl updatedAcl = storageSnippets.updateBucketAcl(BUCKET); - assertEquals(Acl.Role.OWNER, updatedAcl.role()); + assertEquals(Acl.Role.OWNER, updatedAcl.getRole()); Set acls = Sets.newHashSet(storageSnippets.listBucketAcls(BUCKET)); assertTrue(acls.contains(updatedAcl)); assertTrue(storageSnippets.deleteBucketAcl(BUCKET)); @@ -280,7 +282,7 @@ public void testDefaultBucketAcl() { assertFalse(storageSnippets.deleteDefaultBucketAcl(BUCKET)); assertNotNull(storageSnippets.createDefaultBucketAcl(BUCKET)); Acl updatedAcl = storageSnippets.updateDefaultBucketAcl(BUCKET); - assertEquals(Acl.Role.OWNER, updatedAcl.role()); + assertEquals(Acl.Role.OWNER, updatedAcl.getRole()); Set acls = Sets.newHashSet(storageSnippets.listDefaultBucketAcls(BUCKET)); assertTrue(acls.contains(updatedAcl)); assertTrue(storageSnippets.deleteDefaultBucketAcl(BUCKET)); @@ -291,17 +293,17 @@ public void testDefaultBucketAcl() { public void testBlobAcl() { String blobName = "test-blob-acl"; BlobId blobId = BlobId.of(BUCKET, "test-blob-acl"); - BlobInfo blob = BlobInfo.builder(blobId).build(); + BlobInfo blob = BlobInfo.newBuilder(blobId).build(); Blob createdBlob = storage.create(blob); - assertNull(storageSnippets.getBlobAcl(BUCKET, blobName, createdBlob.generation())); - assertNotNull(storageSnippets.createBlobAcl(BUCKET, blobName, createdBlob.generation())); - Acl updatedAcl = storageSnippets.updateBlobAcl(BUCKET, blobName, createdBlob.generation()); - assertEquals(Acl.Role.OWNER, updatedAcl.role()); - Set acls = - Sets.newHashSet(storageSnippets.listBlobAcls(BUCKET, blobName, createdBlob.generation())); + assertNull(storageSnippets.getBlobAcl(BUCKET, blobName, createdBlob.getGeneration())); + assertNotNull(storageSnippets.createBlobAcl(BUCKET, blobName, createdBlob.getGeneration())); + Acl updatedAcl = storageSnippets.updateBlobAcl(BUCKET, blobName, createdBlob.getGeneration()); + assertEquals(Acl.Role.OWNER, updatedAcl.getRole()); + Set acls = Sets.newHashSet( + storageSnippets.listBlobAcls(BUCKET, blobName, createdBlob.getGeneration())); assertTrue(acls.contains(updatedAcl)); - assertTrue(storageSnippets.deleteBlobAcl(BUCKET, blobName, createdBlob.generation())); - assertNull(storageSnippets.getBlobAcl(BUCKET, blobName, createdBlob.generation())); + assertTrue(storageSnippets.deleteBlobAcl(BUCKET, blobName, createdBlob.getGeneration())); + assertNull(storageSnippets.getBlobAcl(BUCKET, blobName, createdBlob.getGeneration())); // test non-existing blob String nonExistingBlob = "test-blob-acl"; assertNull(storageSnippets.getBlobAcl(BUCKET, nonExistingBlob, -1L)); diff --git a/google-cloud-storage/README.md b/google-cloud-storage/README.md index f5ac7c0968de..223ee4d34a14 100644 --- a/google-cloud-storage/README.md +++ b/google-cloud-storage/README.md @@ -112,7 +112,7 @@ At this point, you will be able to see your newly created bucket and blob on the Now that we have content uploaded to the server, we can see how to read data from the server. Add the following line to your program to get back the blob we uploaded. ```java -String blobContent = new String(blob.content(), UTF_8); +String blobContent = new String(blob.getContent(), UTF_8); ``` #### Listing buckets and contents of buckets diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/Acl.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/Acl.java index 9a0e60cac02a..365ce71a4021 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/Acl.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/Acl.java @@ -84,7 +84,15 @@ private Builder(Acl acl) { /** * Sets the entity for the ACL object. */ + @Deprecated public Builder entity(Entity entity) { + return setEntity(entity); + } + + /** + * Sets the entity for the ACL object. + */ + public Builder setEntity(Entity entity) { this.entity = entity; return this; } @@ -92,17 +100,25 @@ public Builder entity(Entity entity) { /** * Sets the role to associate to the {@code entity} object. */ + @Deprecated public Builder role(Role role) { + return setRole(role); + } + + /** + * Sets the role to associate to the {@code entity} object. + */ + public Builder setRole(Role role) { this.role = role; return this; } - Builder id(String id) { + Builder setId(String id) { this.id = id; return this; } - Builder etag(String etag) { + Builder setEtag(String etag) { this.etag = etag; return this; } @@ -137,14 +153,30 @@ public enum Type { /** * Returns the type of entity. */ + @Deprecated public Type type() { + return getType(); + } + + /** + * Returns the type of entity. + */ + public Type getType() { return type; } /** * Returns the entity's value. */ + @Deprecated protected String value() { + return getValue(); + } + + /** + * Returns the entity's value. + */ + protected String getValue() { return value; } @@ -171,7 +203,7 @@ public String toString() { } String toPb() { - return type.name().toLowerCase() + "-" + value(); + return type.name().toLowerCase() + "-" + getValue(); } static Entity fromPb(String entity) { @@ -219,8 +251,16 @@ public Domain(String domain) { /** * Returns the domain associated to this entity. */ + @Deprecated public String domain() { - return value(); + return getDomain(); + } + + /** + * Returns the domain associated to this entity. + */ + public String getDomain() { + return getValue(); } } @@ -243,8 +283,16 @@ public Group(String email) { /** * Returns the group email. */ + @Deprecated public String email() { - return value(); + return getEmail(); + } + + /** + * Returns the group email. + */ + public String getEmail() { + return getValue(); } } @@ -269,13 +317,21 @@ public User(String email) { /** * Returns the user email. */ + @Deprecated public String email() { - return value(); + return getEmail(); + } + + /** + * Returns the user email. + */ + public String getEmail() { + return getValue(); } @Override String toPb() { - switch (value()) { + switch (getValue()) { case ALL_AUTHENTICATED_USERS: return ALL_AUTHENTICATED_USERS; case ALL_USERS: @@ -324,14 +380,30 @@ public Project(ProjectRole projectRole, String projectId) { /** * Returns the role in the project for this entity. */ + @Deprecated public ProjectRole projectRole() { + return getProjectRole(); + } + + /** + * Returns the role in the project for this entity. + */ + public ProjectRole getProjectRole() { return projectRole; } /** * Returns the project id for this entity. */ + @Deprecated public String projectId() { + return getProjectId(); + } + + /** + * Returns the project id for this entity. + */ + public String getProjectId() { return projectId; } } @@ -346,7 +418,7 @@ public static final class RawEntity extends Entity { @Override String toPb() { - return value(); + return getValue(); } } @@ -360,21 +432,45 @@ private Acl(Builder builder) { /** * Returns the entity for this ACL object. */ + @Deprecated public Entity entity() { + return getEntity(); + } + + /** + * Returns the entity for this ACL object. + */ + public Entity getEntity() { return entity; } /** * Returns the role associated to the entity in this ACL object. */ + @Deprecated public Role role() { + return getRole(); + } + + /** + * Returns the role associated to the entity in this ACL object. + */ + public Role getRole() { return role; } /** * Returns the ID of the ACL entry. */ + @Deprecated public String id() { + return getId(); + } + + /** + * Returns the ID of the ACL entry. + */ + public String getId() { return id; } @@ -383,7 +479,17 @@ public String id() { * * @see Entity Tags */ + @Deprecated public String etag() { + return getEtag(); + } + + /** + * Returns HTTP 1.1 Entity tag for the ACL entry. + * + * @see Entity Tags + */ + public String getEtag() { return etag; } @@ -401,7 +507,7 @@ public Builder toBuilder() { * @param role the role to associate to the {@code entity} object */ public static Acl of(Entity entity, Role role) { - return builder(entity, role).build(); + return newBuilder(entity, role).build(); } /** @@ -410,7 +516,18 @@ public static Acl of(Entity entity, Role role) { * @param entity the entity for this ACL object * @param role the role to associate to the {@code entity} object */ + @Deprecated public static Builder builder(Entity entity, Role role) { + return newBuilder(entity, role); + } + + /** + * Returns a builder for {@code Acl} objects. + * + * @param entity the entity for this ACL object + * @param role the role to associate to the {@code entity} object + */ + public static Builder newBuilder(Entity entity, Role role) { return new Builder(entity, role); } @@ -446,37 +563,37 @@ public boolean equals(Object obj) { BucketAccessControl toBucketPb() { BucketAccessControl bucketPb = new BucketAccessControl(); - bucketPb.setEntity(entity().toString()); - bucketPb.setRole(role().toString()); - bucketPb.setId(id()); - bucketPb.setEtag(etag()); + bucketPb.setEntity(getEntity().toString()); + bucketPb.setRole(getRole().toString()); + bucketPb.setId(getId()); + bucketPb.setEtag(getEtag()); return bucketPb; } ObjectAccessControl toObjectPb() { ObjectAccessControl objectPb = new ObjectAccessControl(); - objectPb.setEntity(entity().toPb()); - objectPb.setRole(role().name()); - objectPb.setId(id()); - objectPb.setEtag(etag()); + objectPb.setEntity(getEntity().toPb()); + objectPb.setRole(getRole().name()); + objectPb.setId(getId()); + objectPb.setEtag(getEtag()); return objectPb; } static Acl fromPb(ObjectAccessControl objectAccessControl) { Role role = Role.valueOf(objectAccessControl.getRole()); Entity entity = Entity.fromPb(objectAccessControl.getEntity()); - return builder(entity, role) - .etag(objectAccessControl.getEtag()) - .id(objectAccessControl.getId()) + return newBuilder(entity, role) + .setEtag(objectAccessControl.getEtag()) + .setId(objectAccessControl.getId()) .build(); } static Acl fromPb(BucketAccessControl bucketAccessControl) { Role role = Role.valueOf(bucketAccessControl.getRole()); Entity entity = Entity.fromPb(bucketAccessControl.getEntity()); - return builder(entity, role) - .etag(bucketAccessControl.getEtag()) - .id(bucketAccessControl.getId()) + return newBuilder(entity, role) + .setEtag(bucketAccessControl.getEtag()) + .setId(bucketAccessControl.getId()) .build(); } } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/Blob.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/Blob.java index 9ca4b1ad633f..ebc38d6c24d9 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/Blob.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/Blob.java @@ -88,32 +88,32 @@ private BlobSourceOption(StorageRpc.Option rpcOption, Object value) { } private Storage.BlobSourceOption toSourceOptions(BlobInfo blobInfo) { - switch (rpcOption()) { + switch (getRpcOption()) { case IF_GENERATION_MATCH: - return Storage.BlobSourceOption.generationMatch(blobInfo.generation()); + return Storage.BlobSourceOption.generationMatch(blobInfo.getGeneration()); case IF_GENERATION_NOT_MATCH: - return Storage.BlobSourceOption.generationNotMatch(blobInfo.generation()); + return Storage.BlobSourceOption.generationNotMatch(blobInfo.getGeneration()); case IF_METAGENERATION_MATCH: - return Storage.BlobSourceOption.metagenerationMatch(blobInfo.metageneration()); + return Storage.BlobSourceOption.metagenerationMatch(blobInfo.getMetageneration()); case IF_METAGENERATION_NOT_MATCH: - return Storage.BlobSourceOption.metagenerationNotMatch(blobInfo.metageneration()); + return Storage.BlobSourceOption.metagenerationNotMatch(blobInfo.getMetageneration()); case CUSTOMER_SUPPLIED_KEY: - return Storage.BlobSourceOption.decryptionKey((String) value()); + return Storage.BlobSourceOption.decryptionKey((String) getValue()); default: throw new AssertionError("Unexpected enum value"); } } private Storage.BlobGetOption toGetOption(BlobInfo blobInfo) { - switch (rpcOption()) { + switch (getRpcOption()) { case IF_GENERATION_MATCH: - return Storage.BlobGetOption.generationMatch(blobInfo.generation()); + return Storage.BlobGetOption.generationMatch(blobInfo.getGeneration()); case IF_GENERATION_NOT_MATCH: - return Storage.BlobGetOption.generationNotMatch(blobInfo.generation()); + return Storage.BlobGetOption.generationNotMatch(blobInfo.getGeneration()); case IF_METAGENERATION_MATCH: - return Storage.BlobGetOption.metagenerationMatch(blobInfo.metageneration()); + return Storage.BlobGetOption.metagenerationMatch(blobInfo.getMetageneration()); case IF_METAGENERATION_NOT_MATCH: - return Storage.BlobGetOption.metagenerationNotMatch(blobInfo.metageneration()); + return Storage.BlobGetOption.metagenerationNotMatch(blobInfo.getMetageneration()); default: throw new AssertionError("Unexpected enum value"); } @@ -199,145 +199,204 @@ public static class Builder extends BlobInfo.Builder { private final BlobInfo.BuilderImpl infoBuilder; Builder(Blob blob) { - this.storage = blob.storage(); + this.storage = blob.getStorage(); this.infoBuilder = new BlobInfo.BuilderImpl(blob); } @Override + @Deprecated public Builder blobId(BlobId blobId) { - infoBuilder.blobId(blobId); + return setBlobId(blobId); + } + + @Override + public Builder setBlobId(BlobId blobId) { + infoBuilder.setBlobId(blobId); return this; } @Override - Builder generatedId(String generatedId) { - infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + infoBuilder.setGeneratedId(generatedId); return this; } @Override public Builder contentType(String contentType) { - infoBuilder.contentType(contentType); + return setContentType(contentType); + } + + @Override + public Builder setContentType(String contentType) { + infoBuilder.setContentType(contentType); return this; } @Override + @Deprecated public Builder contentDisposition(String contentDisposition) { - infoBuilder.contentDisposition(contentDisposition); + return setContentDisposition(contentDisposition); + } + + @Override + public Builder setContentDisposition(String contentDisposition) { + infoBuilder.setContentDisposition(contentDisposition); return this; } @Override + @Deprecated public Builder contentLanguage(String contentLanguage) { - infoBuilder.contentLanguage(contentLanguage); + return setContentLanguage(contentLanguage); + } + + @Override + public Builder setContentLanguage(String contentLanguage) { + infoBuilder.setContentLanguage(contentLanguage); return this; } @Override + @Deprecated public Builder contentEncoding(String contentEncoding) { - infoBuilder.contentEncoding(contentEncoding); + return setContentEncoding(contentEncoding); + } + + @Override + public Builder setContentEncoding(String contentEncoding) { + infoBuilder.setContentEncoding(contentEncoding); return this; } @Override - Builder componentCount(Integer componentCount) { - infoBuilder.componentCount(componentCount); + Builder setComponentCount(Integer componentCount) { + infoBuilder.setComponentCount(componentCount); return this; } @Override + @Deprecated public Builder cacheControl(String cacheControl) { - infoBuilder.cacheControl(cacheControl); + return setCacheControl(cacheControl); + } + + @Override + public Builder setCacheControl(String cacheControl) { + infoBuilder.setCacheControl(cacheControl); return this; } @Override + @Deprecated public Builder acl(List acl) { - infoBuilder.acl(acl); + return setAcl(acl); + } + + @Override + public Builder setAcl(List acl) { + infoBuilder.setAcl(acl); return this; } @Override - Builder owner(Entity owner) { - infoBuilder.owner(owner); + Builder setOwner(Entity owner) { + infoBuilder.setOwner(owner); return this; } @Override - Builder size(Long size) { - infoBuilder.size(size); + Builder setSize(Long size) { + infoBuilder.setSize(size); return this; } @Override - Builder etag(String etag) { - infoBuilder.etag(etag); + Builder setEtag(String etag) { + infoBuilder.setEtag(etag); return this; } @Override - Builder selfLink(String selfLink) { - infoBuilder.selfLink(selfLink); + Builder setSelfLink(String selfLink) { + infoBuilder.setSelfLink(selfLink); return this; } @Override + @Deprecated public Builder md5(String md5) { - infoBuilder.md5(md5); + return setMd5(md5); + } + + @Override + public Builder setMd5(String md5) { + infoBuilder.setMd5(md5); return this; } @Override + @Deprecated public Builder crc32c(String crc32c) { - infoBuilder.crc32c(crc32c); + return setCrc32c(crc32c); + } + + @Override + public Builder setCrc32c(String crc32c) { + infoBuilder.setCrc32c(crc32c); return this; } @Override - Builder mediaLink(String mediaLink) { - infoBuilder.mediaLink(mediaLink); + Builder setMediaLink(String mediaLink) { + infoBuilder.setMediaLink(mediaLink); return this; } @Override + @Deprecated public Builder metadata(Map metadata) { - infoBuilder.metadata(metadata); + return setMetadata(metadata); + } + + @Override + public Builder setMetadata(Map metadata) { + infoBuilder.setMetadata(metadata); return this; } @Override - Builder metageneration(Long metageneration) { - infoBuilder.metageneration(metageneration); + Builder setMetageneration(Long metageneration) { + infoBuilder.setMetageneration(metageneration); return this; } @Override - Builder deleteTime(Long deleteTime) { - infoBuilder.deleteTime(deleteTime); + Builder setDeleteTime(Long deleteTime) { + infoBuilder.setDeleteTime(deleteTime); return this; } @Override - Builder updateTime(Long updateTime) { - infoBuilder.updateTime(updateTime); + Builder setUpdateTime(Long updateTime) { + infoBuilder.setUpdateTime(updateTime); return this; } @Override - Builder createTime(Long createTime) { - infoBuilder.createTime(createTime); + Builder setCreateTime(Long createTime) { + infoBuilder.setCreateTime(createTime); return this; } @Override - Builder isDirectory(boolean isDirectory) { - infoBuilder.isDirectory(isDirectory); + Builder setIsDirectory(boolean isDirectory) { + infoBuilder.setIsDirectory(isDirectory); return this; } @Override - Builder customerEncryption(CustomerEncryption customerEncryption) { - infoBuilder.customerEncryption(customerEncryption); + Builder setCustomerEncryption(CustomerEncryption customerEncryption) { + infoBuilder.setCustomerEncryption(customerEncryption); return this; } @@ -374,7 +433,18 @@ public boolean exists(BlobSourceOption... options) { int length = options.length; Storage.BlobGetOption[] getOptions = Arrays.copyOf(toGetOptions(this, options), length + 1); getOptions[length] = Storage.BlobGetOption.fields(); - return storage.get(blobId(), getOptions) != null; + return storage.get(getBlobId(), getOptions) != null; + } + + /** + * Returns this blob's content. + * + * @param options blob read options + * @throws StorageException upon failure + */ + @Deprecated + public byte[] content(BlobSourceOption... options) { + return storage.readAllBytes(getBlobId(), toSourceOptions(this, options)); } /** @@ -383,14 +453,14 @@ public boolean exists(BlobSourceOption... options) { *

Example of reading all bytes of the blob, if its generation matches the * {@link Blob#generation()} value, otherwise a {@link StorageException} is thrown. *

 {@code
-   * byte[] content = blob.content(BlobSourceOption.generationMatch());
+   * byte[] content = blob.getContent(BlobSourceOption.generationMatch());
    * }
* * @param options blob read options * @throws StorageException upon failure */ - public byte[] content(BlobSourceOption... options) { - return storage.readAllBytes(blobId(), toSourceOptions(this, options)); + public byte[] getContent(BlobSourceOption... options) { + return storage.readAllBytes(getBlobId(), toSourceOptions(this, options)); } /** @@ -410,7 +480,7 @@ public byte[] content(BlobSourceOption... options) { * @throws StorageException upon failure */ public Blob reload(BlobSourceOption... options) { - return storage.get(blobId(), toGetOptions(this, options)); + return storage.get(getBlobId(), toGetOptions(this, options)); } /** @@ -430,8 +500,8 @@ public Blob reload(BlobSourceOption... options) { *
 {@code
    * Map newMetadata = new HashMap<>();
    * newMetadata.put("key", "value");
-   * blob.toBuilder().metadata(null).build().update();
-   * Blob updatedBlob = blob.toBuilder().metadata(newMetadata).build().update();
+   * blob.toBuilder().setMetadata(null).build().update();
+   * Blob updatedBlob = blob.toBuilder().setMetadata(newMetadata).build().update();
    * }
* * @param options update options @@ -461,7 +531,7 @@ public Blob update(BlobTargetOption... options) { * @throws StorageException upon failure */ public boolean delete(BlobSourceOption... options) { - return storage.delete(blobId(), toSourceOptions(this, options)); + return storage.delete(getBlobId(), toSourceOptions(this, options)); } /** @@ -473,7 +543,7 @@ public boolean delete(BlobSourceOption... options) { * String bucketName = "my_unique_bucket"; * String blobName = "copy_blob_name"; * CopyWriter copyWriter = blob.copyTo(BlobId.of(bucketName, blobName)); - * Blob copiedBlob = copyWriter.result(); + * Blob copiedBlob = copyWriter.getResult(); * }
* * @param targetBlob target blob's id @@ -483,10 +553,10 @@ public boolean delete(BlobSourceOption... options) { * @throws StorageException upon failure */ public CopyWriter copyTo(BlobId targetBlob, BlobSourceOption... options) { - CopyRequest copyRequest = CopyRequest.builder() - .source(bucket(), name()) - .sourceOptions(toSourceOptions(this, options)) - .target(targetBlob) + CopyRequest copyRequest = CopyRequest.newBuilder() + .setSource(getBucket(), getName()) + .setSourceOptions(toSourceOptions(this, options)) + .setTarget(targetBlob) .build(); return storage.copy(copyRequest); } @@ -499,7 +569,7 @@ public CopyWriter copyTo(BlobId targetBlob, BlobSourceOption... options) { *
 {@code
    * String bucketName = "my_unique_bucket";
    * CopyWriter copyWriter = blob.copyTo(bucketName);
-   * Blob copiedBlob = copyWriter.result();
+   * Blob copiedBlob = copyWriter.getResult();
    * }
* * @param targetBucket target bucket's name @@ -509,7 +579,7 @@ public CopyWriter copyTo(BlobId targetBlob, BlobSourceOption... options) { * @throws StorageException upon failure */ public CopyWriter copyTo(String targetBucket, BlobSourceOption... options) { - return copyTo(targetBucket, name(), options); + return copyTo(targetBucket, getName(), options); } /** @@ -521,7 +591,7 @@ public CopyWriter copyTo(String targetBucket, BlobSourceOption... options) { * String bucketName = "my_unique_bucket"; * String blobName = "copy_blob_name"; * CopyWriter copyWriter = blob.copyTo(bucketName, blobName); - * Blob copiedBlob = copyWriter.result(); + * Blob copiedBlob = copyWriter.getResult(); * }
* * @param targetBucket target bucket's name @@ -554,7 +624,7 @@ public CopyWriter copyTo(String targetBucket, String targetBlob, BlobSourceOptio * @throws StorageException upon failure */ public ReadChannel reader(BlobSourceOption... options) { - return storage.reader(blobId(), toSourceOptions(this, options)); + return storage.reader(getBlobId(), toSourceOptions(this, options)); } /** @@ -647,7 +717,7 @@ public URL signUrl(long duration, TimeUnit unit, SignUrlOption... options) { * @throws StorageException upon failure */ public Acl getAcl(Entity entity) { - return storage.getAcl(blobId(), entity); + return storage.getAcl(getBlobId(), entity); } /** @@ -667,7 +737,7 @@ public Acl getAcl(Entity entity) { * @throws StorageException upon failure */ public boolean deleteAcl(Entity entity) { - return storage.deleteAcl(blobId(), entity); + return storage.deleteAcl(getBlobId(), entity); } /** @@ -681,7 +751,7 @@ public boolean deleteAcl(Entity entity) { * @throws StorageException upon failure */ public Acl createAcl(Acl acl) { - return storage.createAcl(blobId(), acl); + return storage.createAcl(getBlobId(), acl); } /** @@ -695,7 +765,7 @@ public Acl createAcl(Acl acl) { * @throws StorageException upon failure */ public Acl updateAcl(Acl acl) { - return storage.updateAcl(blobId(), acl); + return storage.updateAcl(getBlobId(), acl); } /** @@ -712,13 +782,21 @@ public Acl updateAcl(Acl acl) { * @throws StorageException upon failure */ public List listAcls() { - return storage.listAcls(blobId()); + return storage.listAcls(getBlobId()); } /** * Returns the blob's {@code Storage} object used to issue requests. */ + @Deprecated public Storage storage() { + return getStorage(); + } + + /** + * Returns the blob's {@code Storage} object used to issue requests. + */ + public Storage getStorage() { return storage; } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobId.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobId.java index 88664e191f84..f24e5ea2a4ed 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobId.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobId.java @@ -45,30 +45,54 @@ private BlobId(String bucket, String name, Long generation) { /** * Returns the name of the bucket containing the blob. */ + @Deprecated public String bucket() { + return getBucket(); + } + + /** + * Returns the name of the bucket containing the blob. + */ + public String getBucket() { return bucket; } /** * Returns the name of the blob. */ + @Deprecated public String name() { + return getName(); + } + + /** + * Returns the name of the blob. + */ + public String getName() { return name; } /** * Returns blob's data generation. Used for versioning. */ + @Deprecated public Long generation() { + return getGeneration(); + } + + /** + * Returns blob's data generation. Used for versioning. + */ + public Long getGeneration() { return generation; } @Override public String toString() { return MoreObjects.toStringHelper(this) - .add("bucket", bucket()) - .add("name", name()) - .add("generation", generation()) + .add("bucket", getBucket()) + .add("name", getName()) + .add("generation", getGeneration()) .toString(); } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobInfo.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobInfo.java index 149e5d02e95d..150a11d6793b 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobInfo.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobInfo.java @@ -112,22 +112,38 @@ public static class CustomerEncryption implements Serializable { /** * Returns the algorithm used to encrypt the blob. */ + @Deprecated public String encryptionAlgorithm() { + return getEncryptionAlgorithm(); + } + + /** + * Returns the algorithm used to encrypt the blob. + */ + public String getEncryptionAlgorithm() { return encryptionAlgorithm; } /** * Returns the SHA256 hash of the encryption key. */ + @Deprecated public String keySha256() { + return getKeySha256(); + } + + /** + * Returns the SHA256 hash of the encryption key. + */ + public String getKeySha256() { return keySha256; } @Override public String toString() { return MoreObjects.toStringHelper(this) - .add("encryptionAlgorithm", encryptionAlgorithm()) - .add("keySha256", keySha256()) + .add("encryptionAlgorithm", getEncryptionAlgorithm()) + .add("keySha256", getKeySha256()) .toString(); } @@ -164,47 +180,93 @@ public abstract static class Builder { /** * Sets the blob identity. */ + @Deprecated public abstract Builder blobId(BlobId blobId); - abstract Builder generatedId(String generatedId); + /** + * Sets the blob identity. + */ + public abstract Builder setBlobId(BlobId blobId); + + abstract Builder setGeneratedId(String generatedId); /** * Sets the blob's data content type. * * @see Content-Type */ + @Deprecated public abstract Builder contentType(String contentType); + /** + * Sets the blob's data content type. + * + * @see Content-Type + */ + public abstract Builder setContentType(String contentType); + /** * Sets the blob's data content disposition. * * @see Content-Disposition */ + @Deprecated public abstract Builder contentDisposition(String contentDisposition); + /** + * Sets the blob's data content disposition. + * + * @see Content-Disposition + */ + public abstract Builder setContentDisposition(String contentDisposition); + /** * Sets the blob's data content language. * * @see Content-Language */ + @Deprecated public abstract Builder contentLanguage(String contentLanguage); + /** + * Sets the blob's data content language. + * + * @see Content-Language + */ + public abstract Builder setContentLanguage(String contentLanguage); + /** * Sets the blob's data content encoding. * * @see Content-Encoding */ + @Deprecated public abstract Builder contentEncoding(String contentEncoding); - abstract Builder componentCount(Integer componentCount); + /** + * Sets the blob's data content encoding. + * + * @see Content-Encoding + */ + public abstract Builder setContentEncoding(String contentEncoding); + + abstract Builder setComponentCount(Integer componentCount); /** * Sets the blob's data cache control. * * @see Cache-Control */ + @Deprecated public abstract Builder cacheControl(String cacheControl); + /** + * Sets the blob's data cache control. + * + * @see Cache-Control + */ + public abstract Builder setCacheControl(String cacheControl); + /** * Sets the blob's access control configuration. * @@ -212,15 +274,25 @@ public abstract static class Builder { * href="https://cloud.google.com/storage/docs/access-control#About-Access-Control-Lists"> * About Access Control Lists */ + @Deprecated public abstract Builder acl(List acl); - abstract Builder owner(Acl.Entity owner); + /** + * Sets the blob's access control configuration. + * + * @see + * About Access Control Lists + */ + public abstract Builder setAcl(List acl); + + abstract Builder setOwner(Acl.Entity owner); - abstract Builder size(Long size); + abstract Builder setSize(Long size); - abstract Builder etag(String etag); + abstract Builder setEtag(String etag); - abstract Builder selfLink(String selfLink); + abstract Builder setSelfLink(String selfLink); /** * Sets the MD5 hash of blob's data. MD5 value must be encoded in base64. @@ -228,8 +300,17 @@ public abstract static class Builder { * @see * Hashes and ETags: Best Practices */ + @Deprecated public abstract Builder md5(String md5); + /** + * Sets the MD5 hash of blob's data. MD5 value must be encoded in base64. + * + * @see + * Hashes and ETags: Best Practices + */ + public abstract Builder setMd5(String md5); + /** * Sets the CRC32C checksum of blob's data as described in * RFC 4960, Appendix B; encoded in @@ -238,26 +319,43 @@ public abstract static class Builder { * @see * Hashes and ETags: Best Practices */ + @Deprecated public abstract Builder crc32c(String crc32c); - abstract Builder mediaLink(String mediaLink); + /** + * Sets the CRC32C checksum of blob's data as described in + * RFC 4960, Appendix B; encoded in + * base64 in big-endian order. + * + * @see + * Hashes and ETags: Best Practices + */ + public abstract Builder setCrc32c(String crc32c); + + abstract Builder setMediaLink(String mediaLink); /** * Sets the blob's user provided metadata. */ + @Deprecated public abstract Builder metadata(Map metadata); - abstract Builder metageneration(Long metageneration); + /** + * Sets the blob's user provided metadata. + */ + public abstract Builder setMetadata(Map metadata); - abstract Builder deleteTime(Long deleteTime); + abstract Builder setMetageneration(Long metageneration); - abstract Builder updateTime(Long updateTime); + abstract Builder setDeleteTime(Long deleteTime); - abstract Builder createTime(Long createTime); + abstract Builder setUpdateTime(Long updateTime); - abstract Builder isDirectory(boolean isDirectory); + abstract Builder setCreateTime(Long createTime); - abstract Builder customerEncryption(CustomerEncryption customerEncryption); + abstract Builder setIsDirectory(boolean isDirectory); + + abstract Builder setCustomerEncryption(CustomerEncryption customerEncryption); /** * Creates a {@code BlobInfo} object. @@ -322,140 +420,200 @@ static final class BuilderImpl extends Builder { } @Override + @Deprecated public Builder blobId(BlobId blobId) { + return setBlobId(blobId); + } + + @Override + public Builder setBlobId(BlobId blobId) { this.blobId = checkNotNull(blobId); return this; } @Override - Builder generatedId(String generatedId) { + Builder setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } @Override + @Deprecated public Builder contentType(String contentType) { + return setContentType(contentType); + } + + @Override + public Builder setContentType(String contentType) { this.contentType = firstNonNull(contentType, Data.nullOf(String.class)); return this; } @Override + @Deprecated public Builder contentDisposition(String contentDisposition) { + return setContentDisposition(contentDisposition); + } + + @Override + public Builder setContentDisposition(String contentDisposition) { this.contentDisposition = firstNonNull(contentDisposition, Data.nullOf(String.class)); return this; } @Override + @Deprecated public Builder contentLanguage(String contentLanguage) { + return setContentLanguage(contentLanguage); + } + + @Override + public Builder setContentLanguage(String contentLanguage) { this.contentLanguage = firstNonNull(contentLanguage, Data.nullOf(String.class)); return this; } @Override + @Deprecated public Builder contentEncoding(String contentEncoding) { + return setContentEncoding(contentEncoding); + } + + @Override + public Builder setContentEncoding(String contentEncoding) { this.contentEncoding = firstNonNull(contentEncoding, Data.nullOf(String.class)); return this; } @Override - Builder componentCount(Integer componentCount) { + Builder setComponentCount(Integer componentCount) { this.componentCount = componentCount; return this; } @Override + @Deprecated public Builder cacheControl(String cacheControl) { + return setCacheControl(cacheControl); + } + + @Override + public Builder setCacheControl(String cacheControl) { this.cacheControl = firstNonNull(cacheControl, Data.nullOf(String.class)); return this; } @Override + @Deprecated public Builder acl(List acl) { + return setAcl(acl); + } + + @Override + public Builder setAcl(List acl) { this.acl = acl != null ? ImmutableList.copyOf(acl) : null; return this; } @Override - Builder owner(Acl.Entity owner) { + Builder setOwner(Acl.Entity owner) { this.owner = owner; return this; } @Override - Builder size(Long size) { + Builder setSize(Long size) { this.size = size; return this; } @Override - Builder etag(String etag) { + Builder setEtag(String etag) { this.etag = etag; return this; } @Override - Builder selfLink(String selfLink) { + Builder setSelfLink(String selfLink) { this.selfLink = selfLink; return this; } @Override + @Deprecated public Builder md5(String md5) { + return setMd5(md5); + } + + @Override + public Builder setMd5(String md5) { this.md5 = firstNonNull(md5, Data.nullOf(String.class)); return this; } @Override + @Deprecated public Builder crc32c(String crc32c) { + return setCrc32c(crc32c); + } + + @Override + public Builder setCrc32c(String crc32c) { this.crc32c = firstNonNull(crc32c, Data.nullOf(String.class)); return this; } @Override - Builder mediaLink(String mediaLink) { + Builder setMediaLink(String mediaLink) { this.mediaLink = mediaLink; return this; } @Override + @Deprecated public Builder metadata(Map metadata) { + return setMetadata(metadata); + } + + @Override + public Builder setMetadata(Map metadata) { this.metadata = metadata != null ? new HashMap<>(metadata) : Data.>nullOf(ImmutableEmptyMap.class); return this; } @Override - Builder metageneration(Long metageneration) { + Builder setMetageneration(Long metageneration) { this.metageneration = metageneration; return this; } @Override - Builder deleteTime(Long deleteTime) { + Builder setDeleteTime(Long deleteTime) { this.deleteTime = deleteTime; return this; } @Override - Builder updateTime(Long updateTime) { + Builder setUpdateTime(Long updateTime) { this.updateTime = updateTime; return this; } @Override - Builder createTime(Long createTime) { + Builder setCreateTime(Long createTime) { this.createTime = createTime; return this; } @Override - Builder isDirectory(boolean isDirectory) { + Builder setIsDirectory(boolean isDirectory) { this.isDirectory = isDirectory; return this; } @Override - Builder customerEncryption(CustomerEncryption customerEncryption) { + Builder setCustomerEncryption(CustomerEncryption customerEncryption) { this.customerEncryption = customerEncryption; return this; } @@ -496,29 +654,61 @@ public BlobInfo build() { /** * Returns the blob's identity. */ + @Deprecated public BlobId blobId() { + return getBlobId(); + } + + /** + * Returns the blob's identity. + */ + public BlobId getBlobId() { return blobId; } /** * Returns the name of the containing bucket. */ + @Deprecated public String bucket() { - return blobId().bucket(); + return getBucket(); + } + + /** + * Returns the name of the containing bucket. + */ + public String getBucket() { + return getBlobId().getBucket(); } /** * Returns the service-generated for the blob. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated for the blob. + */ + public String getGeneratedId() { return generatedId; } /** * Returns the blob's name. */ + @Deprecated public String name() { - return blobId().name(); + return getName(); + } + + /** + * Returns the blob's name. + */ + public String getName() { + return getBlobId().getName(); } /** @@ -526,7 +716,17 @@ public String name() { * * @see Cache-Control */ + @Deprecated public String cacheControl() { + return getCacheControl(); + } + + /** + * Returns the blob's data cache control. + * + * @see Cache-Control + */ + public String getCacheControl() { return Data.isNull(cacheControl) ? null : cacheControl; } @@ -536,14 +736,33 @@ public String cacheControl() { * @see * About Access Control Lists */ + @Deprecated public List acl() { + return getAcl(); + } + + /** + * Returns the blob's access control configuration. + * + * @see + * About Access Control Lists + */ + public List getAcl() { return acl; } /** * Returns the blob's owner. This will always be the uploader of the blob. */ + @Deprecated public Acl.Entity owner() { + return getOwner(); + } + + /** + * Returns the blob's owner. This will always be the uploader of the blob. + */ + public Acl.Entity getOwner() { return owner; } @@ -552,7 +771,17 @@ public Acl.Entity owner() { * * @see Content-Length */ + @Deprecated public Long size() { + return getSize(); + } + + /** + * Returns the content length of the data in bytes. + * + * @see Content-Length + */ + public Long getSize() { return size; } @@ -561,7 +790,17 @@ public Long size() { * * @see Content-Type */ + @Deprecated public String contentType() { + return getContentType(); + } + + /** + * Returns the blob's data content type. + * + * @see Content-Type + */ + public String getContentType() { return Data.isNull(contentType) ? null : contentType; } @@ -570,7 +809,17 @@ public String contentType() { * * @see Content-Encoding */ + @Deprecated public String contentEncoding() { + return getContentEncoding(); + } + + /** + * Returns the blob's data content encoding. + * + * @see Content-Encoding + */ + public String getContentEncoding() { return Data.isNull(contentEncoding) ? null : contentEncoding; } @@ -579,7 +828,17 @@ public String contentEncoding() { * * @see Content-Disposition */ + @Deprecated public String contentDisposition() { + return getContentDisposition(); + } + + /** + * Returns the blob's data content disposition. + * + * @see Content-Disposition + */ + public String getContentDisposition() { return Data.isNull(contentDisposition) ? null : contentDisposition; } @@ -588,7 +847,17 @@ public String contentDisposition() { * * @see Content-Language */ + @Deprecated public String contentLanguage() { + return getContentLanguage(); + } + + /** + * Returns the blob's data content language. + * + * @see Content-Language + */ + public String getContentLanguage() { return Data.isNull(contentLanguage) ? null : contentLanguage; } @@ -601,7 +870,21 @@ public String contentLanguage() { * @see Component Count * Property */ + @Deprecated public Integer componentCount() { + return getComponentCount(); + } + + /** + * Returns the number of components that make up this blob. Components are accumulated through + * the {@link Storage#compose(Storage.ComposeRequest)} operation and are limited to a count of + * 1024, counting 1 for each non-composite component blob and componentCount for each composite + * component blob. This value is set only for composite blobs. + * + * @see Component Count + * Property + */ + public Integer getComponentCount() { return componentCount; } @@ -610,14 +893,32 @@ public Integer componentCount() { * * @see Entity Tags */ + @Deprecated public String etag() { + return getEtag(); + } + + /** + * Returns HTTP 1.1 Entity tag for the blob. + * + * @see Entity Tags + */ + public String getEtag() { return etag; } /** * Returns the URI of this blob as a string. */ + @Deprecated public String selfLink() { + return getSelfLink(); + } + + /** + * Returns the URI of this blob as a string. + */ + public String getSelfLink() { return selfLink; } @@ -627,7 +928,18 @@ public String selfLink() { * @see * Hashes and ETags: Best Practices */ + @Deprecated public String md5() { + return getMd5(); + } + + /** + * Returns the MD5 hash of blob's data encoded in base64. + * + * @see + * Hashes and ETags: Best Practices + */ + public String getMd5() { return Data.isNull(md5) ? null : md5; } @@ -639,29 +951,66 @@ public String md5() { * @see * Hashes and ETags: Best Practices */ + @Deprecated public String crc32c() { + return getCrc32c(); + } + + /** + * Returns the CRC32C checksum of blob's data as described in + * RFC 4960, Appendix B; encoded in + * base64 in big-endian order. + * + * @see + * Hashes and ETags: Best Practices + */ + public String getCrc32c() { return Data.isNull(crc32c) ? null : crc32c; } /** * Returns the blob's media download link. */ + @Deprecated public String mediaLink() { + return getMediaLink(); + } + + /** + * Returns the blob's media download link. + */ + public String getMediaLink() { return mediaLink; } /** * Returns blob's user provided metadata. */ + @Deprecated public Map metadata() { + return getMetadata(); + } + + /** + * Returns blob's user provided metadata. + */ + public Map getMetadata() { return metadata == null || Data.isNull(metadata) ? null : Collections.unmodifiableMap(metadata); } /** * Returns blob's data generation. Used for blob versioning. */ + @Deprecated public Long generation() { - return blobId().generation(); + return getGeneration(); + } + + /** + * Returns blob's data generation. Used for blob versioning. + */ + public Long getGeneration() { + return getBlobId().getGeneration(); } /** @@ -669,28 +1018,62 @@ public Long generation() { * A metageneration number is only meaningful in the context of a particular generation of a * particular blob. */ + @Deprecated public Long metageneration() { + return getMetageneration(); + } + + /** + * Returns blob's metageneration. Used for preconditions and for detecting changes in metadata. + * A metageneration number is only meaningful in the context of a particular generation of a + * particular blob. + */ + public Long getMetageneration() { return metageneration; } /** * Returns the deletion time of the blob. */ + @Deprecated public Long deleteTime() { + return getDeleteTime(); + } + + /** + * Returns the deletion time of the blob. + */ + public Long getDeleteTime() { return deleteTime; } /** * Returns the last modification time of the blob's metadata. */ + @Deprecated public Long updateTime() { + return getUpdateTime(); + } + + /** + * Returns the last modification time of the blob's metadata. + */ + public Long getUpdateTime() { return updateTime; } /** * Returns the creation time of the blob. */ + @Deprecated public Long createTime() { + return getCreateTime(); + } + + /** + * Returns the creation time of the blob. + */ + public Long getCreateTime() { return createTime; } @@ -710,7 +1093,16 @@ public boolean isDirectory() { * Returns information on the customer-supplied encryption key, if the blob is encrypted using * such a key. */ + @Deprecated public CustomerEncryption customerEncryption() { + return getCustomerEncryption(); + } + + /** + * Returns information on the customer-supplied encryption key, if the blob is encrypted using + * such a key. + */ + public CustomerEncryption getCustomerEncryption() { return customerEncryption; } @@ -724,12 +1116,12 @@ public Builder toBuilder() { @Override public String toString() { return MoreObjects.toStringHelper(this) - .add("bucket", bucket()) - .add("name", name()) - .add("generation", generation()) - .add("size", size()) - .add("content-type", contentType()) - .add("metadata", metadata()) + .add("bucket", getBucket()) + .add("name", getName()) + .add("generation", getGeneration()) + .add("size", getSize()) + .add("content-type", getContentType()) + .add("metadata", getMetadata()) .toString(); } @@ -802,107 +1194,152 @@ public ObjectAccessControl apply(Acl acl) { /** * Returns a {@code BlobInfo} builder where blob identity is set using the provided values. */ + @Deprecated public static Builder builder(BucketInfo bucketInfo, String name) { - return builder(bucketInfo.name(), name); + return newBuilder(bucketInfo.getName(), name); + } + + /** + * Returns a {@code BlobInfo} builder where blob identity is set using the provided values. + */ + public static Builder newBuilder(BucketInfo bucketInfo, String name) { + return newBuilder(bucketInfo.getName(), name); } /** * Returns a {@code BlobInfo} builder where blob identity is set using the provided values. */ + @Deprecated public static Builder builder(String bucket, String name) { - return builder(BlobId.of(bucket, name)); + return newBuilder(BlobId.of(bucket, name)); } /** * Returns a {@code BlobInfo} builder where blob identity is set using the provided values. */ + public static Builder newBuilder(String bucket, String name) { + return newBuilder(BlobId.of(bucket, name)); + } + + /** + * Returns a {@code BlobInfo} builder where blob identity is set using the provided values. + */ + @Deprecated public static Builder builder(BucketInfo bucketInfo, String name, Long generation) { - return builder(bucketInfo.name(), name, generation); + return newBuilder(bucketInfo.getName(), name, generation); + } + + /** + * Returns a {@code BlobInfo} builder where blob identity is set using the provided values. + */ + public static Builder newBuilder(BucketInfo bucketInfo, String name, Long generation) { + return newBuilder(bucketInfo.getName(), name, generation); } /** * Returns a {@code BlobInfo} builder where blob identity is set using the provided values. */ + @Deprecated public static Builder builder(String bucket, String name, Long generation) { - return builder(BlobId.of(bucket, name, generation)); + return newBuilder(BlobId.of(bucket, name, generation)); + } + + /** + * Returns a {@code BlobInfo} builder where blob identity is set using the provided values. + */ + public static Builder newBuilder(String bucket, String name, Long generation) { + return newBuilder(BlobId.of(bucket, name, generation)); } + /** + * Returns a {@code BlobInfo} builder where blob identity is set using the provided value. + */ + @Deprecated public static Builder builder(BlobId blobId) { + return newBuilder(blobId); + } + + /** + * Returns a {@code BlobInfo} builder where blob identity is set using the provided value. + */ + public static Builder newBuilder(BlobId blobId) { return new BuilderImpl(blobId); } static BlobInfo fromPb(StorageObject storageObject) { - Builder builder = builder(BlobId.fromPb(storageObject)); + Builder builder = newBuilder(BlobId.fromPb(storageObject)); if (storageObject.getCacheControl() != null) { - builder.cacheControl(storageObject.getCacheControl()); + builder.setCacheControl(storageObject.getCacheControl()); } if (storageObject.getContentEncoding() != null) { - builder.contentEncoding(storageObject.getContentEncoding()); + builder.setContentEncoding(storageObject.getContentEncoding()); } if (storageObject.getCrc32c() != null) { - builder.crc32c(storageObject.getCrc32c()); + builder.setCrc32c(storageObject.getCrc32c()); } if (storageObject.getContentType() != null) { - builder.contentType(storageObject.getContentType()); + builder.setContentType(storageObject.getContentType()); } if (storageObject.getMd5Hash() != null) { - builder.md5(storageObject.getMd5Hash()); + builder.setMd5(storageObject.getMd5Hash()); } if (storageObject.getMediaLink() != null) { - builder.mediaLink(storageObject.getMediaLink()); + builder.setMediaLink(storageObject.getMediaLink()); } if (storageObject.getMetageneration() != null) { - builder.metageneration(storageObject.getMetageneration()); + builder.setMetageneration(storageObject.getMetageneration()); } if (storageObject.getContentDisposition() != null) { - builder.contentDisposition(storageObject.getContentDisposition()); + builder.setContentDisposition(storageObject.getContentDisposition()); } if (storageObject.getComponentCount() != null) { - builder.componentCount(storageObject.getComponentCount()); + builder.setComponentCount(storageObject.getComponentCount()); } if (storageObject.getContentLanguage() != null) { - builder.contentLanguage(storageObject.getContentLanguage()); + builder.setContentLanguage(storageObject.getContentLanguage()); } if (storageObject.getEtag() != null) { - builder.etag(storageObject.getEtag()); + builder.setEtag(storageObject.getEtag()); } if (storageObject.getId() != null) { - builder.generatedId(storageObject.getId()); + builder.setGeneratedId(storageObject.getId()); } if (storageObject.getSelfLink() != null) { - builder.selfLink(storageObject.getSelfLink()); + builder.setSelfLink(storageObject.getSelfLink()); } if (storageObject.getMetadata() != null) { - builder.metadata(storageObject.getMetadata()); + builder.setMetadata(storageObject.getMetadata()); } if (storageObject.getTimeDeleted() != null) { - builder.deleteTime(storageObject.getTimeDeleted().getValue()); + builder.setDeleteTime(storageObject.getTimeDeleted().getValue()); } if (storageObject.getUpdated() != null) { - builder.updateTime(storageObject.getUpdated().getValue()); + builder.setUpdateTime(storageObject.getUpdated().getValue()); } if (storageObject.getTimeCreated() != null) { - builder.createTime(storageObject.getTimeCreated().getValue()); + builder.setCreateTime(storageObject.getTimeCreated().getValue()); } if (storageObject.getSize() != null) { - builder.size(storageObject.getSize().longValue()); + builder.setSize(storageObject.getSize().longValue()); } if (storageObject.getOwner() != null) { - builder.owner(Acl.Entity.fromPb(storageObject.getOwner().getEntity())); + builder.setOwner(Acl.Entity.fromPb(storageObject.getOwner().getEntity())); } if (storageObject.getAcl() != null) { - builder.acl(Lists.transform(storageObject.getAcl(), new Function() { - @Override - public Acl apply(ObjectAccessControl objectAccessControl) { - return Acl.fromPb(objectAccessControl); - } - })); + builder.setAcl(Lists.transform(storageObject.getAcl(), + new Function() { + @Override + public Acl apply(ObjectAccessControl objectAccessControl) { + return Acl.fromPb(objectAccessControl); + } + })); } if (storageObject.containsKey("isDirectory")) { - builder.isDirectory(Boolean.TRUE); + builder.setIsDirectory(Boolean.TRUE); } if (storageObject.getCustomerEncryption() != null) { - builder.customerEncryption(CustomerEncryption.fromPb(storageObject.getCustomerEncryption())); + builder.setCustomerEncryption( + CustomerEncryption.fromPb(storageObject.getCustomerEncryption())); } return builder.build(); } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/Bucket.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/Bucket.java index 7377e1742135..19a6034b5e2c 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/Bucket.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/Bucket.java @@ -71,22 +71,22 @@ private BucketSourceOption(StorageRpc.Option rpcOption) { } private Storage.BucketSourceOption toSourceOption(BucketInfo bucketInfo) { - switch (rpcOption()) { + switch (getRpcOption()) { case IF_METAGENERATION_MATCH: - return Storage.BucketSourceOption.metagenerationMatch(bucketInfo.metageneration()); + return Storage.BucketSourceOption.metagenerationMatch(bucketInfo.getMetageneration()); case IF_METAGENERATION_NOT_MATCH: - return Storage.BucketSourceOption.metagenerationNotMatch(bucketInfo.metageneration()); + return Storage.BucketSourceOption.metagenerationNotMatch(bucketInfo.getMetageneration()); default: throw new AssertionError("Unexpected enum value"); } } private Storage.BucketGetOption toGetOption(BucketInfo bucketInfo) { - switch (rpcOption()) { + switch (getRpcOption()) { case IF_METAGENERATION_MATCH: - return Storage.BucketGetOption.metagenerationMatch(bucketInfo.metageneration()); + return Storage.BucketGetOption.metagenerationMatch(bucketInfo.getMetageneration()); case IF_METAGENERATION_NOT_MATCH: - return Storage.BucketGetOption.metagenerationNotMatch(bucketInfo.metageneration()); + return Storage.BucketGetOption.metagenerationNotMatch(bucketInfo.getMetageneration()); default: throw new AssertionError("Unexpected enum value"); } @@ -139,7 +139,7 @@ public static class BlobTargetOption extends Option { new Function() { @Override public StorageRpc.Option apply(BlobTargetOption blobTargetOption) { - return blobTargetOption.rpcOption(); + return blobTargetOption.getRpcOption(); } }; private static final long serialVersionUID = 8345296337342509425L; @@ -149,28 +149,30 @@ private BlobTargetOption(StorageRpc.Option rpcOption, Object value) { } private StorageRpc.Tuple toTargetOption(BlobInfo blobInfo) { - BlobId blobId = blobInfo.blobId(); - switch (rpcOption()) { + BlobId blobId = blobInfo.getBlobId(); + switch (getRpcOption()) { case PREDEFINED_ACL: return StorageRpc.Tuple.of(blobInfo, - Storage.BlobTargetOption.predefinedAcl((Storage.PredefinedAcl) value())); + Storage.BlobTargetOption.predefinedAcl((Storage.PredefinedAcl) getValue())); case IF_GENERATION_MATCH: - blobId = BlobId.of(blobId.bucket(), blobId.name(), (Long) value()); - return StorageRpc.Tuple.of(blobInfo.toBuilder().blobId(blobId).build(), + blobId = BlobId.of(blobId.getBucket(), blobId.getName(), (Long) getValue()); + return StorageRpc.Tuple.of(blobInfo.toBuilder().setBlobId(blobId).build(), Storage.BlobTargetOption.generationMatch()); case IF_GENERATION_NOT_MATCH: - blobId = BlobId.of(blobId.bucket(), blobId.name(), (Long) value()); - return StorageRpc.Tuple.of(blobInfo.toBuilder().blobId(blobId).build(), + blobId = BlobId.of(blobId.getBucket(), blobId.getName(), (Long) getValue()); + return StorageRpc.Tuple.of(blobInfo.toBuilder().setBlobId(blobId).build(), Storage.BlobTargetOption.generationNotMatch()); case IF_METAGENERATION_MATCH: - return StorageRpc.Tuple.of(blobInfo.toBuilder().metageneration((Long) value()).build(), + return StorageRpc.Tuple.of( + blobInfo.toBuilder().setMetageneration((Long) getValue()).build(), Storage.BlobTargetOption.metagenerationMatch()); case IF_METAGENERATION_NOT_MATCH: - return StorageRpc.Tuple.of(blobInfo.toBuilder().metageneration((Long) value()).build(), + return StorageRpc.Tuple.of( + blobInfo.toBuilder().setMetageneration((Long) getValue()).build(), Storage.BlobTargetOption.metagenerationNotMatch()); case CUSTOMER_SUPPLIED_KEY: return StorageRpc.Tuple.of(blobInfo, - Storage.BlobTargetOption.encryptionKey((String) value())); + Storage.BlobTargetOption.encryptionKey((String) getValue())); default: throw new AssertionError("Unexpected enum value"); } @@ -288,30 +290,30 @@ public Storage.BlobWriteOption.Option apply(BlobWriteOption blobWriteOption) { private final Object value; private StorageRpc.Tuple toWriteOption(BlobInfo blobInfo) { - BlobId blobId = blobInfo.blobId(); + BlobId blobId = blobInfo.getBlobId(); switch (option) { case PREDEFINED_ACL: return StorageRpc.Tuple.of(blobInfo, Storage.BlobWriteOption.predefinedAcl((Storage.PredefinedAcl) value)); case IF_GENERATION_MATCH: - blobId = BlobId.of(blobId.bucket(), blobId.name(), (Long) value); - return StorageRpc.Tuple.of(blobInfo.toBuilder().blobId(blobId).build(), + blobId = BlobId.of(blobId.getBucket(), blobId.getName(), (Long) value); + return StorageRpc.Tuple.of(blobInfo.toBuilder().setBlobId(blobId).build(), Storage.BlobWriteOption.generationMatch()); case IF_GENERATION_NOT_MATCH: - blobId = BlobId.of(blobId.bucket(), blobId.name(), (Long) value); - return StorageRpc.Tuple.of(blobInfo.toBuilder().blobId(blobId).build(), + blobId = BlobId.of(blobId.getBucket(), blobId.getName(), (Long) value); + return StorageRpc.Tuple.of(blobInfo.toBuilder().setBlobId(blobId).build(), Storage.BlobWriteOption.generationNotMatch()); case IF_METAGENERATION_MATCH: - return StorageRpc.Tuple.of(blobInfo.toBuilder().metageneration((Long) value).build(), + return StorageRpc.Tuple.of(blobInfo.toBuilder().setMetageneration((Long) value).build(), Storage.BlobWriteOption.metagenerationMatch()); case IF_METAGENERATION_NOT_MATCH: - return StorageRpc.Tuple.of(blobInfo.toBuilder().metageneration((Long) value).build(), + return StorageRpc.Tuple.of(blobInfo.toBuilder().setMetageneration((Long) value).build(), Storage.BlobWriteOption.metagenerationNotMatch()); case IF_MD5_MATCH: - return StorageRpc.Tuple.of(blobInfo.toBuilder().md5((String) value).build(), + return StorageRpc.Tuple.of(blobInfo.toBuilder().setMd5((String) value).build(), Storage.BlobWriteOption.md5Match()); case IF_CRC32C_MATCH: - return StorageRpc.Tuple.of(blobInfo.toBuilder().crc32c((String) value).build(), + return StorageRpc.Tuple.of(blobInfo.toBuilder().setCrc32c((String) value).build(), Storage.BlobWriteOption.crc32cMatch()); case CUSTOMER_SUPPLIED_KEY: return StorageRpc.Tuple.of(blobInfo, @@ -468,98 +470,158 @@ public static class Builder extends BucketInfo.Builder { } @Override + @Deprecated public Builder name(String name) { - infoBuilder.name(name); + return setName(name); + } + + @Override + public Builder setName(String name) { + infoBuilder.setName(name); return this; } @Override - Builder generatedId(String generatedId) { - infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + infoBuilder.setGeneratedId(generatedId); return this; } @Override - Builder owner(Entity owner) { - infoBuilder.owner(owner); + Builder setOwner(Entity owner) { + infoBuilder.setOwner(owner); return this; } @Override - Builder selfLink(String selfLink) { - infoBuilder.selfLink(selfLink); + Builder setSelfLink(String selfLink) { + infoBuilder.setSelfLink(selfLink); return this; } @Override + @Deprecated public Builder versioningEnabled(Boolean enable) { - infoBuilder.versioningEnabled(enable); + return setVersioningEnabled(enable); + } + + @Override + public Builder setVersioningEnabled(Boolean enable) { + infoBuilder.setVersioningEnabled(enable); return this; } @Override + @Deprecated public Builder indexPage(String indexPage) { - infoBuilder.indexPage(indexPage); + return setIndexPage(indexPage); + } + + @Override + public Builder setIndexPage(String indexPage) { + infoBuilder.setIndexPage(indexPage); return this; } @Override + @Deprecated public Builder notFoundPage(String notFoundPage) { - infoBuilder.notFoundPage(notFoundPage); + return setNotFoundPage(notFoundPage); + } + + @Override + public Builder setNotFoundPage(String notFoundPage) { + infoBuilder.setNotFoundPage(notFoundPage); return this; } @Override + @Deprecated public Builder deleteRules(Iterable rules) { - infoBuilder.deleteRules(rules); + return setDeleteRules(rules); + } + + @Override + public Builder setDeleteRules(Iterable rules) { + infoBuilder.setDeleteRules(rules); return this; } @Override + @Deprecated public Builder storageClass(String storageClass) { - infoBuilder.storageClass(storageClass); + return setStorageClass(storageClass); + } + + @Override + public Builder setStorageClass(String storageClass) { + infoBuilder.setStorageClass(storageClass); return this; } @Override + @Deprecated public Builder location(String location) { - infoBuilder.location(location); + return setLocation(location); + } + + @Override + public Builder setLocation(String location) { + infoBuilder.setLocation(location); return this; } @Override - Builder etag(String etag) { - infoBuilder.etag(etag); + Builder setEtag(String etag) { + infoBuilder.setEtag(etag); return this; } @Override - Builder createTime(Long createTime) { - infoBuilder.createTime(createTime); + Builder setCreateTime(Long createTime) { + infoBuilder.setCreateTime(createTime); return this; } @Override - Builder metageneration(Long metageneration) { - infoBuilder.metageneration(metageneration); + Builder setMetageneration(Long metageneration) { + infoBuilder.setMetageneration(metageneration); return this; } @Override + @Deprecated public Builder cors(Iterable cors) { - infoBuilder.cors(cors); + return setCors(cors); + } + + @Override + public Builder setCors(Iterable cors) { + infoBuilder.setCors(cors); return this; } @Override + @Deprecated public Builder acl(Iterable acl) { - infoBuilder.acl(acl); + return setAcl(acl); + } + + @Override + public Builder setAcl(Iterable acl) { + infoBuilder.setAcl(acl); return this; } @Override + @Deprecated public Builder defaultAcl(Iterable acl) { - infoBuilder.defaultAcl(acl); + return setDefaultAcl(acl); + } + + @Override + public Builder setDefaultAcl(Iterable acl) { + infoBuilder.setDefaultAcl(acl); return this; } @@ -595,7 +657,7 @@ public boolean exists(BucketSourceOption... options) { int length = options.length; Storage.BucketGetOption[] getOptions = Arrays.copyOf(toGetOptions(this, options), length + 1); getOptions[length] = Storage.BucketGetOption.fields(); - return storage.get(name(), getOptions) != null; + return storage.get(getName(), getOptions) != null; } /** @@ -615,7 +677,7 @@ public boolean exists(BucketSourceOption... options) { * @throws StorageException upon failure */ public Bucket reload(BucketSourceOption... options) { - return storage.get(name(), toGetOptions(this, options)); + return storage.get(getName(), toGetOptions(this, options)); } /** @@ -627,7 +689,7 @@ public Bucket reload(BucketSourceOption... options) { * *

Example of updating the bucket's information. *

 {@code
-   * Bucket updatedBucket = bucket.toBuilder().versioningEnabled(true).build().update();
+   * Bucket updatedBucket = bucket.toBuilder().setVersioningEnabled(true).build().update();
    * }
* * @param options update options @@ -657,7 +719,7 @@ public Bucket update(BucketTargetOption... options) { * @throws StorageException upon failure */ public boolean delete(BucketSourceOption... options) { - return storage.delete(name(), toSourceOptions(this, options)); + return storage.delete(getName(), toSourceOptions(this, options)); } /** @@ -677,7 +739,7 @@ public boolean delete(BucketSourceOption... options) { * @throws StorageException upon failure */ public Page list(BlobListOption... options) { - return storage.list(name(), options); + return storage.list(getName(), options); } /** @@ -696,7 +758,7 @@ public Page list(BlobListOption... options) { * @throws StorageException upon failure */ public Blob get(String blob, BlobGetOption... options) { - return storage.get(BlobId.of(name(), blob), options); + return storage.get(BlobId.of(getName(), blob), options); } /** @@ -722,10 +784,10 @@ public Blob get(String blob, BlobGetOption... options) { */ public List get(String blobName1, String blobName2, String... blobNames) { List blobIds = Lists.newArrayListWithCapacity(blobNames.length + 2); - blobIds.add(BlobId.of(name(), blobName1)); - blobIds.add(BlobId.of(name(), blobName2)); + blobIds.add(BlobId.of(getName(), blobName1)); + blobIds.add(BlobId.of(getName(), blobName2)); for (String blobName : blobNames) { - blobIds.add(BlobId.of(name(), blobName)); + blobIds.add(BlobId.of(getName(), blobName)); } return storage.get(blobIds); } @@ -755,7 +817,7 @@ public List get(String blobName1, String blobName2, String... blobNames) { public List get(Iterable blobNames) { ImmutableList.Builder builder = ImmutableList.builder(); for (String blobName : blobNames) { - builder.add(BlobId.of(name(), blobName)); + builder.add(BlobId.of(getName(), blobName)); } return storage.get(builder.build()); } @@ -780,7 +842,8 @@ public List get(Iterable blobNames) { * @throws StorageException upon failure */ public Blob create(String blob, byte[] content, String contentType, BlobTargetOption... options) { - BlobInfo blobInfo = BlobInfo.builder(BlobId.of(name(), blob)).contentType(contentType).build(); + BlobInfo blobInfo = + BlobInfo.newBuilder(BlobId.of(getName(), blob)).setContentType(contentType).build(); StorageRpc.Tuple target = BlobTargetOption.toTargetOptions(blobInfo, options); return storage.create(target.x(), content, target.y()); @@ -807,7 +870,8 @@ public Blob create(String blob, byte[] content, String contentType, BlobTargetOp */ public Blob create(String blob, InputStream content, String contentType, BlobWriteOption... options) { - BlobInfo blobInfo = BlobInfo.builder(BlobId.of(name(), blob)).contentType(contentType).build(); + BlobInfo blobInfo = + BlobInfo.newBuilder(BlobId.of(getName(), blob)).setContentType(contentType).build(); StorageRpc.Tuple write = BlobWriteOption.toWriteOptions(blobInfo, options); return storage.create(write.x(), content, write.y()); @@ -832,7 +896,7 @@ public Blob create(String blob, InputStream content, String contentType, * @throws StorageException upon failure */ public Blob create(String blob, byte[] content, BlobTargetOption... options) { - BlobInfo blobInfo = BlobInfo.builder(BlobId.of(name(), blob)).build(); + BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(getName(), blob)).build(); StorageRpc.Tuple target = BlobTargetOption.toTargetOptions(blobInfo, options); return storage.create(target.x(), content, target.y()); @@ -857,7 +921,7 @@ public Blob create(String blob, byte[] content, BlobTargetOption... options) { * @throws StorageException upon failure */ public Blob create(String blob, InputStream content, BlobWriteOption... options) { - BlobInfo blobInfo = BlobInfo.builder(BlobId.of(name(), blob)).build(); + BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(getName(), blob)).build(); StorageRpc.Tuple write = BlobWriteOption.toWriteOptions(blobInfo, options); return storage.create(write.x(), content, write.y()); @@ -874,7 +938,7 @@ public Blob create(String blob, InputStream content, BlobWriteOption... options) * @throws StorageException upon failure */ public Acl getAcl(Entity entity) { - return storage.getAcl(name(), entity); + return storage.getAcl(getName(), entity); } /** @@ -894,7 +958,7 @@ public Acl getAcl(Entity entity) { * @throws StorageException upon failure */ public boolean deleteAcl(Entity entity) { - return storage.deleteAcl(name(), entity); + return storage.deleteAcl(getName(), entity); } /** @@ -908,7 +972,7 @@ public boolean deleteAcl(Entity entity) { * @throws StorageException upon failure */ public Acl createAcl(Acl acl) { - return storage.createAcl(name(), acl); + return storage.createAcl(getName(), acl); } /** @@ -922,7 +986,7 @@ public Acl createAcl(Acl acl) { * @throws StorageException upon failure */ public Acl updateAcl(Acl acl) { - return storage.updateAcl(name(), acl); + return storage.updateAcl(getName(), acl); } /** @@ -939,7 +1003,7 @@ public Acl updateAcl(Acl acl) { * @throws StorageException upon failure */ public List listAcls() { - return storage.listAcls(name()); + return storage.listAcls(getName()); } /** @@ -957,7 +1021,7 @@ public List listAcls() { * @throws StorageException upon failure */ public Acl getDefaultAcl(Entity entity) { - return storage.getDefaultAcl(name(), entity); + return storage.getDefaultAcl(getName(), entity); } /** @@ -980,7 +1044,7 @@ public Acl getDefaultAcl(Entity entity) { * @throws StorageException upon failure */ public boolean deleteDefaultAcl(Entity entity) { - return storage.deleteDefaultAcl(name(), entity); + return storage.deleteDefaultAcl(getName(), entity); } /** @@ -997,7 +1061,7 @@ public boolean deleteDefaultAcl(Entity entity) { * @throws StorageException upon failure */ public Acl createDefaultAcl(Acl acl) { - return storage.createDefaultAcl(name(), acl); + return storage.createDefaultAcl(getName(), acl); } /** @@ -1014,7 +1078,7 @@ public Acl createDefaultAcl(Acl acl) { * @throws StorageException upon failure */ public Acl updateDefaultAcl(Acl acl) { - return storage.updateDefaultAcl(name(), acl); + return storage.updateDefaultAcl(getName(), acl); } /** @@ -1034,13 +1098,21 @@ public Acl updateDefaultAcl(Acl acl) { * @throws StorageException upon failure */ public List listDefaultAcls() { - return storage.listDefaultAcls(name()); + return storage.listDefaultAcls(getName()); } /** * Returns the bucket's {@code Storage} object used to issue requests. */ + @Deprecated public Storage storage() { + return getStorage(); + } + + /** + * Returns the bucket's {@code Storage} object used to issue requests. + */ + public Storage getStorage() { return storage; } @@ -1054,7 +1126,7 @@ public final boolean equals(Object obj) { if (obj == this) { return true; } - if (obj != null && !obj.getClass().equals(Bucket.class)) { + if (obj == null || !obj.getClass().equals(Bucket.class)) { return false; } Bucket other = (Bucket) obj; diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/BucketInfo.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/BucketInfo.java index 36e0ed54ffa0..283d34b3bf5e 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/BucketInfo.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/BucketInfo.java @@ -102,7 +102,12 @@ public enum Type { this.type = type; } + @Deprecated public Type type() { + return getType(); + } + + public Type getType() { return type; } @@ -180,7 +185,12 @@ public AgeDeleteRule(int daysToLive) { this.daysToLive = daysToLive; } + @Deprecated public int daysToLive() { + return getDaysToLive(); + } + + public int getDaysToLive() { return daysToLive; } @@ -244,7 +254,12 @@ public CreatedBeforeDeleteRule(long timeMillis) { this.timeMillis = timeMillis; } + @Deprecated public long timeMillis() { + return getTimeMillis(); + } + + public long getTimeMillis() { return timeMillis; } @@ -276,7 +291,12 @@ public NumNewerVersionsDeleteRule(int numNewerVersions) { this.numNewerVersions = numNewerVersions; } + @Deprecated public int numNewerVersions() { + return getNumNewerVersions(); + } + + public int getNumNewerVersions() { return numNewerVersions; } @@ -324,57 +344,107 @@ public abstract static class Builder { /** * Sets the bucket's name. */ + @Deprecated public abstract Builder name(String name); - abstract Builder generatedId(String generatedId); + /** + * Sets the bucket's name. + */ + public abstract Builder setName(String name); + + abstract Builder setGeneratedId(String generatedId); - abstract Builder owner(Acl.Entity owner); + abstract Builder setOwner(Acl.Entity owner); - abstract Builder selfLink(String selfLink); + abstract Builder setSelfLink(String selfLink); /** * Sets whether versioning should be enabled for this bucket. When set to true, versioning is * fully enabled. */ + @Deprecated public abstract Builder versioningEnabled(Boolean enable); + /** + * Sets whether versioning should be enabled for this bucket. When set to true, versioning is + * fully enabled. + */ + public abstract Builder setVersioningEnabled(Boolean enable); + /** * Sets the bucket's website index page. Behaves as the bucket's directory index where missing * blobs are treated as potential directories. */ + @Deprecated public abstract Builder indexPage(String indexPage); + /** + * Sets the bucket's website index page. Behaves as the bucket's directory index where missing + * blobs are treated as potential directories. + */ + public abstract Builder setIndexPage(String indexPage); + /** * Sets the custom object to return when a requested resource is not found. */ + @Deprecated public abstract Builder notFoundPage(String notFoundPage); + /** + * Sets the custom object to return when a requested resource is not found. + */ + public abstract Builder setNotFoundPage(String notFoundPage); + /** * Sets the bucket's lifecycle configuration as a number of delete rules. * * @see Lifecycle Management */ + @Deprecated public abstract Builder deleteRules(Iterable rules); + /** + * Sets the bucket's lifecycle configuration as a number of delete rules. + * + * @see Lifecycle Management + */ + public abstract Builder setDeleteRules(Iterable rules); + /** * Sets the bucket's storage class. This defines how blobs in the bucket are stored and * determines the SLA and the cost of storage. A list of supported values is available * here. */ + @Deprecated public abstract Builder storageClass(String storageClass); + /** + * Sets the bucket's storage class. This defines how blobs in the bucket are stored and + * determines the SLA and the cost of storage. A list of supported values is available + * here. + */ + public abstract Builder setStorageClass(String storageClass); + /** * Sets the bucket's location. Data for blobs in the bucket resides in physical storage within * this region. A list of supported values is available * here. */ + @Deprecated public abstract Builder location(String location); - abstract Builder etag(String etag); + /** + * Sets the bucket's location. Data for blobs in the bucket resides in physical storage within + * this region. A list of supported values is available + * here. + */ + public abstract Builder setLocation(String location); + + abstract Builder setEtag(String etag); - abstract Builder createTime(Long createTime); + abstract Builder setCreateTime(Long createTime); - abstract Builder metageneration(Long metageneration); + abstract Builder setMetageneration(Long metageneration); /** * Sets the bucket's Cross-Origin Resource Sharing (CORS) configuration. @@ -382,8 +452,17 @@ public abstract static class Builder { * @see * Cross-Origin Resource Sharing (CORS) */ + @Deprecated public abstract Builder cors(Iterable cors); + /** + * Sets the bucket's Cross-Origin Resource Sharing (CORS) configuration. + * + * @see + * Cross-Origin Resource Sharing (CORS) + */ + public abstract Builder setCors(Iterable cors); + /** * Sets the bucket's access control configuration. * @@ -391,8 +470,18 @@ public abstract static class Builder { * href="https://cloud.google.com/storage/docs/access-control#About-Access-Control-Lists"> * About Access Control Lists */ + @Deprecated public abstract Builder acl(Iterable acl); + /** + * Sets the bucket's access control configuration. + * + * @see + * About Access Control Lists + */ + public abstract Builder setAcl(Iterable acl); + /** * Sets the default access control configuration to apply to bucket's blobs when no other * configuration is specified. @@ -401,8 +490,19 @@ public abstract static class Builder { * href="https://cloud.google.com/storage/docs/access-control#About-Access-Control-Lists"> * About Access Control Lists */ + @Deprecated public abstract Builder defaultAcl(Iterable acl); + /** + * Sets the default access control configuration to apply to bucket's blobs when no other + * configuration is specified. + * + * @see + * About Access Control Lists + */ + public abstract Builder setDefaultAcl(Iterable acl); + /** * Creates a {@code BucketInfo} object. */ @@ -452,97 +552,157 @@ static final class BuilderImpl extends Builder { } @Override + @Deprecated public Builder name(String name) { + return setName(name); + } + + @Override + public Builder setName(String name) { this.name = checkNotNull(name); return this; } @Override - Builder generatedId(String generatedId) { + Builder setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } @Override - Builder owner(Acl.Entity owner) { + Builder setOwner(Acl.Entity owner) { this.owner = owner; return this; } @Override - Builder selfLink(String selfLink) { + Builder setSelfLink(String selfLink) { this.selfLink = selfLink; return this; } @Override + @Deprecated public Builder versioningEnabled(Boolean enable) { + return setVersioningEnabled(enable); + } + + @Override + public Builder setVersioningEnabled(Boolean enable) { this.versioningEnabled = firstNonNull(enable, Data.nullOf(Boolean.class)); return this; } @Override + @Deprecated public Builder indexPage(String indexPage) { + return setIndexPage(indexPage); + } + + @Override + public Builder setIndexPage(String indexPage) { this.indexPage = indexPage; return this; } @Override + @Deprecated public Builder notFoundPage(String notFoundPage) { + return setNotFoundPage(notFoundPage); + } + + @Override + public Builder setNotFoundPage(String notFoundPage) { this.notFoundPage = notFoundPage; return this; } @Override + @Deprecated public Builder deleteRules(Iterable rules) { + return setDeleteRules(rules); + } + + @Override + public Builder setDeleteRules(Iterable rules) { this.deleteRules = rules != null ? ImmutableList.copyOf(rules) : null; return this; } @Override + @Deprecated public Builder storageClass(String storageClass) { + return setStorageClass(storageClass); + } + + @Override + public Builder setStorageClass(String storageClass) { this.storageClass = storageClass; return this; } @Override + @Deprecated public Builder location(String location) { + return setLocation(location); + } + + @Override + public Builder setLocation(String location) { this.location = location; return this; } @Override - Builder etag(String etag) { + Builder setEtag(String etag) { this.etag = etag; return this; } @Override - Builder createTime(Long createTime) { + Builder setCreateTime(Long createTime) { this.createTime = createTime; return this; } @Override - Builder metageneration(Long metageneration) { + Builder setMetageneration(Long metageneration) { this.metageneration = metageneration; return this; } @Override + @Deprecated public Builder cors(Iterable cors) { + return setCors(cors); + } + + @Override + public Builder setCors(Iterable cors) { this.cors = cors != null ? ImmutableList.copyOf(cors) : null; return this; } @Override + @Deprecated public Builder acl(Iterable acl) { + return setAcl(acl); + } + + @Override + public Builder setAcl(Iterable acl) { this.acl = acl != null ? ImmutableList.copyOf(acl) : null; return this; } @Override + @Deprecated public Builder defaultAcl(Iterable acl) { + return setDefaultAcl(acl); + } + + @Override + public Builder setDefaultAcl(Iterable acl) { this.defaultAcl = acl != null ? ImmutableList.copyOf(acl) : null; return this; } @@ -576,28 +736,60 @@ public BucketInfo build() { /** * Returns the service-generated id for the bucket. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated id for the bucket. + */ + public String getGeneratedId() { return generatedId; } /** * Returns the bucket's name. */ + @Deprecated public String name() { + return getName(); + } + + /** + * Returns the bucket's name. + */ + public String getName() { return name; } /** * Returns the bucket's owner. This is always the project team's owner group. */ + @Deprecated public Entity owner() { + return getOwner(); + } + + /** + * Returns the bucket's owner. This is always the project team's owner group. + */ + public Entity getOwner() { return owner; } /** * Returns the URI of this bucket as a string. */ + @Deprecated public String selfLink() { + return getSelfLink(); + } + + /** + * Returns the URI of this bucket as a string. + */ + public String getSelfLink() { return selfLink; } @@ -612,14 +804,31 @@ public Boolean versioningEnabled() { * Returns bucket's website index page. Behaves as the bucket's directory index where missing * blobs are treated as potential directories. */ + @Deprecated public String indexPage() { + return getIndexPage(); + } + + /** + * Returns bucket's website index page. Behaves as the bucket's directory index where missing + * blobs are treated as potential directories. + */ + public String getIndexPage() { return indexPage; } /** * Returns the custom object to return when a requested resource is not found. */ + @Deprecated public String notFoundPage() { + return getNotFoundPage(); + } + + /** + * Returns the custom object to return when a requested resource is not found. + */ + public String getNotFoundPage() { return notFoundPage; } @@ -628,7 +837,17 @@ public String notFoundPage() { * * @see Lifecycle Management */ + @Deprecated public List deleteRules() { + return getDeleteRules(); + } + + /** + * Returns bucket's lifecycle configuration as a number of delete rules. + * + * @see Lifecycle Management + */ + public List getDeleteRules() { return deleteRules; } @@ -637,21 +856,47 @@ public List deleteRules() { * * @see Entity Tags */ + @Deprecated public String etag() { + return getEtag(); + } + + /** + * Returns HTTP 1.1 Entity tag for the bucket. + * + * @see Entity Tags + */ + public String getEtag() { return etag; } /** * Returns the time at which the bucket was created. */ + @Deprecated public Long createTime() { + return getCreateTime(); + } + + /** + * Returns the time at which the bucket was created. + */ + public Long getCreateTime() { return createTime; } /** * Returns the metadata generation of this bucket. */ + @Deprecated public Long metageneration() { + return getMetageneration(); + } + + /** + * Returns the metadata generation of this bucket. + */ + public Long getMetageneration() { return metageneration; } @@ -661,7 +906,18 @@ public Long metageneration() { * * @see Bucket Locations */ + @Deprecated public String location() { + return getLocation(); + } + + /** + * Returns the bucket's location. Data for blobs in the bucket resides in physical storage within + * this region. + * + * @see Bucket Locations + */ + public String getLocation() { return location; } @@ -671,7 +927,18 @@ public String location() { * * @see Storage Classes */ + @Deprecated public String storageClass() { + return getStorageClass(); + } + + /** + * Returns the bucket's storage class. This defines how blobs in the bucket are stored and + * determines the SLA and the cost of storage. + * + * @see Storage Classes + */ + public String getStorageClass() { return storageClass; } @@ -681,7 +948,18 @@ public String storageClass() { * @see * Cross-Origin Resource Sharing (CORS) */ + @Deprecated public List cors() { + return getCors(); + } + + /** + * Returns the bucket's Cross-Origin Resource Sharing (CORS) configuration. + * + * @see + * Cross-Origin Resource Sharing (CORS) + */ + public List getCors() { return cors; } @@ -691,7 +969,18 @@ public List cors() { * @see * About Access Control Lists */ + @Deprecated public List acl() { + return getAcl(); + } + + /** + * Returns the bucket's access control configuration. + * + * @see + * About Access Control Lists + */ + public List getAcl() { return acl; } @@ -701,7 +990,18 @@ public List acl() { * @see * About Access Control Lists */ + @Deprecated public List defaultAcl() { + return getDefaultAcl(); + } + + /** + * Returns the default access control configuration for this bucket's blobs. + * + * @see + * About Access Control Lists + */ + public List getDefaultAcl() { return defaultAcl; } @@ -728,7 +1028,7 @@ public boolean equals(Object obj) { @Override public String toString() { return MoreObjects.toStringHelper(this) - .add("name", name()) + .add("name", name) .toString(); } @@ -799,44 +1099,52 @@ public Rule apply(DeleteRule deleteRule) { * Creates a {@code BucketInfo} object for the provided bucket name. */ public static BucketInfo of(String name) { - return builder(name).build(); + return newBuilder(name).build(); } /** * Returns a {@code BucketInfo} builder where the bucket's name is set to the provided name. */ + @Deprecated public static Builder builder(String name) { + return newBuilder(name); + } + + /** + * Returns a {@code BucketInfo} builder where the bucket's name is set to the provided name. + */ + public static Builder newBuilder(String name) { return new BuilderImpl(name); } static BucketInfo fromPb(com.google.api.services.storage.model.Bucket bucketPb) { Builder builder = new BuilderImpl(bucketPb.getName()); if (bucketPb.getId() != null) { - builder.generatedId(bucketPb.getId()); + builder.setGeneratedId(bucketPb.getId()); } if (bucketPb.getEtag() != null) { - builder.etag(bucketPb.getEtag()); + builder.setEtag(bucketPb.getEtag()); } if (bucketPb.getMetageneration() != null) { - builder.metageneration(bucketPb.getMetageneration()); + builder.setMetageneration(bucketPb.getMetageneration()); } if (bucketPb.getSelfLink() != null) { - builder.selfLink(bucketPb.getSelfLink()); + builder.setSelfLink(bucketPb.getSelfLink()); } if (bucketPb.getTimeCreated() != null) { - builder.createTime(bucketPb.getTimeCreated().getValue()); + builder.setCreateTime(bucketPb.getTimeCreated().getValue()); } if (bucketPb.getLocation() != null) { - builder.location(bucketPb.getLocation()); + builder.setLocation(bucketPb.getLocation()); } if (bucketPb.getStorageClass() != null) { - builder.storageClass(bucketPb.getStorageClass()); + builder.setStorageClass(bucketPb.getStorageClass()); } if (bucketPb.getCors() != null) { - builder.cors(transform(bucketPb.getCors(), Cors.FROM_PB_FUNCTION)); + builder.setCors(transform(bucketPb.getCors(), Cors.FROM_PB_FUNCTION)); } if (bucketPb.getAcl() != null) { - builder.acl(transform(bucketPb.getAcl(), new Function() { + builder.setAcl(transform(bucketPb.getAcl(), new Function() { @Override public Acl apply(BucketAccessControl bucketAccessControl) { return Acl.fromPb(bucketAccessControl); @@ -844,7 +1152,7 @@ public Acl apply(BucketAccessControl bucketAccessControl) { })); } if (bucketPb.getDefaultObjectAcl() != null) { - builder.defaultAcl(transform(bucketPb.getDefaultObjectAcl(), + builder.setDefaultAcl(transform(bucketPb.getDefaultObjectAcl(), new Function() { @Override public Acl apply(ObjectAccessControl objectAccessControl) { @@ -853,18 +1161,18 @@ public Acl apply(ObjectAccessControl objectAccessControl) { })); } if (bucketPb.getOwner() != null) { - builder.owner(Entity.fromPb(bucketPb.getOwner().getEntity())); + builder.setOwner(Entity.fromPb(bucketPb.getOwner().getEntity())); } if (bucketPb.getVersioning() != null) { - builder.versioningEnabled(bucketPb.getVersioning().getEnabled()); + builder.setVersioningEnabled(bucketPb.getVersioning().getEnabled()); } Website website = bucketPb.getWebsite(); if (website != null) { - builder.indexPage(website.getMainPageSuffix()); - builder.notFoundPage(website.getNotFoundPage()); + builder.setIndexPage(website.getMainPageSuffix()); + builder.setNotFoundPage(website.getNotFoundPage()); } if (bucketPb.getLifecycle() != null && bucketPb.getLifecycle().getRule() != null) { - builder.deleteRules(transform(bucketPb.getLifecycle().getRule(), + builder.setDeleteRules(transform(bucketPb.getLifecycle().getRule(), new Function() { @Override public DeleteRule apply(Rule rule) { diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/CopyWriter.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/CopyWriter.java index 2cf309d7c5ca..ec08bca60b91 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/CopyWriter.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/CopyWriter.java @@ -71,7 +71,25 @@ public class CopyWriter implements Restorable { * * @throws StorageException upon failure */ + @Deprecated public Blob result() { + return getResult(); + } + + /** + * Returns the updated information for the written blob. Calling this method when {@code isDone()} + * is {@code false} will block until all pending chunks are copied. + * + *

This method has the same effect of doing: + *

 {@code
+   * while (!copyWriter.isDone()) {
+   *    copyWriter.copyChunk();
+   * }}
+   * 
+ * + * @throws StorageException upon failure + */ + public Blob getResult() { while (!isDone()) { copyChunk(); } @@ -81,7 +99,15 @@ public Blob result() { /** * Returns the size of the blob being copied. */ + @Deprecated public long blobSize() { + return getBlobSize(); + } + + /** + * Returns the size of the blob being copied. + */ + public long getBlobSize() { return rewriteResponse.blobSize; } @@ -95,7 +121,15 @@ public boolean isDone() { /** * Returns the number of bytes copied. */ + @Deprecated public long totalBytesCopied() { + return getTotalBytesCopied(); + } + + /** + * Returns the number of bytes copied. + */ + public long getTotalBytesCopied() { return rewriteResponse.totalBytesRewritten; } @@ -122,19 +156,19 @@ public RewriteResponse call() { @Override public RestorableState capture() { - return StateImpl.builder( + return StateImpl.newBuilder( serviceOptions, BlobId.fromPb(rewriteResponse.rewriteRequest.source), rewriteResponse.rewriteRequest.sourceOptions, rewriteResponse.rewriteRequest.overrideInfo, BlobInfo.fromPb(rewriteResponse.rewriteRequest.target), rewriteResponse.rewriteRequest.targetOptions) - .result(rewriteResponse.result != null ? BlobInfo.fromPb(rewriteResponse.result) : null) - .blobSize(blobSize()) - .isDone(isDone()) - .megabytesCopiedPerChunk(rewriteResponse.rewriteRequest.megabytesRewrittenPerCall) - .rewriteToken(rewriteResponse.rewriteToken) - .totalBytesRewritten(totalBytesCopied()) + .setResult(rewriteResponse.result != null ? BlobInfo.fromPb(rewriteResponse.result) : null) + .setBlobSize(getBlobSize()) + .setIsDone(isDone()) + .setMegabytesCopiedPerChunk(rewriteResponse.rewriteRequest.megabytesRewrittenPerCall) + .setRewriteToken(rewriteResponse.rewriteToken) + .setTotalBytesRewritten(getTotalBytesCopied()) .build(); } @@ -196,32 +230,32 @@ private Builder(StorageOptions options, BlobId source, this.targetOptions = targetOptions; } - Builder result(BlobInfo result) { + Builder setResult(BlobInfo result) { this.result = result; return this; } - Builder blobSize(long blobSize) { + Builder setBlobSize(long blobSize) { this.blobSize = blobSize; return this; } - Builder isDone(boolean isDone) { + Builder setIsDone(boolean isDone) { this.isDone = isDone; return this; } - Builder rewriteToken(String rewriteToken) { + Builder setRewriteToken(String rewriteToken) { this.rewriteToken = rewriteToken; return this; } - Builder totalBytesRewritten(long totalBytesRewritten) { + Builder setTotalBytesRewritten(long totalBytesRewritten) { this.totalBytesCopied = totalBytesRewritten; return this; } - Builder megabytesCopiedPerChunk(Long megabytesCopiedPerChunk) { + Builder setMegabytesCopiedPerChunk(Long megabytesCopiedPerChunk) { this.megabytesCopiedPerChunk = megabytesCopiedPerChunk; return this; } @@ -231,7 +265,7 @@ RestorableState build() { } } - static Builder builder(StorageOptions options, BlobId source, + static Builder newBuilder(StorageOptions options, BlobId source, Map sourceOptions, boolean overrideInfo, BlobInfo target, Map targetOptions) { return new Builder(options, source, sourceOptions, overrideInfo, target, targetOptions); diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/Cors.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/Cors.java index 27ff44156712..8f8766adbaa0 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/Cors.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/Cors.java @@ -142,7 +142,16 @@ private Builder() {} * Sets the max time in seconds in which a client can issue requests before sending a new * preflight request. */ + @Deprecated public Builder maxAgeSeconds(Integer maxAgeSeconds) { + return setMaxAgeSeconds(maxAgeSeconds); + } + + /** + * Sets the max time in seconds in which a client can issue requests before sending a new + * preflight request. + */ + public Builder setMaxAgeSeconds(Integer maxAgeSeconds) { this.maxAgeSeconds = maxAgeSeconds; return this; } @@ -150,7 +159,15 @@ public Builder maxAgeSeconds(Integer maxAgeSeconds) { /** * Sets the HTTP methods supported by this CORS configuration. */ + @Deprecated public Builder methods(Iterable methods) { + return setMethods(methods); + } + + /** + * Sets the HTTP methods supported by this CORS configuration. + */ + public Builder setMethods(Iterable methods) { this.methods = methods != null ? ImmutableList.copyOf(methods) : null; return this; } @@ -158,7 +175,15 @@ public Builder methods(Iterable methods) { /** * Sets the origins for this CORS configuration. */ + @Deprecated public Builder origins(Iterable origins) { + return setOrigins(origins); + } + + /** + * Sets the origins for this CORS configuration. + */ + public Builder setOrigins(Iterable origins) { this.origins = origins != null ? ImmutableList.copyOf(origins) : null; return this; } @@ -166,7 +191,15 @@ public Builder origins(Iterable origins) { /** * Sets the response headers supported by this CORS configuration. */ + @Deprecated public Builder responseHeaders(Iterable headers) { + return setResponseHeaders(headers); + } + + /** + * Sets the response headers supported by this CORS configuration. + */ + public Builder setResponseHeaders(Iterable headers) { this.responseHeaders = headers != null ? ImmutableList.copyOf(headers) : null; return this; } @@ -190,28 +223,61 @@ private Cors(Builder builder) { * Returns the max time in seconds in which a client can issue requests before sending a new * preflight request. */ + @Deprecated public Integer maxAgeSeconds() { + return getMaxAgeSeconds(); + } + + /** + * Returns the max time in seconds in which a client can issue requests before sending a new + * preflight request. + */ + public Integer getMaxAgeSeconds() { return maxAgeSeconds; } /** * Returns the HTTP methods supported by this CORS configuration. */ + @Deprecated public List methods() { + return getMethods(); + } + + /** + * Returns the HTTP methods supported by this CORS configuration. + */ + public List getMethods() { return methods; } /** * Returns the origins in this CORS configuration. */ + @Deprecated public List origins() { + return getOrigins(); + } + + /** + * Returns the origins in this CORS configuration. + */ + public List getOrigins() { return origins; } /** * Returns the response headers supported by this CORS configuration. */ + @Deprecated public List responseHeaders() { + return getResponseHeaders(); + } + + /** + * Returns the response headers supported by this CORS configuration. + */ + public List getResponseHeaders() { return responseHeaders; } @@ -219,11 +285,11 @@ public List responseHeaders() { * Returns a builder for this CORS configuration. */ public Builder toBuilder() { - return builder() - .maxAgeSeconds(maxAgeSeconds) - .methods(methods) - .origins(origins) - .responseHeaders(responseHeaders); + return newBuilder() + .setMaxAgeSeconds(maxAgeSeconds) + .setMethods(methods) + .setOrigins(origins) + .setResponseHeaders(responseHeaders); } @Override @@ -246,7 +312,15 @@ public boolean equals(Object obj) { /** * Returns a CORS configuration builder. */ + @Deprecated public static Builder builder() { + return newBuilder(); + } + + /** + * Returns a CORS configuration builder. + */ + public static Builder newBuilder() { return new Builder(); } @@ -264,9 +338,9 @@ Bucket.Cors toPb() { } static Cors fromPb(Bucket.Cors cors) { - Builder builder = builder().maxAgeSeconds(cors.getMaxAgeSeconds()); + Builder builder = newBuilder().setMaxAgeSeconds(cors.getMaxAgeSeconds()); if (cors.getMethod() != null) { - builder.methods(transform(cors.getMethod(), new Function() { + builder.setMethods(transform(cors.getMethod(), new Function() { @Override public HttpMethod apply(String name) { return HttpMethod.valueOf(name.toUpperCase()); @@ -274,14 +348,14 @@ public HttpMethod apply(String name) { })); } if (cors.getOrigin() != null) { - builder.origins(transform(cors.getOrigin(), new Function() { + builder.setOrigins(transform(cors.getOrigin(), new Function() { @Override public Origin apply(String value) { return Origin.of(value); } })); } - builder.responseHeaders(cors.getResponseHeader()); + builder.setResponseHeaders(cors.getResponseHeader()); return builder.build(); } } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/Option.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/Option.java index e15d53a2d591..4716fbe754f0 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/Option.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/Option.java @@ -39,11 +39,11 @@ abstract class Option implements Serializable { this.value = value; } - StorageRpc.Option rpcOption() { + StorageRpc.Option getRpcOption() { return rpcOption; } - Object value() { + Object getValue() { return value; } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/Storage.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/Storage.java index 08202202ee64..01dfdc5cd654 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/Storage.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/Storage.java @@ -74,7 +74,7 @@ enum PredefinedAcl { this.entry = entry; } - String entry() { + String getEntry() { return entry; } } @@ -168,14 +168,15 @@ private BucketTargetOption(StorageRpc.Option rpcOption) { * Returns an option for specifying bucket's predefined ACL configuration. */ public static BucketTargetOption predefinedAcl(PredefinedAcl acl) { - return new BucketTargetOption(StorageRpc.Option.PREDEFINED_ACL, acl.entry()); + return new BucketTargetOption(StorageRpc.Option.PREDEFINED_ACL, acl.getEntry()); } /** * Returns an option for specifying bucket's default ACL configuration for blobs. */ public static BucketTargetOption predefinedDefaultObjectAcl(PredefinedAcl acl) { - return new BucketTargetOption(StorageRpc.Option.PREDEFINED_DEFAULT_OBJECT_ACL, acl.entry()); + return new BucketTargetOption(StorageRpc.Option.PREDEFINED_DEFAULT_OBJECT_ACL, + acl.getEntry()); } /** @@ -285,7 +286,7 @@ private BlobTargetOption(StorageRpc.Option rpcOption) { * Returns an option for specifying blob's predefined ACL configuration. */ public static BlobTargetOption predefinedAcl(PredefinedAcl acl) { - return new BlobTargetOption(StorageRpc.Option.PREDEFINED_ACL, acl.entry()); + return new BlobTargetOption(StorageRpc.Option.PREDEFINED_ACL, acl.getEntry()); } /** @@ -347,15 +348,15 @@ public static BlobTargetOption encryptionKey(String key) { } static Tuple convert(BlobInfo info, BlobWriteOption... options) { - BlobInfo.Builder infoBuilder = info.toBuilder().crc32c(null).md5(null); + BlobInfo.Builder infoBuilder = info.toBuilder().setCrc32c(null).setMd5(null); List targetOptions = Lists.newArrayListWithCapacity(options.length); for (BlobWriteOption option : options) { switch (option.option) { case IF_CRC32C_MATCH: - infoBuilder.crc32c(info.crc32c()); + infoBuilder.setCrc32c(info.getCrc32c()); break; case IF_MD5_MATCH: - infoBuilder.md5(info.md5()); + infoBuilder.setMd5(info.getMd5()); break; default: targetOptions.add(option.toTargetOption()); @@ -420,7 +421,7 @@ public boolean equals(Object obj) { * Returns an option for specifying blob's predefined ACL configuration. */ public static BlobWriteOption predefinedAcl(PredefinedAcl acl) { - return new BlobWriteOption(Option.PREDEFINED_ACL, acl.entry()); + return new BlobWriteOption(Option.PREDEFINED_ACL, acl.getEntry()); } /** @@ -797,11 +798,11 @@ private SignUrlOption(Option option, Object value) { this.value = value; } - Option option() { + Option getOption() { return option; } - Object value() { + Object getValue() { return value; } @@ -873,11 +874,21 @@ public static class SourceBlob implements Serializable { this.generation = generation; } + @Deprecated public String name() { + return getName(); + } + + public String getName() { return name; } + @Deprecated public Long generation() { + return getGeneration(); + } + + public Long getGeneration() { return generation; } } @@ -916,7 +927,15 @@ public Builder addSource(String blob, long generation) { /** * Sets compose operation's target blob. */ + @Deprecated public Builder target(BlobInfo target) { + return setTarget(target); + } + + /** + * Sets compose operation's target blob. + */ + public Builder setTarget(BlobInfo target) { this.target = target; return this; } @@ -924,7 +943,15 @@ public Builder target(BlobInfo target) { /** * Sets compose operation's target blob options. */ + @Deprecated public Builder targetOptions(BlobTargetOption... options) { + return setTargetOptions(options); + } + + /** + * Sets compose operation's target blob options. + */ + public Builder setTargetOptions(BlobTargetOption... options) { Collections.addAll(targetOptions, options); return this; } @@ -932,7 +959,15 @@ public Builder targetOptions(BlobTargetOption... options) { /** * Sets compose operation's target blob options. */ + @Deprecated public Builder targetOptions(Iterable options) { + return setTargetOptions(options); + } + + /** + * Sets compose operation's target blob options. + */ + public Builder setTargetOptions(Iterable options) { Iterables.addAll(targetOptions, options); return this; } @@ -956,21 +991,45 @@ private ComposeRequest(Builder builder) { /** * Returns compose operation's source blobs. */ + @Deprecated public List sourceBlobs() { + return getSourceBlobs(); + } + + /** + * Returns compose operation's source blobs. + */ + public List getSourceBlobs() { return sourceBlobs; } /** * Returns compose operation's target blob. */ + @Deprecated public BlobInfo target() { + return getTarget(); + } + + /** + * Returns compose operation's target blob. + */ + public BlobInfo getTarget() { return target; } /** * Returns compose operation's target blob's options. */ + @Deprecated public List targetOptions() { + return getTargetOptions(); + } + + /** + * Returns compose operation's target blob's options. + */ + public List getTargetOptions() { return targetOptions; } @@ -981,7 +1040,7 @@ public List targetOptions() { * @param target target blob */ public static ComposeRequest of(Iterable sources, BlobInfo target) { - return builder().target(target).addSource(sources).build(); + return newBuilder().setTarget(target).addSource(sources).build(); } /** @@ -992,13 +1051,21 @@ public static ComposeRequest of(Iterable sources, BlobInfo target) { * @param target target blob name */ public static ComposeRequest of(String bucket, Iterable sources, String target) { - return of(sources, BlobInfo.builder(BlobId.of(bucket, target)).build()); + return of(sources, BlobInfo.newBuilder(BlobId.of(bucket, target)).build()); } /** * Returns a {@code ComposeRequest} builder. */ + @Deprecated public static Builder builder() { + return newBuilder(); + } + + /** + * Returns a {@code ComposeRequest} builder. + */ + public static Builder newBuilder() { return new Builder(); } } @@ -1031,7 +1098,17 @@ public static class Builder { * * @return the builder */ + @Deprecated public Builder source(String bucket, String blob) { + return setSource(bucket, blob); + } + + /** + * Sets the blob to copy given bucket and blob name. + * + * @return the builder + */ + public Builder setSource(String bucket, String blob) { this.source = BlobId.of(bucket, blob); return this; } @@ -1041,7 +1118,17 @@ public Builder source(String bucket, String blob) { * * @return the builder */ + @Deprecated public Builder source(BlobId source) { + return setSource(source); + } + + /** + * Sets the blob to copy given a {@link BlobId}. + * + * @return the builder + */ + public Builder setSource(BlobId source) { this.source = source; return this; } @@ -1051,7 +1138,17 @@ public Builder source(BlobId source) { * * @return the builder */ + @Deprecated public Builder sourceOptions(BlobSourceOption... options) { + return setSourceOptions(options); + } + + /** + * Sets blob's source options. + * + * @return the builder + */ + public Builder setSourceOptions(BlobSourceOption... options) { Collections.addAll(sourceOptions, options); return this; } @@ -1061,7 +1158,17 @@ public Builder sourceOptions(BlobSourceOption... options) { * * @return the builder */ + @Deprecated public Builder sourceOptions(Iterable options) { + return setSourceOptions(options); + } + + /** + * Sets blob's source options. + * + * @return the builder + */ + public Builder setSourceOptions(Iterable options) { Iterables.addAll(sourceOptions, options); return this; } @@ -1071,9 +1178,19 @@ public Builder sourceOptions(Iterable options) { * * @return the builder */ + @Deprecated public Builder target(BlobId targetId) { + return setTarget(targetId); + } + + /** + * Sets the copy target. Target blob information is copied from source. + * + * @return the builder + */ + public Builder setTarget(BlobId targetId) { this.overrideInfo = false; - this.target = BlobInfo.builder(targetId).build(); + this.target = BlobInfo.newBuilder(targetId).build(); return this; } @@ -1085,7 +1202,20 @@ public Builder target(BlobId targetId) { * * @return the builder */ + @Deprecated public Builder target(BlobInfo target, BlobTargetOption... options) { + return setTarget(target, options); + } + + /** + * Sets the copy target and target options. {@code target} parameter is used to override + * source blob information (e.g. {@code contentType}, {@code contentLanguage}). Target blob + * information is set exactly to {@code target}, no information is inherited from the source + * blob. + * + * @return the builder + */ + public Builder setTarget(BlobInfo target, BlobTargetOption... options) { this.overrideInfo = true; this.target = checkNotNull(target); Collections.addAll(targetOptions, options); @@ -1100,7 +1230,20 @@ public Builder target(BlobInfo target, BlobTargetOption... options) { * * @return the builder */ + @Deprecated public Builder target(BlobInfo target, Iterable options) { + return setTarget(target, options); + } + + /** + * Sets the copy target and target options. {@code target} parameter is used to override + * source blob information (e.g. {@code contentType}, {@code contentLanguage}). Target blob + * information is set exactly to {@code target}, no information is inherited from the source + * blob. + * + * @return the builder + */ + public Builder setTarget(BlobInfo target, Iterable options) { this.overrideInfo = true; this.target = checkNotNull(target); Iterables.addAll(targetOptions, options); @@ -1114,7 +1257,19 @@ public Builder target(BlobInfo target, Iterable options) { * * @return the builder */ + @Deprecated public Builder megabytesCopiedPerChunk(Long megabytesCopiedPerChunk) { + return setMegabytesCopiedPerChunk(megabytesCopiedPerChunk); + } + + /** + * Sets the maximum number of megabytes to copy for each RPC call. This parameter is ignored + * if source and target blob share the same location and storage class as copy is made with + * one single RPC. + * + * @return the builder + */ + public Builder setMegabytesCopiedPerChunk(Long megabytesCopiedPerChunk) { this.megabytesCopiedPerChunk = megabytesCopiedPerChunk; return this; } @@ -1139,21 +1294,45 @@ private CopyRequest(Builder builder) { /** * Returns the blob to copy, as a {@link BlobId}. */ + @Deprecated public BlobId source() { + return getSource(); + } + + /** + * Returns the blob to copy, as a {@link BlobId}. + */ + public BlobId getSource() { return source; } /** * Returns blob's source options. */ + @Deprecated public List sourceOptions() { + return getSourceOptions(); + } + + /** + * Returns blob's source options. + */ + public List getSourceOptions() { return sourceOptions; } /** * Returns the {@link BlobInfo} for the target blob. */ + @Deprecated public BlobInfo target() { + return getTarget(); + } + + /** + * Returns the {@link BlobInfo} for the target blob. + */ + public BlobInfo getTarget() { return target; } @@ -1171,7 +1350,15 @@ public boolean overrideInfo() { /** * Returns blob's target options. */ + @Deprecated public List targetOptions() { + return getTargetOptions(); + } + + /** + * Returns blob's target options. + */ + public List getTargetOptions() { return targetOptions; } @@ -1180,7 +1367,17 @@ public List targetOptions() { * if source and target blob share the same location and storage class as copy is made with * one single RPC. */ + @Deprecated public Long megabytesCopiedPerChunk() { + return getMegabytesCopiedPerChunk(); + } + + /** + * Returns the maximum number of megabytes to copy for each RPC call. This parameter is ignored + * if source and target blob share the same location and storage class as copy is made with + * one single RPC. + */ + public Long getMegabytesCopiedPerChunk() { return megabytesCopiedPerChunk; } @@ -1194,7 +1391,7 @@ public Long megabytesCopiedPerChunk() { * @return a copy request */ public static CopyRequest of(String sourceBucket, String sourceBlob, BlobInfo target) { - return builder().source(sourceBucket, sourceBlob).target(target).build(); + return newBuilder().setSource(sourceBucket, sourceBlob).setTarget(target).build(); } /** @@ -1207,7 +1404,7 @@ public static CopyRequest of(String sourceBucket, String sourceBlob, BlobInfo ta * @return a copy request */ public static CopyRequest of(BlobId sourceBlobId, BlobInfo target) { - return builder().source(sourceBlobId).target(target).build(); + return newBuilder().setSource(sourceBlobId).setTarget(target).build(); } /** @@ -1219,9 +1416,9 @@ public static CopyRequest of(BlobId sourceBlobId, BlobInfo target) { * @return a copy request */ public static CopyRequest of(String sourceBucket, String sourceBlob, String targetBlob) { - return CopyRequest.builder() - .source(sourceBucket, sourceBlob) - .target(BlobId.of(sourceBucket, targetBlob)) + return CopyRequest.newBuilder() + .setSource(sourceBucket, sourceBlob) + .setTarget(BlobId.of(sourceBucket, targetBlob)) .build(); } @@ -1234,7 +1431,7 @@ public static CopyRequest of(String sourceBucket, String sourceBlob, String targ * @return a copy request */ public static CopyRequest of(String sourceBucket, String sourceBlob, BlobId target) { - return builder().source(sourceBucket, sourceBlob).target(target).build(); + return newBuilder().setSource(sourceBucket, sourceBlob).setTarget(target).build(); } /** @@ -1245,9 +1442,9 @@ public static CopyRequest of(String sourceBucket, String sourceBlob, BlobId targ * @return a copy request */ public static CopyRequest of(BlobId sourceBlobId, String targetBlob) { - return CopyRequest.builder() - .source(sourceBlobId) - .target(BlobId.of(sourceBlobId.bucket(), targetBlob)) + return CopyRequest.newBuilder() + .setSource(sourceBlobId) + .setTarget(BlobId.of(sourceBlobId.getBucket(), targetBlob)) .build(); } @@ -1259,13 +1456,24 @@ public static CopyRequest of(BlobId sourceBlobId, String targetBlob) { * @return a copy request */ public static CopyRequest of(BlobId sourceBlobId, BlobId targetBlobId) { - return CopyRequest.builder() - .source(sourceBlobId) - .target(targetBlobId) + return CopyRequest.newBuilder() + .setSource(sourceBlobId) + .setTarget(targetBlobId) .build(); } + /** + * Creates a builder for {@code CopyRequest} objects. + */ + @Deprecated public static Builder builder() { + return newBuilder(); + } + + /** + * Creates a builder for {@code CopyRequest} objects. + */ + public static Builder newBuilder() { return new Builder(); } } @@ -1292,7 +1500,7 @@ public static Builder builder() { * String bucketName = "my_unique_bucket"; * String blobName = "my_blob_name"; * BlobId blobId = BlobId.of(bucketName, blobName); - * BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); + * BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); * Blob blob = storage.create(blobInfo); * }
* @@ -1311,7 +1519,7 @@ public static Builder builder() { * String bucketName = "my_unique_bucket"; * String blobName = "my_blob_name"; * BlobId blobId = BlobId.of(bucketName, blobName); - * BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); + * BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); * Blob blob = storage.create(blobInfo, "Hello, World!".getBytes(UTF_8)); * }
* @@ -1334,7 +1542,7 @@ public static Builder builder() { * String blobName = "my_blob_name"; * InputStream content = new ByteArrayInputStream("Hello, World!".getBytes(UTF_8)); * BlobId blobId = BlobId.of(bucketName, blobName); - * BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); + * BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); * Blob blob = storage.create(blobInfo, content); * }
* @@ -1454,7 +1662,7 @@ public static Builder builder() { *

Example of updating bucket information. *

 {@code
    * String bucketName = "my_unique_bucket";
-   * BucketInfo bucketInfo = BucketInfo.builder(bucketName).versioningEnabled(true).build();
+   * BucketInfo bucketInfo = BucketInfo.newBuilder(bucketName).setVersioningEnabled(true).build();
    * Bucket bucket = storage.update(bucketInfo);
    * }
* @@ -1474,7 +1682,7 @@ public static Builder builder() { * String bucketName = "my_unique_bucket"; * String blobName = "my_blob_name"; * Blob blob = storage.get(bucketName, blobName); - * BlobInfo updatedInfo = blob.toBuilder().contentType("text/plain").build(); + * BlobInfo updatedInfo = blob.toBuilder().setContentType("text/plain").build(); * storage.update(updatedInfo, BlobTargetOption.metagenerationMatch()); * }
* @@ -1494,9 +1702,9 @@ public static Builder builder() { * String blobName = "my_blob_name"; * Map newMetadata = new HashMap<>(); * newMetadata.put("key", "value"); - * storage.update(BlobInfo.builder(bucketName, blobName).metadata(null).build()); - * Blob blob = storage.update(BlobInfo.builder(bucketName, blobName) - * .metadata(newMetadata) + * storage.update(BlobInfo.newBuilder(bucketName, blobName).setMetadata(null).build()); + * Blob blob = storage.update(BlobInfo.newBuilder(bucketName, blobName) + * .setMetadata(newMetadata) * .build()); * }
* @@ -1604,9 +1812,9 @@ public static Builder builder() { * String sourceBlob1 = "source_blob_1"; * String sourceBlob2 = "source_blob_2"; * BlobId blobId = BlobId.of(bucketName, blobName); - * BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); - * ComposeRequest request = ComposeRequest.builder() - * .target(blobInfo) + * BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); + * ComposeRequest request = ComposeRequest.newBuilder() + * .setTarget(blobInfo) * .addSource(sourceBlob1) * .addSource(sourceBlob2) * .build(); @@ -1637,11 +1845,11 @@ public static Builder builder() { * String bucketName = "my_unique_bucket"; * String blobName = "my_blob_name"; * String copyBlobName = "copy_blob_name"; - * CopyRequest request = CopyRequest.builder() - * .source(BlobId.of(bucketName, blobName)) - * .target(BlobId.of(bucketName, copyBlobName)) + * CopyRequest request = CopyRequest.newBuilder() + * .setSource(BlobId.of(bucketName, blobName)) + * .setTarget(BlobId.of(bucketName, copyBlobName)) * .build(); - * Blob blob = storage.copy(request).result(); + * Blob blob = storage.copy(request).getResult(); * }
* *

Example of copying a blob in chunks. @@ -1649,15 +1857,15 @@ public static Builder builder() { * String bucketName = "my_unique_bucket"; * String blobName = "my_blob_name"; * String copyBlobName = "copy_blob_name"; - * CopyRequest request = CopyRequest.builder() - * .source(BlobId.of(bucketName, blobName)) - * .target(BlobId.of(bucketName, copyBlobName)) + * CopyRequest request = CopyRequest.newBuilder() + * .setSource(BlobId.of(bucketName, blobName)) + * .setTarget(BlobId.of(bucketName, copyBlobName)) * .build(); * CopyWriter copyWriter = storage.copy(request); * while (!copyWriter.isDone()) { * copyWriter.copyChunk(); * } - * Blob blob = copyWriter.result(); + * Blob blob = copyWriter.getResult(); * }

* * @return a {@link CopyWriter} object that can be used to get information on the newly created @@ -1723,7 +1931,7 @@ public static Builder builder() { * // delete failed * } * }); - * batch.update(BlobInfo.builder(secondBlob).contentType("text/plain").build()); + * batch.update(BlobInfo.newBuilder(secondBlob).setContentType("text/plain").build()); * StorageBatchResult result = batch.get(secondBlob); * batch.submit(); * Blob blob = result.get(); // returns get result or throws StorageException @@ -1797,7 +2005,7 @@ public static Builder builder() { * String blobName = "my_blob_name"; * BlobId blobId = BlobId.of(bucketName, blobName); * byte[] content = "Hello, World!".getBytes(UTF_8); - * BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build(); + * BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); * try (WriteChannel writer = storage.writer(blobInfo)) { * try { * writer.write(ByteBuffer.wrap(content, 0, content.length)); @@ -1838,7 +2046,7 @@ public static Builder builder() { *
 {@code
    * String bucketName = "my_unique_bucket";
    * String blobName = "my_blob_name";
-   * URL signedUrl = storage.signUrl(BlobInfo.builder(bucketName, blobName).build(), 14,
+   * URL signedUrl = storage.signUrl(BlobInfo.newBuilder(bucketName, blobName).build(), 14,
    *     TimeUnit.DAYS);
    * }
* @@ -1849,7 +2057,7 @@ public static Builder builder() { * String bucketName = "my_unique_bucket"; * String blobName = "my_blob_name"; * String keyPath = "/path/to/key.json"; - * URL signedUrl = storage.signUrl(BlobInfo.builder(bucketName, blobName).build(), + * URL signedUrl = storage.signUrl(BlobInfo.newBuilder(bucketName, blobName).build(), * 14, TimeUnit.DAYS, SignUrlOption.signWith( * AuthCredentials.createForJson(new FileInputStream(keyPath)))); * }
@@ -1928,8 +2136,8 @@ public static Builder builder() { * Blob firstBlob = storage.get(bucketName, blobName1); * Blob secondBlob = storage.get(bucketName, blobName2); * List updatedBlobs = storage.update( - * firstBlob.toBuilder().contentType("text/plain").build(), - * secondBlob.toBuilder().contentType("text/plain").build()); + * firstBlob.toBuilder().setContentType("text/plain").build(), + * secondBlob.toBuilder().setContentType("text/plain").build()); * } * * @param blobInfos blobs to update @@ -1954,8 +2162,8 @@ public static Builder builder() { * Blob firstBlob = storage.get(bucketName, blobName1); * Blob secondBlob = storage.get(bucketName, blobName2); * List blobs = new LinkedList<>(); - * blobs.add(firstBlob.toBuilder().contentType("text/plain").build()); - * blobs.add(secondBlob.toBuilder().contentType("text/plain").build()); + * blobs.add(firstBlob.toBuilder().setContentType("text/plain").build()); + * blobs.add(secondBlob.toBuilder().setContentType("text/plain").build()); * List updatedBlobs = storage.update(blobs); * } * diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java index 8e8209e486f0..7cdda52aad0d 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java @@ -54,8 +54,8 @@ import com.google.common.collect.Maps; import com.google.common.hash.Hashing; import com.google.common.io.BaseEncoding; -import com.google.common.primitives.Ints; import com.google.common.net.UrlEscapers; +import com.google.common.primitives.Ints; import java.io.ByteArrayInputStream; import java.io.InputStream; @@ -113,8 +113,8 @@ public com.google.api.services.storage.model.Bucket call() { @Override public Blob create(BlobInfo blobInfo, BlobTargetOption... options) { BlobInfo updatedInfo = blobInfo.toBuilder() - .md5(EMPTY_BYTE_ARRAY_MD5) - .crc32c(EMPTY_BYTE_ARRAY_CRC32C) + .setMd5(EMPTY_BYTE_ARRAY_MD5) + .setCrc32c(EMPTY_BYTE_ARRAY_CRC32C) .build(); return create(updatedInfo, new ByteArrayInputStream(EMPTY_BYTE_ARRAY), options); } @@ -123,8 +123,8 @@ public Blob create(BlobInfo blobInfo, BlobTargetOption... options) { public Blob create(BlobInfo blobInfo, byte[] content, BlobTargetOption... options) { content = firstNonNull(content, EMPTY_BYTE_ARRAY); BlobInfo updatedInfo = blobInfo.toBuilder() - .md5(BaseEncoding.base64().encode(Hashing.md5().hashBytes(content).asBytes())) - .crc32c(BaseEncoding.base64().encode( + .setMd5(BaseEncoding.base64().encode(Hashing.md5().hashBytes(content).asBytes())) + .setCrc32c(BaseEncoding.base64().encode( Ints.toByteArray(Hashing.crc32c().hashBytes(content).asInt()))) .build(); return create(updatedInfo, new ByteArrayInputStream(content), options); @@ -387,15 +387,17 @@ public boolean delete(BlobId blob) { @Override public Blob compose(final ComposeRequest composeRequest) { final List sources = - Lists.newArrayListWithCapacity(composeRequest.sourceBlobs().size()); - for (ComposeRequest.SourceBlob sourceBlob : composeRequest.sourceBlobs()) { - sources.add(BlobInfo.builder( - BlobId.of(composeRequest.target().bucket(), sourceBlob.name(), sourceBlob.generation())) - .build().toPb()); - } - final StorageObject target = composeRequest.target().toPb(); - final Map targetOptions = optionMap(composeRequest.target().generation(), - composeRequest.target().metageneration(), composeRequest.targetOptions()); + Lists.newArrayListWithCapacity(composeRequest.getSourceBlobs().size()); + for (ComposeRequest.SourceBlob sourceBlob : composeRequest.getSourceBlobs()) { + sources.add(BlobInfo.newBuilder( + BlobId.of(composeRequest.getTarget().getBucket(), sourceBlob.getName(), + sourceBlob.getGeneration())) + .build().toPb()); + } + final StorageObject target = composeRequest.getTarget().toPb(); + final Map targetOptions = optionMap( + composeRequest.getTarget().getGeneration(), composeRequest.getTarget().getMetageneration(), + composeRequest.getTargetOptions()); try { return Blob.fromPb(this, runWithRetries(new Callable() { @Override @@ -410,19 +412,20 @@ public StorageObject call() { @Override public CopyWriter copy(final CopyRequest copyRequest) { - final StorageObject source = copyRequest.source().toPb(); - final Map sourceOptions = - optionMap(copyRequest.source().generation(), null, copyRequest.sourceOptions(), true); - final StorageObject targetObject = copyRequest.target().toPb(); - final Map targetOptions = optionMap(copyRequest.target().generation(), - copyRequest.target().metageneration(), copyRequest.targetOptions()); + final StorageObject source = copyRequest.getSource().toPb(); + final Map sourceOptions = optionMap( + copyRequest.getSource().getGeneration(), null, copyRequest.getSourceOptions(), true); + final StorageObject targetObject = copyRequest.getTarget().toPb(); + final Map targetOptions = + optionMap(copyRequest.getTarget().getGeneration(), + copyRequest.getTarget().getMetageneration(), copyRequest.getTargetOptions()); try { RewriteResponse rewriteResponse = runWithRetries(new Callable() { @Override public RewriteResponse call() { return storageRpc.openRewrite(new StorageRpc.RewriteRequest(source, sourceOptions, copyRequest.overrideInfo(), targetObject, targetOptions, - copyRequest.megabytesCopiedPerChunk())); + copyRequest.getMegabytesCopiedPerChunk())); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return new CopyWriter(options(), rewriteResponse); @@ -484,7 +487,7 @@ private BlobWriteChannel writer(BlobInfo blobInfo, BlobTargetOption... options) public URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, SignUrlOption... options) { EnumMap optionMap = Maps.newEnumMap(SignUrlOption.Option.class); for (SignUrlOption option : options) { - optionMap.put(option.option(), option.value()); + optionMap.put(option.getOption(), option.getValue()); } ServiceAccountSigner authCredentials = (ServiceAccountSigner) optionMap.get(SignUrlOption.Option.SERVICE_ACCOUNT_CRED); @@ -502,30 +505,30 @@ public URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, SignUrlOptio } stBuilder.append('\n'); if (firstNonNull((Boolean) optionMap.get(SignUrlOption.Option.MD5), false)) { - checkArgument(blobInfo.md5() != null, "Blob is missing a value for md5"); - stBuilder.append(blobInfo.md5()); + checkArgument(blobInfo.getMd5() != null, "Blob is missing a value for md5"); + stBuilder.append(blobInfo.getMd5()); } stBuilder.append('\n'); if (firstNonNull((Boolean) optionMap.get(SignUrlOption.Option.CONTENT_TYPE), false)) { - checkArgument(blobInfo.contentType() != null, "Blob is missing a value for content-type"); - stBuilder.append(blobInfo.contentType()); + checkArgument(blobInfo.getContentType() != null, "Blob is missing a value for content-type"); + stBuilder.append(blobInfo.getContentType()); } stBuilder.append('\n'); long expiration = TimeUnit.SECONDS.convert( options().clock().millis() + unit.toMillis(duration), TimeUnit.MILLISECONDS); stBuilder.append(expiration).append('\n'); StringBuilder path = new StringBuilder(); - if (!blobInfo.bucket().startsWith("/")) { + if (!blobInfo.getBucket().startsWith("/")) { path.append('/'); } - path.append(blobInfo.bucket()); - if (!blobInfo.bucket().endsWith("/")) { + path.append(blobInfo.getBucket()); + if (!blobInfo.getBucket().endsWith("/")) { path.append('/'); } - if (blobInfo.name().startsWith("/")) { + if (blobInfo.getName().startsWith("/")) { path.setLength(path.length() - 1); } - path.append(UrlEscapers.urlPathSegmentEscaper().escape(blobInfo.name())); + path.append(UrlEscapers.urlPathSegmentEscaper().escape(blobInfo.getName())); stBuilder.append(path); try { byte[] signatureBytes = authCredentials.sign(stBuilder.toString().getBytes(UTF_8)); @@ -773,7 +776,8 @@ public Acl getAcl(final BlobId blob, final Entity entity) { ObjectAccessControl answer = runWithRetries(new Callable() { @Override public ObjectAccessControl call() { - return storageRpc.getAcl(blob.bucket(), blob.name(), blob.generation(), entity.toPb()); + return storageRpc.getAcl( + blob.getBucket(), blob.getName(), blob.getGeneration(), entity.toPb()); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Acl.fromPb(answer); @@ -788,7 +792,8 @@ public boolean deleteAcl(final BlobId blob, final Entity entity) { return runWithRetries(new Callable() { @Override public Boolean call() { - return storageRpc.deleteAcl(blob.bucket(), blob.name(), blob.generation(), entity.toPb()); + return storageRpc.deleteAcl( + blob.getBucket(), blob.getName(), blob.getGeneration(), entity.toPb()); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); } catch (RetryHelperException e) { @@ -799,9 +804,9 @@ public Boolean call() { @Override public Acl createAcl(final BlobId blob, final Acl acl) { final ObjectAccessControl aclPb = acl.toObjectPb() - .setBucket(blob.bucket()) - .setObject(blob.name()) - .setGeneration(blob.generation()); + .setBucket(blob.getBucket()) + .setObject(blob.getName()) + .setGeneration(blob.getGeneration()); try { return Acl.fromPb(runWithRetries(new Callable() { @Override @@ -817,9 +822,9 @@ public ObjectAccessControl call() { @Override public Acl updateAcl(BlobId blob, Acl acl) { final ObjectAccessControl aclPb = acl.toObjectPb() - .setBucket(blob.bucket()) - .setObject(blob.name()) - .setGeneration(blob.generation()); + .setBucket(blob.getBucket()) + .setObject(blob.getName()) + .setGeneration(blob.getGeneration()); try { return Acl.fromPb(runWithRetries(new Callable() { @Override @@ -838,7 +843,7 @@ public List listAcls(final BlobId blob) { List answer = runWithRetries(new Callable>() { @Override public List call() { - return storageRpc.listAcls(blob.bucket(), blob.name(), blob.generation()); + return storageRpc.listAcls(blob.getBucket(), blob.getName(), blob.getGeneration()); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return Lists.transform(answer, Acl.FROM_OBJECT_PB_FUNCTION); @@ -873,7 +878,7 @@ private static void addToOptionMap(StorageRpc.Option getOption, StorageRpc.O Iterable options, boolean useAsSource) { Map temp = Maps.newEnumMap(StorageRpc.Option.class); for (Option option : options) { - Object prev = temp.put(option.rpcOption(), option.value()); + Object prev = temp.put(option.getRpcOption(), option.getValue()); checkArgument(prev == null, "Duplicate option %s", option); } Boolean value = (Boolean) temp.remove(DELIMITER); @@ -905,14 +910,14 @@ private static void addToOptionMap(StorageRpc.Option getOption, StorageRpc.O } private static Map optionMap(BucketInfo bucketInfo, Option... options) { - return optionMap(null, bucketInfo.metageneration(), options); + return optionMap(null, bucketInfo.getMetageneration(), options); } static Map optionMap(BlobInfo blobInfo, Option... options) { - return optionMap(blobInfo.generation(), blobInfo.metageneration(), options); + return optionMap(blobInfo.getGeneration(), blobInfo.getMetageneration(), options); } static Map optionMap(BlobId blobId, Option... options) { - return optionMap(blobId.generation(), null, options); + return optionMap(blobId.getGeneration(), null, options); } } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/package-info.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/package-info.java index b1f5736057bc..7c0cc3f588c7 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/package-info.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/package-info.java @@ -24,7 +24,7 @@ *
 {@code
  * Storage storage = StorageOptions.defaultInstance().service();
  * BlobId blobId = BlobId.of("bucket", "blob_name");
- * BlobInfo blobInfo = BlobInfo.builder(blobId).contentType("text/plain").build();
+ * BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
  * Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));
  * }
*

@@ -37,7 +37,7 @@ * BlobId blobId = BlobId.of("bucket", "blob_name"); * Blob blob = storage.get(blobId); * if (blob != null) { - * byte[] prevContent = blob.content(); + * byte[] prevContent = blob.getContent(); * System.out.println(new String(prevContent, UTF_8)); * WritableByteChannel channel = blob.writer(); * channel.write(ByteBuffer.wrap("Updated content".getBytes(UTF_8))); diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/RemoteStorageHelper.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/RemoteStorageHelper.java index 675c892fcc22..c24b5b75a4a6 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/RemoteStorageHelper.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/RemoteStorageHelper.java @@ -39,10 +39,10 @@ /** * Utility to create a remote storage configuration for testing. Storage options can be obtained via - * the {@link #options()} method. Returned options have custom {@link StorageOptions#retryParams()}: - * {@link RetryParams#retryMaxAttempts()} is {@code 10}, {@link RetryParams#retryMinAttempts()} is - * {@code 6}, {@link RetryParams#maxRetryDelayMillis()} is {@code 30000}, - * {@link RetryParams#totalRetryPeriodMillis()} is {@code 120000} and + * the {@link #getOptions()} ()} method. Returned options have custom + * {@link StorageOptions#retryParams()}: {@link RetryParams#retryMaxAttempts()} is {@code 10}, + * {@link RetryParams#retryMinAttempts()} is {@code 6}, {@link RetryParams#maxRetryDelayMillis()} is + * {@code 30000}, {@link RetryParams#totalRetryPeriodMillis()} is {@code 120000} and * {@link RetryParams#initialRetryDelayMillis()} is {@code 250}. * {@link StorageOptions#connectTimeout()} and {@link StorageOptions#readTimeout()} are both set * to {@code 60000}. @@ -60,7 +60,15 @@ private RemoteStorageHelper(StorageOptions options) { /** * Returns a {@link StorageOptions} object to be used for testing. */ + @Deprecated public StorageOptions options() { + return getOptions(); + } + + /** + * Returns a {@link StorageOptions} object to be used for testing. + */ + public StorageOptions getOptions() { return options; } @@ -176,7 +184,7 @@ public DeleteBucketTask(Storage storage, String bucket) { public Boolean call() { while (true) { for (BlobInfo info : storage.list(bucket, BlobListOption.versions(true)).values()) { - storage.delete(info.blobId()); + storage.delete(info.getBlobId()); } try { storage.delete(bucket); diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/package-info.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/package-info.java index bd234a1120b5..160add370e62 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/package-info.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/package-info.java @@ -22,7 +22,7 @@ *

Before the test: *

 {@code
  * RemoteStorageHelper helper = RemoteStorageHelper.create();
- * Storage storage = helper.options().service();
+ * Storage storage = helper.getOptions().service();
  * String bucket = RemoteStorageHelper.generateBucketName();
  * storage.create(BucketInfo.of(bucket));
  * } 
diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/AclTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/AclTest.java index 99180359486a..eaefcf96ff11 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/AclTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/AclTest.java @@ -38,22 +38,47 @@ public class AclTest { private static final Entity ENTITY = User.ofAllAuthenticatedUsers(); private static final String ETAG = "etag"; private static final String ID = "id"; - private static final Acl ACL = Acl.builder(ENTITY, ROLE).etag(ETAG).id(ID).build(); + private static final Acl ACL = Acl.newBuilder(ENTITY, ROLE).setEtag(ETAG).setId(ID).build(); + private static final Acl DEPRECATED_ACL = + Acl.builder(ENTITY, ROLE).setEtag(ETAG).setId(ID).build(); @Test public void testBuilder() { - assertEquals(ROLE, ACL.role()); - assertEquals(ENTITY, ACL.entity()); - assertEquals(ETAG, ACL.etag()); - assertEquals(ID, ACL.id()); + assertEquals(ROLE, ACL.getRole()); + assertEquals(ENTITY, ACL.getEntity()); + assertEquals(ETAG, ACL.getEtag()); + assertEquals(ID, ACL.getId()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(ROLE, DEPRECATED_ACL.role()); + assertEquals(ENTITY, DEPRECATED_ACL.entity()); + assertEquals(ETAG, DEPRECATED_ACL.etag()); + assertEquals(ID, DEPRECATED_ACL.id()); } @Test public void testToBuilder() { assertEquals(ACL, ACL.toBuilder().build()); Acl acl = ACL.toBuilder() - .etag("otherEtag") - .id("otherId") + .setEtag("otherEtag") + .setId("otherId") + .setRole(Role.READER) + .setEntity(User.ofAllUsers()) + .build(); + assertEquals(Role.READER, acl.getRole()); + assertEquals(User.ofAllUsers(), acl.getEntity()); + assertEquals("otherEtag", acl.getEtag()); + assertEquals("otherId", acl.getId()); + } + + @Test + public void testToBuilderDeprecated() { + assertEquals(DEPRECATED_ACL, DEPRECATED_ACL.toBuilder().build()); + Acl acl = DEPRECATED_ACL.toBuilder() + .setEtag("otherEtag") + .setId("otherId") .role(Role.READER) .entity(User.ofAllUsers()) .build(); @@ -71,6 +96,15 @@ public void testToAndFromPb() { @Test public void testDomainEntity() { + Domain acl = new Domain("d1"); + assertEquals("d1", acl.getDomain()); + assertEquals(Type.DOMAIN, acl.getType()); + String pb = acl.toPb(); + assertEquals(acl, Entity.fromPb(pb)); + } + + @Test + public void testDomainEntityDeprecated() { Domain acl = new Domain("d1"); assertEquals("d1", acl.domain()); assertEquals(Type.DOMAIN, acl.type()); @@ -80,6 +114,15 @@ public void testDomainEntity() { @Test public void testGroupEntity() { + Group acl = new Group("g1"); + assertEquals("g1", acl.getEmail()); + assertEquals(Type.GROUP, acl.getType()); + String pb = acl.toPb(); + assertEquals(acl, Entity.fromPb(pb)); + } + + @Test + public void testGroupEntityDeprecated() { Group acl = new Group("g1"); assertEquals("g1", acl.email()); assertEquals(Type.GROUP, acl.type()); @@ -89,6 +132,15 @@ public void testGroupEntity() { @Test public void testUserEntity() { + User acl = new User("u1"); + assertEquals("u1", acl.getEmail()); + assertEquals(Type.USER, acl.getType()); + String pb = acl.toPb(); + assertEquals(acl, Entity.fromPb(pb)); + } + + @Test + public void testUserEntityDeprecated() { User acl = new User("u1"); assertEquals("u1", acl.email()); assertEquals(Type.USER, acl.type()); @@ -98,6 +150,16 @@ public void testUserEntity() { @Test public void testProjectEntity() { + Project acl = new Project(ProjectRole.VIEWERS, "p1"); + assertEquals(ProjectRole.VIEWERS, acl.getProjectRole()); + assertEquals("p1", acl.getProjectId()); + assertEquals(Type.PROJECT, acl.getType()); + String pb = acl.toPb(); + assertEquals(acl, Entity.fromPb(pb)); + } + + @Test + public void testProjectEntityDeprecated() { Project acl = new Project(ProjectRole.VIEWERS, "p1"); assertEquals(ProjectRole.VIEWERS, acl.projectRole()); assertEquals("p1", acl.projectId()); @@ -108,6 +170,15 @@ public void testProjectEntity() { @Test public void testRawEntity() { + Entity acl = new RawEntity("bla"); + assertEquals("bla", acl.getValue()); + assertEquals(Type.UNKNOWN, acl.getType()); + String pb = acl.toPb(); + assertEquals(acl, Entity.fromPb(pb)); + } + + @Test + public void testRawEntityDeprecated() { Entity acl = new RawEntity("bla"); assertEquals("bla", acl.value()); assertEquals(Type.UNKNOWN, acl.type()); @@ -118,8 +189,8 @@ public void testRawEntity() { @Test public void testOf() { Acl acl = Acl.of(User.ofAllUsers(), Role.READER); - assertEquals(User.ofAllUsers(), acl.entity()); - assertEquals(Role.READER, acl.role()); + assertEquals(User.ofAllUsers(), acl.getEntity()); + assertEquals(Role.READER, acl.getRole()); ObjectAccessControl objectPb = acl.toObjectPb(); assertEquals(acl, Acl.fromPb(objectPb)); BucketAccessControl bucketPb = acl.toBucketPb(); diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobIdTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobIdTest.java index 989d6ff82f40..d1d16170b3c3 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobIdTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobIdTest.java @@ -26,6 +26,13 @@ public class BlobIdTest { @Test public void testOf() { + BlobId blobId = BlobId.of("b", "n"); + assertEquals("b", blobId.getBucket()); + assertEquals("n", blobId.getName()); + } + + @Test + public void testOfDeprecated() { BlobId blobId = BlobId.of("b", "n"); assertEquals("b", blobId.bucket()); assertEquals("n", blobId.name()); @@ -38,8 +45,8 @@ public void testEquals() { private void compareBlobIds(BlobId expected, BlobId value) { assertEquals(expected, value); - assertEquals(expected.bucket(), value.bucket()); - assertEquals(expected.name(), value.name()); + assertEquals(expected.getBucket(), value.getBucket()); + assertEquals(expected.getName(), value.getName()); assertEquals(expected.hashCode(), value.hashCode()); } diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobInfoTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobInfoTest.java index 63ed99c33551..7af723c45040 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobInfoTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobInfoTest.java @@ -66,36 +66,69 @@ public class BlobInfoTest { private static final String KEY_SHA256 = "keySha"; private static final CustomerEncryption CUSTOMER_ENCRYPTION = new CustomerEncryption(ENCRYPTION_ALGORITHM, KEY_SHA256); - private static final BlobInfo BLOB_INFO = BlobInfo.builder("b", "n", GENERATION) + private static final BlobInfo BLOB_INFO = BlobInfo.newBuilder("b", "n", GENERATION) + .setAcl(ACL) + .setComponentCount(COMPONENT_COUNT) + .setContentType(CONTENT_TYPE) + .setCacheControl(CACHE_CONTROL) + .setContentDisposition(CONTENT_DISPOSITION) + .setContentEncoding(CONTENT_ENCODING) + .setContentLanguage(CONTENT_LANGUAGE) + .setCustomerEncryption(CUSTOMER_ENCRYPTION) + .setCrc32c(CRC32) + .setDeleteTime(DELETE_TIME) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setMd5(MD5) + .setMediaLink(MEDIA_LINK) + .setMetadata(METADATA) + .setMetageneration(META_GENERATION) + .setOwner(OWNER) + .setSelfLink(SELF_LINK) + .setSize(SIZE) + .setUpdateTime(UPDATE_TIME) + .setCreateTime(CREATE_TIME) + .build(); + private static final BlobInfo DIRECTORY_INFO = BlobInfo.newBuilder("b", "n/") + .setSize(0L) + .setIsDirectory(true) + .build(); + private static final BlobInfo DEPRECATED_BLOB_INFO = BlobInfo.builder("b", "n", GENERATION) .acl(ACL) - .componentCount(COMPONENT_COUNT) + .setComponentCount(COMPONENT_COUNT) .contentType(CONTENT_TYPE) .cacheControl(CACHE_CONTROL) .contentDisposition(CONTENT_DISPOSITION) .contentEncoding(CONTENT_ENCODING) .contentLanguage(CONTENT_LANGUAGE) - .customerEncryption(CUSTOMER_ENCRYPTION) + .setCustomerEncryption(CUSTOMER_ENCRYPTION) .crc32c(CRC32) - .deleteTime(DELETE_TIME) - .etag(ETAG) - .generatedId(GENERATED_ID) + .setDeleteTime(DELETE_TIME) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) .md5(MD5) - .mediaLink(MEDIA_LINK) + .setMediaLink(MEDIA_LINK) .metadata(METADATA) - .metageneration(META_GENERATION) - .owner(OWNER) - .selfLink(SELF_LINK) - .size(SIZE) - .updateTime(UPDATE_TIME) - .createTime(CREATE_TIME) + .setMetageneration(META_GENERATION) + .setOwner(OWNER) + .setSelfLink(SELF_LINK) + .setSize(SIZE) + .setUpdateTime(UPDATE_TIME) + .setCreateTime(CREATE_TIME) .build(); - private static final BlobInfo DIRECTORY_INFO = BlobInfo.builder("b", "n/") - .size(0L) - .isDirectory(true) + private static final BlobInfo DEPRECATED_DIRECTORY_INFO = BlobInfo.builder("b", "n/") + .setSize(0L) + .setIsDirectory(true) .build(); @Test public void testCustomerEncryption() { + assertEquals(ENCRYPTION_ALGORITHM, CUSTOMER_ENCRYPTION.getEncryptionAlgorithm()); + assertEquals(KEY_SHA256, CUSTOMER_ENCRYPTION.getKeySha256()); + } + + @Test + public void testCustomerEncryptionDeprecated() { assertEquals(ENCRYPTION_ALGORITHM, CUSTOMER_ENCRYPTION.encryptionAlgorithm()); assertEquals(KEY_SHA256, CUSTOMER_ENCRYPTION.keySha256()); } @@ -103,106 +136,172 @@ public void testCustomerEncryption() { @Test public void testToBuilder() { compareBlobs(BLOB_INFO, BLOB_INFO.toBuilder().build()); - BlobInfo blobInfo = BLOB_INFO.toBuilder().blobId(BlobId.of("b2", "n2")).size(200L).build(); - assertEquals("n2", blobInfo.name()); - assertEquals("b2", blobInfo.bucket()); - assertEquals(Long.valueOf(200), blobInfo.size()); - blobInfo = blobInfo.toBuilder().blobId(BlobId.of("b", "n", GENERATION)).size(SIZE).build(); + BlobInfo blobInfo = BLOB_INFO.toBuilder() + .setBlobId(BlobId.of("b2", "n2")) + .setSize(200L) + .build(); + assertEquals("n2", blobInfo.getName()); + assertEquals("b2", blobInfo.getBucket()); + assertEquals(Long.valueOf(200), blobInfo.getSize()); + blobInfo = blobInfo.toBuilder() + .setBlobId(BlobId.of("b", "n", GENERATION)) + .setSize(SIZE) + .build(); compareBlobs(BLOB_INFO, blobInfo); } @Test public void testToBuilderIncomplete() { + BlobInfo incompleteBlobInfo = BlobInfo.newBuilder(BlobId.of("b2", "n2")).build(); + compareBlobs(incompleteBlobInfo, incompleteBlobInfo.toBuilder().build()); + } + + @Test + public void testToBuilderIncompleteDeprecated() { BlobInfo incompleteBlobInfo = BlobInfo.builder(BlobId.of("b2", "n2")).build(); compareBlobs(incompleteBlobInfo, incompleteBlobInfo.toBuilder().build()); } @Test public void testBuilder() { - assertEquals("b", BLOB_INFO.bucket()); - assertEquals("n", BLOB_INFO.name()); - assertEquals(ACL, BLOB_INFO.acl()); - assertEquals(COMPONENT_COUNT, BLOB_INFO.componentCount()); - assertEquals(CONTENT_TYPE, BLOB_INFO.contentType()); - assertEquals(CACHE_CONTROL, BLOB_INFO.cacheControl()); - assertEquals(CONTENT_DISPOSITION, BLOB_INFO.contentDisposition()); - assertEquals(CONTENT_ENCODING, BLOB_INFO.contentEncoding()); - assertEquals(CONTENT_LANGUAGE, BLOB_INFO.contentLanguage()); - assertEquals(CUSTOMER_ENCRYPTION, BLOB_INFO.customerEncryption()); - assertEquals(CRC32, BLOB_INFO.crc32c()); - assertEquals(DELETE_TIME, BLOB_INFO.deleteTime()); - assertEquals(ETAG, BLOB_INFO.etag()); - assertEquals(GENERATION, BLOB_INFO.generation()); - assertEquals(GENERATED_ID, BLOB_INFO.generatedId()); - assertEquals(MD5, BLOB_INFO.md5()); - assertEquals(MEDIA_LINK, BLOB_INFO.mediaLink()); - assertEquals(METADATA, BLOB_INFO.metadata()); - assertEquals(META_GENERATION, BLOB_INFO.metageneration()); - assertEquals(OWNER, BLOB_INFO.owner()); - assertEquals(SELF_LINK, BLOB_INFO.selfLink()); - assertEquals(SIZE, BLOB_INFO.size()); - assertEquals(UPDATE_TIME, BLOB_INFO.updateTime()); - assertEquals(CREATE_TIME, BLOB_INFO.createTime()); + assertEquals("b", BLOB_INFO.getBucket()); + assertEquals("n", BLOB_INFO.getName()); + assertEquals(ACL, BLOB_INFO.getAcl()); + assertEquals(COMPONENT_COUNT, BLOB_INFO.getComponentCount()); + assertEquals(CONTENT_TYPE, BLOB_INFO.getContentType()); + assertEquals(CACHE_CONTROL, BLOB_INFO.getCacheControl()); + assertEquals(CONTENT_DISPOSITION, BLOB_INFO.getContentDisposition()); + assertEquals(CONTENT_ENCODING, BLOB_INFO.getContentEncoding()); + assertEquals(CONTENT_LANGUAGE, BLOB_INFO.getContentLanguage()); + assertEquals(CUSTOMER_ENCRYPTION, BLOB_INFO.getCustomerEncryption()); + assertEquals(CRC32, BLOB_INFO.getCrc32c()); + assertEquals(DELETE_TIME, BLOB_INFO.getDeleteTime()); + assertEquals(ETAG, BLOB_INFO.getEtag()); + assertEquals(GENERATION, BLOB_INFO.getGeneration()); + assertEquals(GENERATED_ID, BLOB_INFO.getGeneratedId()); + assertEquals(MD5, BLOB_INFO.getMd5()); + assertEquals(MEDIA_LINK, BLOB_INFO.getMediaLink()); + assertEquals(METADATA, BLOB_INFO.getMetadata()); + assertEquals(META_GENERATION, BLOB_INFO.getMetageneration()); + assertEquals(OWNER, BLOB_INFO.getOwner()); + assertEquals(SELF_LINK, BLOB_INFO.getSelfLink()); + assertEquals(SIZE, BLOB_INFO.getSize()); + assertEquals(UPDATE_TIME, BLOB_INFO.getUpdateTime()); + assertEquals(CREATE_TIME, BLOB_INFO.getCreateTime()); assertFalse(BLOB_INFO.isDirectory()); - assertEquals("b", DIRECTORY_INFO.bucket()); - assertEquals("n/", DIRECTORY_INFO.name()); - assertNull(DIRECTORY_INFO.acl()); - assertNull(DIRECTORY_INFO.componentCount()); - assertNull(DIRECTORY_INFO.contentType()); - assertNull(DIRECTORY_INFO.cacheControl()); - assertNull(DIRECTORY_INFO.contentDisposition()); - assertNull(DIRECTORY_INFO.contentEncoding()); - assertNull(DIRECTORY_INFO.contentLanguage()); - assertNull(DIRECTORY_INFO.customerEncryption()); - assertNull(DIRECTORY_INFO.crc32c()); - assertNull(DIRECTORY_INFO.createTime()); - assertNull(DIRECTORY_INFO.deleteTime()); - assertNull(DIRECTORY_INFO.etag()); - assertNull(DIRECTORY_INFO.generation()); - assertNull(DIRECTORY_INFO.generatedId()); - assertNull(DIRECTORY_INFO.md5()); - assertNull(DIRECTORY_INFO.mediaLink()); - assertNull(DIRECTORY_INFO.metadata()); - assertNull(DIRECTORY_INFO.metageneration()); - assertNull(DIRECTORY_INFO.owner()); - assertNull(DIRECTORY_INFO.selfLink()); - assertEquals(0L, (long) DIRECTORY_INFO.size()); - assertNull(DIRECTORY_INFO.updateTime()); + assertEquals("b", DIRECTORY_INFO.getBucket()); + assertEquals("n/", DIRECTORY_INFO.getName()); + assertNull(DIRECTORY_INFO.getAcl()); + assertNull(DIRECTORY_INFO.getComponentCount()); + assertNull(DIRECTORY_INFO.getContentType()); + assertNull(DIRECTORY_INFO.getCacheControl()); + assertNull(DIRECTORY_INFO.getContentDisposition()); + assertNull(DIRECTORY_INFO.getContentEncoding()); + assertNull(DIRECTORY_INFO.getContentLanguage()); + assertNull(DIRECTORY_INFO.getCustomerEncryption()); + assertNull(DIRECTORY_INFO.getCrc32c()); + assertNull(DIRECTORY_INFO.getCreateTime()); + assertNull(DIRECTORY_INFO.getDeleteTime()); + assertNull(DIRECTORY_INFO.getEtag()); + assertNull(DIRECTORY_INFO.getGeneration()); + assertNull(DIRECTORY_INFO.getGeneratedId()); + assertNull(DIRECTORY_INFO.getMd5()); + assertNull(DIRECTORY_INFO.getMediaLink()); + assertNull(DIRECTORY_INFO.getMetadata()); + assertNull(DIRECTORY_INFO.getMetageneration()); + assertNull(DIRECTORY_INFO.getOwner()); + assertNull(DIRECTORY_INFO.getSelfLink()); + assertEquals(0L, (long) DIRECTORY_INFO.getSize()); + assertNull(DIRECTORY_INFO.getUpdateTime()); assertTrue(DIRECTORY_INFO.isDirectory()); } + @Test + public void testBuilderDeprecated() { + assertEquals("b", DEPRECATED_BLOB_INFO.bucket()); + assertEquals("n", DEPRECATED_BLOB_INFO.name()); + assertEquals(ACL, DEPRECATED_BLOB_INFO.acl()); + assertEquals(COMPONENT_COUNT, DEPRECATED_BLOB_INFO.componentCount()); + assertEquals(CONTENT_TYPE, DEPRECATED_BLOB_INFO.contentType()); + assertEquals(CACHE_CONTROL, DEPRECATED_BLOB_INFO.cacheControl()); + assertEquals(CONTENT_DISPOSITION, DEPRECATED_BLOB_INFO.contentDisposition()); + assertEquals(CONTENT_ENCODING, DEPRECATED_BLOB_INFO.contentEncoding()); + assertEquals(CONTENT_LANGUAGE, DEPRECATED_BLOB_INFO.contentLanguage()); + assertEquals(CUSTOMER_ENCRYPTION, DEPRECATED_BLOB_INFO.customerEncryption()); + assertEquals(CRC32, DEPRECATED_BLOB_INFO.crc32c()); + assertEquals(DELETE_TIME, DEPRECATED_BLOB_INFO.deleteTime()); + assertEquals(ETAG, DEPRECATED_BLOB_INFO.etag()); + assertEquals(GENERATION, DEPRECATED_BLOB_INFO.generation()); + assertEquals(GENERATED_ID, DEPRECATED_BLOB_INFO.generatedId()); + assertEquals(MD5, DEPRECATED_BLOB_INFO.md5()); + assertEquals(MEDIA_LINK, DEPRECATED_BLOB_INFO.mediaLink()); + assertEquals(METADATA, DEPRECATED_BLOB_INFO.metadata()); + assertEquals(META_GENERATION, DEPRECATED_BLOB_INFO.metageneration()); + assertEquals(OWNER, DEPRECATED_BLOB_INFO.owner()); + assertEquals(SELF_LINK, DEPRECATED_BLOB_INFO.selfLink()); + assertEquals(SIZE, DEPRECATED_BLOB_INFO.size()); + assertEquals(UPDATE_TIME, DEPRECATED_BLOB_INFO.updateTime()); + assertEquals(CREATE_TIME, DEPRECATED_BLOB_INFO.createTime()); + assertFalse(DEPRECATED_BLOB_INFO.isDirectory()); + assertEquals("b", DEPRECATED_DIRECTORY_INFO.bucket()); + assertEquals("n/", DEPRECATED_DIRECTORY_INFO.name()); + assertNull(DEPRECATED_DIRECTORY_INFO.acl()); + assertNull(DEPRECATED_DIRECTORY_INFO.componentCount()); + assertNull(DEPRECATED_DIRECTORY_INFO.contentType()); + assertNull(DEPRECATED_DIRECTORY_INFO.cacheControl()); + assertNull(DEPRECATED_DIRECTORY_INFO.contentDisposition()); + assertNull(DEPRECATED_DIRECTORY_INFO.contentEncoding()); + assertNull(DEPRECATED_DIRECTORY_INFO.contentLanguage()); + assertNull(DEPRECATED_DIRECTORY_INFO.customerEncryption()); + assertNull(DEPRECATED_DIRECTORY_INFO.crc32c()); + assertNull(DEPRECATED_DIRECTORY_INFO.createTime()); + assertNull(DEPRECATED_DIRECTORY_INFO.deleteTime()); + assertNull(DEPRECATED_DIRECTORY_INFO.etag()); + assertNull(DEPRECATED_DIRECTORY_INFO.generation()); + assertNull(DEPRECATED_DIRECTORY_INFO.generatedId()); + assertNull(DEPRECATED_DIRECTORY_INFO.md5()); + assertNull(DEPRECATED_DIRECTORY_INFO.mediaLink()); + assertNull(DEPRECATED_DIRECTORY_INFO.metadata()); + assertNull(DEPRECATED_DIRECTORY_INFO.metageneration()); + assertNull(DEPRECATED_DIRECTORY_INFO.owner()); + assertNull(DEPRECATED_DIRECTORY_INFO.selfLink()); + assertEquals(0L, (long) DEPRECATED_DIRECTORY_INFO.size()); + assertNull(DEPRECATED_DIRECTORY_INFO.updateTime()); + assertTrue(DEPRECATED_DIRECTORY_INFO.isDirectory()); + } + private void compareBlobs(BlobInfo expected, BlobInfo value) { assertEquals(expected, value); - assertEquals(expected.bucket(), value.bucket()); - assertEquals(expected.name(), value.name()); - assertEquals(expected.acl(), value.acl()); - assertEquals(expected.componentCount(), value.componentCount()); - assertEquals(expected.contentType(), value.contentType()); - assertEquals(expected.cacheControl(), value.cacheControl()); - assertEquals(expected.contentDisposition(), value.contentDisposition()); - assertEquals(expected.contentEncoding(), value.contentEncoding()); - assertEquals(expected.contentLanguage(), value.contentLanguage()); - assertEquals(expected.customerEncryption(), value.customerEncryption()); - assertEquals(expected.crc32c(), value.crc32c()); - assertEquals(expected.createTime(), value.createTime()); - assertEquals(expected.deleteTime(), value.deleteTime()); - assertEquals(expected.etag(), value.etag()); - assertEquals(expected.generation(), value.generation()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.md5(), value.md5()); - assertEquals(expected.mediaLink(), value.mediaLink()); - assertEquals(expected.metadata(), value.metadata()); - assertEquals(expected.metageneration(), value.metageneration()); - assertEquals(expected.owner(), value.owner()); - assertEquals(expected.selfLink(), value.selfLink()); - assertEquals(expected.size(), value.size()); - assertEquals(expected.updateTime(), value.updateTime()); + assertEquals(expected.getBucket(), value.getBucket()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getAcl(), value.getAcl()); + assertEquals(expected.getComponentCount(), value.getComponentCount()); + assertEquals(expected.getContentType(), value.getContentType()); + assertEquals(expected.getCacheControl(), value.getCacheControl()); + assertEquals(expected.getContentDisposition(), value.getContentDisposition()); + assertEquals(expected.getContentEncoding(), value.getContentEncoding()); + assertEquals(expected.getContentLanguage(), value.getContentLanguage()); + assertEquals(expected.getCustomerEncryption(), value.getCustomerEncryption()); + assertEquals(expected.getCrc32c(), value.getCrc32c()); + assertEquals(expected.getCreateTime(), value.getCreateTime()); + assertEquals(expected.getDeleteTime(), value.getDeleteTime()); + assertEquals(expected.getEtag(), value.getEtag()); + assertEquals(expected.getGeneration(), value.getGeneration()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getMd5(), value.getMd5()); + assertEquals(expected.getMediaLink(), value.getMediaLink()); + assertEquals(expected.getMetadata(), value.getMetadata()); + assertEquals(expected.getMetageneration(), value.getMetageneration()); + assertEquals(expected.getOwner(), value.getOwner()); + assertEquals(expected.getSelfLink(), value.getSelfLink()); + assertEquals(expected.getSize(), value.getSize()); + assertEquals(expected.getUpdateTime(), value.getUpdateTime()); } private void compareCustomerEncryptions(CustomerEncryption expected, CustomerEncryption value) { assertEquals(expected, value); - assertEquals(expected.encryptionAlgorithm(), value.encryptionAlgorithm()); - assertEquals(expected.keySha256(), value.keySha256()); + assertEquals(expected.getEncryptionAlgorithm(), value.getEncryptionAlgorithm()); + assertEquals(expected.getKeySha256(), value.getKeySha256()); assertEquals(expected.hashCode(), value.hashCode()); } @@ -210,8 +309,8 @@ private void compareCustomerEncryptions(CustomerEncryption expected, CustomerEnc public void testToPbAndFromPb() { compareCustomerEncryptions(CUSTOMER_ENCRYPTION, CustomerEncryption.fromPb(CUSTOMER_ENCRYPTION.toPb())); - compareBlobs(BLOB_INFO, BlobInfo.fromPb(BLOB_INFO.toPb())); - BlobInfo blobInfo = BlobInfo.builder(BlobId.of("b", "n")).build(); + compareBlobs(DEPRECATED_BLOB_INFO, BlobInfo.fromPb(DEPRECATED_BLOB_INFO.toPb())); + BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of("b", "n")).build(); compareBlobs(blobInfo, BlobInfo.fromPb(blobInfo.toPb())); StorageObject object = new StorageObject() .setName("n/") @@ -219,35 +318,35 @@ public void testToPbAndFromPb() { .setSize(BigInteger.ZERO) .set("isDirectory", true); blobInfo = BlobInfo.fromPb(object); - assertEquals("b", blobInfo.bucket()); - assertEquals("n/", blobInfo.name()); - assertNull(blobInfo.acl()); - assertNull(blobInfo.componentCount()); - assertNull(blobInfo.contentType()); - assertNull(blobInfo.cacheControl()); - assertNull(blobInfo.contentDisposition()); - assertNull(blobInfo.contentEncoding()); - assertNull(blobInfo.contentLanguage()); - assertNull(blobInfo.customerEncryption()); - assertNull(blobInfo.crc32c()); - assertNull(blobInfo.createTime()); - assertNull(blobInfo.deleteTime()); - assertNull(blobInfo.etag()); - assertNull(blobInfo.generation()); - assertNull(blobInfo.generatedId()); - assertNull(blobInfo.md5()); - assertNull(blobInfo.mediaLink()); - assertNull(blobInfo.metadata()); - assertNull(blobInfo.metageneration()); - assertNull(blobInfo.owner()); - assertNull(blobInfo.selfLink()); - assertEquals(0L, (long) blobInfo.size()); - assertNull(blobInfo.updateTime()); + assertEquals("b", blobInfo.getBucket()); + assertEquals("n/", blobInfo.getName()); + assertNull(blobInfo.getAcl()); + assertNull(blobInfo.getComponentCount()); + assertNull(blobInfo.getContentType()); + assertNull(blobInfo.getCacheControl()); + assertNull(blobInfo.getContentDisposition()); + assertNull(blobInfo.getContentEncoding()); + assertNull(blobInfo.getContentLanguage()); + assertNull(blobInfo.getCustomerEncryption()); + assertNull(blobInfo.getCrc32c()); + assertNull(blobInfo.getCreateTime()); + assertNull(blobInfo.getDeleteTime()); + assertNull(blobInfo.getEtag()); + assertNull(blobInfo.getGeneration()); + assertNull(blobInfo.getGeneratedId()); + assertNull(blobInfo.getMd5()); + assertNull(blobInfo.getMediaLink()); + assertNull(blobInfo.getMetadata()); + assertNull(blobInfo.getMetageneration()); + assertNull(blobInfo.getOwner()); + assertNull(blobInfo.getSelfLink()); + assertEquals(0L, (long) blobInfo.getSize()); + assertNull(blobInfo.getUpdateTime()); assertTrue(blobInfo.isDirectory()); } @Test public void testBlobId() { - assertEquals(BlobId.of("b", "n", GENERATION), BLOB_INFO.blobId()); + assertEquals(BlobId.of("b", "n", GENERATION), BLOB_INFO.getBlobId()); } } diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobTest.java index 577e74685f84..b070ebb0b1c4 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobTest.java @@ -84,33 +84,35 @@ public class BlobTest { private static final String KEY_SHA256 = "keySha"; private static final BlobInfo.CustomerEncryption CUSTOMER_ENCRYPTION = new BlobInfo.CustomerEncryption(ENCRYPTION_ALGORITHM, KEY_SHA256); - private static final BlobInfo FULL_BLOB_INFO = BlobInfo.builder("b", "n", GENERATION) - .acl(ACLS) - .componentCount(COMPONENT_COUNT) - .contentType(CONTENT_TYPE) - .cacheControl(CACHE_CONTROL) - .contentDisposition(CONTENT_DISPOSITION) - .contentEncoding(CONTENT_ENCODING) - .contentLanguage(CONTENT_LANGUAGE) - .crc32c(CRC32) - .deleteTime(DELETE_TIME) - .etag(ETAG) - .generatedId(GENERATED_ID) - .md5(MD5) - .mediaLink(MEDIA_LINK) - .metadata(METADATA) - .metageneration(META_GENERATION) - .owner(OWNER) - .selfLink(SELF_LINK) - .size(SIZE) - .updateTime(UPDATE_TIME) - .createTime(CREATE_TIME) - .customerEncryption(CUSTOMER_ENCRYPTION) + private static final BlobInfo FULL_BLOB_INFO = BlobInfo.newBuilder("b", "n", GENERATION) + .setAcl(ACLS) + .setComponentCount(COMPONENT_COUNT) + .setContentType(CONTENT_TYPE) + .setCacheControl(CACHE_CONTROL) + .setContentDisposition(CONTENT_DISPOSITION) + .setContentEncoding(CONTENT_ENCODING) + .setContentLanguage(CONTENT_LANGUAGE) + .setCrc32c(CRC32) + .setDeleteTime(DELETE_TIME) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setMd5(MD5) + .setMediaLink(MEDIA_LINK) + .setMetadata(METADATA) + .setMetageneration(META_GENERATION) + .setOwner(OWNER) + .setSelfLink(SELF_LINK) + .setSize(SIZE) + .setUpdateTime(UPDATE_TIME) + .setCreateTime(CREATE_TIME) + .setCustomerEncryption(CUSTOMER_ENCRYPTION) .build(); - private static final BlobInfo BLOB_INFO = BlobInfo.builder("b", "n").metageneration(42L).build(); - private static final BlobInfo DIRECTORY_INFO = BlobInfo.builder("b", "n/") - .size(0L) - .isDirectory(true) + private static final BlobInfo BLOB_INFO = BlobInfo.newBuilder("b", "n") + .setMetageneration(42L) + .build(); + private static final BlobInfo DIRECTORY_INFO = BlobInfo.newBuilder("b", "n/") + .setSize(0L) + .setIsDirectory(true) .build(); private static final String BASE64_KEY = "JVzfVl8NLD9FjedFuStegjRfES5ll5zc59CIXw572OA="; private static final Key KEY = @@ -147,7 +149,7 @@ public void testExists_True() throws Exception { initializeExpectedBlob(1); Storage.BlobGetOption[] expectedOptions = {Storage.BlobGetOption.fields()}; expect(storage.options()).andReturn(mockOptions); - expect(storage.get(expectedBlob.blobId(), expectedOptions)).andReturn(expectedBlob); + expect(storage.get(expectedBlob.getBlobId(), expectedOptions)).andReturn(expectedBlob); replay(storage); initializeBlob(); assertTrue(blob.exists()); @@ -157,7 +159,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { Storage.BlobGetOption[] expectedOptions = {Storage.BlobGetOption.fields()}; expect(storage.options()).andReturn(null); - expect(storage.get(BLOB_INFO.blobId(), expectedOptions)).andReturn(null); + expect(storage.get(BLOB_INFO.getBlobId(), expectedOptions)).andReturn(null); replay(storage); initializeBlob(); assertFalse(blob.exists()); @@ -168,10 +170,10 @@ public void testContent() throws Exception { initializeExpectedBlob(2); byte[] content = {1, 2}; expect(storage.options()).andReturn(mockOptions); - expect(storage.readAllBytes(BLOB_INFO.blobId())).andReturn(content); + expect(storage.readAllBytes(BLOB_INFO.getBlobId())).andReturn(content); replay(storage); initializeBlob(); - assertArrayEquals(content, blob.content()); + assertArrayEquals(content, blob.getContent()); } @Test @@ -179,21 +181,21 @@ public void testContentWithDecryptionKey() throws Exception { initializeExpectedBlob(2); byte[] content = {1, 2}; expect(storage.options()).andReturn(mockOptions); - expect(storage.readAllBytes(BLOB_INFO.blobId(), + expect(storage.readAllBytes(BLOB_INFO.getBlobId(), Storage.BlobSourceOption.decryptionKey(BASE64_KEY))) .andReturn(content).times(2); replay(storage); initializeBlob(); - assertArrayEquals(content, blob.content(BlobSourceOption.decryptionKey(BASE64_KEY))); - assertArrayEquals(content, blob.content(BlobSourceOption.decryptionKey(KEY))); + assertArrayEquals(content, blob.getContent(BlobSourceOption.decryptionKey(BASE64_KEY))); + assertArrayEquals(content, blob.getContent(BlobSourceOption.decryptionKey(KEY))); } @Test public void testReload() throws Exception { initializeExpectedBlob(2); - Blob expectedReloadedBlob = expectedBlob.toBuilder().cacheControl("c").build(); + Blob expectedReloadedBlob = expectedBlob.toBuilder().setCacheControl("c").build(); expect(storage.options()).andReturn(mockOptions); - expect(storage.get(BLOB_INFO.blobId(), new Storage.BlobGetOption[0])) + expect(storage.get(BLOB_INFO.getBlobId(), new Storage.BlobGetOption[0])) .andReturn(expectedReloadedBlob); replay(storage); initializeBlob(); @@ -205,7 +207,7 @@ public void testReload() throws Exception { public void testReloadNull() throws Exception { initializeExpectedBlob(1); expect(storage.options()).andReturn(mockOptions); - expect(storage.get(BLOB_INFO.blobId(), new Storage.BlobGetOption[0])).andReturn(null); + expect(storage.get(BLOB_INFO.getBlobId(), new Storage.BlobGetOption[0])).andReturn(null); replay(storage); initializeBlob(); Blob reloadedBlob = blob.reload(); @@ -215,10 +217,10 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedBlob(2); - Blob expectedReloadedBlob = expectedBlob.toBuilder().cacheControl("c").build(); + Blob expectedReloadedBlob = expectedBlob.toBuilder().setCacheControl("c").build(); Storage.BlobGetOption[] options = {Storage.BlobGetOption.metagenerationMatch(42L)}; expect(storage.options()).andReturn(mockOptions); - expect(storage.get(BLOB_INFO.blobId(), options)).andReturn(expectedReloadedBlob); + expect(storage.get(BLOB_INFO.getBlobId(), options)).andReturn(expectedReloadedBlob); replay(storage); initializeBlob(); Blob updatedBlob = blob.reload(BlobSourceOption.metagenerationMatch()); @@ -228,7 +230,7 @@ public void testReloadWithOptions() throws Exception { @Test public void testUpdate() throws Exception { initializeExpectedBlob(2); - Blob expectedUpdatedBlob = expectedBlob.toBuilder().cacheControl("c").build(); + Blob expectedUpdatedBlob = expectedBlob.toBuilder().setCacheControl("c").build(); expect(storage.options()).andReturn(mockOptions).times(2); expect(storage.update(eq(expectedUpdatedBlob), new Storage.BlobTargetOption[0])) .andReturn(expectedUpdatedBlob); @@ -243,7 +245,7 @@ public void testUpdate() throws Exception { public void testDelete() throws Exception { initializeExpectedBlob(2); expect(storage.options()).andReturn(mockOptions); - expect(storage.delete(BLOB_INFO.blobId(), new Storage.BlobSourceOption[0])).andReturn(true); + expect(storage.delete(BLOB_INFO.getBlobId(), new Storage.BlobSourceOption[0])).andReturn(true); replay(storage); initializeBlob(); assertTrue(blob.delete()); @@ -252,7 +254,7 @@ public void testDelete() throws Exception { @Test public void testCopyToBucket() throws Exception { initializeExpectedBlob(2); - BlobInfo target = BlobInfo.builder(BlobId.of("bt", "n")).build(); + BlobInfo target = BlobInfo.newBuilder(BlobId.of("bt", "n")).build(); CopyWriter copyWriter = createMock(CopyWriter.class); Capture capturedCopyRequest = Capture.newInstance(); expect(storage.options()).andReturn(mockOptions); @@ -261,17 +263,17 @@ public void testCopyToBucket() throws Exception { initializeBlob(); CopyWriter returnedCopyWriter = blob.copyTo("bt"); assertEquals(copyWriter, returnedCopyWriter); - assertEquals(capturedCopyRequest.getValue().source(), blob.blobId()); - assertEquals(capturedCopyRequest.getValue().target(), target); + assertEquals(capturedCopyRequest.getValue().getSource(), blob.getBlobId()); + assertEquals(capturedCopyRequest.getValue().getTarget(), target); assertFalse(capturedCopyRequest.getValue().overrideInfo()); - assertTrue(capturedCopyRequest.getValue().sourceOptions().isEmpty()); - assertTrue(capturedCopyRequest.getValue().targetOptions().isEmpty()); + assertTrue(capturedCopyRequest.getValue().getSourceOptions().isEmpty()); + assertTrue(capturedCopyRequest.getValue().getTargetOptions().isEmpty()); } @Test public void testCopyTo() throws Exception { initializeExpectedBlob(2); - BlobInfo target = BlobInfo.builder(BlobId.of("bt", "nt")).build(); + BlobInfo target = BlobInfo.newBuilder(BlobId.of("bt", "nt")).build(); CopyWriter copyWriter = createMock(CopyWriter.class); Capture capturedCopyRequest = Capture.newInstance(); expect(storage.options()).andReturn(mockOptions); @@ -280,17 +282,17 @@ public void testCopyTo() throws Exception { initializeBlob(); CopyWriter returnedCopyWriter = blob.copyTo("bt", "nt"); assertEquals(copyWriter, returnedCopyWriter); - assertEquals(capturedCopyRequest.getValue().source(), blob.blobId()); - assertEquals(capturedCopyRequest.getValue().target(), target); + assertEquals(capturedCopyRequest.getValue().getSource(), blob.getBlobId()); + assertEquals(capturedCopyRequest.getValue().getTarget(), target); assertFalse(capturedCopyRequest.getValue().overrideInfo()); - assertTrue(capturedCopyRequest.getValue().sourceOptions().isEmpty()); - assertTrue(capturedCopyRequest.getValue().targetOptions().isEmpty()); + assertTrue(capturedCopyRequest.getValue().getSourceOptions().isEmpty()); + assertTrue(capturedCopyRequest.getValue().getTargetOptions().isEmpty()); } @Test public void testCopyToBlobId() throws Exception { initializeExpectedBlob(2); - BlobInfo target = BlobInfo.builder(BlobId.of("bt", "nt")).build(); + BlobInfo target = BlobInfo.newBuilder(BlobId.of("bt", "nt")).build(); BlobId targetId = BlobId.of("bt", "nt"); CopyWriter copyWriter = createMock(CopyWriter.class); Capture capturedCopyRequest = Capture.newInstance(); @@ -300,11 +302,11 @@ public void testCopyToBlobId() throws Exception { initializeBlob(); CopyWriter returnedCopyWriter = blob.copyTo(targetId); assertEquals(copyWriter, returnedCopyWriter); - assertEquals(capturedCopyRequest.getValue().source(), blob.blobId()); - assertEquals(capturedCopyRequest.getValue().target(), target); + assertEquals(capturedCopyRequest.getValue().getSource(), blob.getBlobId()); + assertEquals(capturedCopyRequest.getValue().getTarget(), target); assertFalse(capturedCopyRequest.getValue().overrideInfo()); - assertTrue(capturedCopyRequest.getValue().sourceOptions().isEmpty()); - assertTrue(capturedCopyRequest.getValue().targetOptions().isEmpty()); + assertTrue(capturedCopyRequest.getValue().getSourceOptions().isEmpty()); + assertTrue(capturedCopyRequest.getValue().getTargetOptions().isEmpty()); } @Test @@ -312,7 +314,7 @@ public void testReader() throws Exception { initializeExpectedBlob(2); ReadChannel channel = createMock(ReadChannel.class); expect(storage.options()).andReturn(mockOptions); - expect(storage.reader(BLOB_INFO.blobId())).andReturn(channel); + expect(storage.reader(BLOB_INFO.getBlobId())).andReturn(channel); replay(storage); initializeBlob(); assertSame(channel, blob.reader()); @@ -323,7 +325,7 @@ public void testReaderWithDecryptionKey() throws Exception { initializeExpectedBlob(2); ReadChannel channel = createMock(ReadChannel.class); expect(storage.options()).andReturn(mockOptions); - expect(storage.reader(BLOB_INFO.blobId(), Storage.BlobSourceOption.decryptionKey(BASE64_KEY))) + expect(storage.reader(BLOB_INFO.getBlobId(), Storage.BlobSourceOption.decryptionKey(BASE64_KEY))) .andReturn(channel).times(2); replay(storage); initializeBlob(); @@ -370,7 +372,7 @@ public void testSignUrl() throws Exception { public void testGetAcl() throws Exception { initializeExpectedBlob(1); expect(storage.options()).andReturn(mockOptions); - expect(storage.getAcl(BLOB_INFO.blobId(), User.ofAllAuthenticatedUsers())).andReturn(ACL); + expect(storage.getAcl(BLOB_INFO.getBlobId(), User.ofAllAuthenticatedUsers())).andReturn(ACL); replay(storage); initializeBlob(); assertEquals(ACL, blob.getAcl(User.ofAllAuthenticatedUsers())); @@ -380,7 +382,7 @@ public void testGetAcl() throws Exception { public void testDeleteAcl() throws Exception { initializeExpectedBlob(1); expect(storage.options()).andReturn(mockOptions); - expect(storage.deleteAcl(BLOB_INFO.blobId(), User.ofAllAuthenticatedUsers())).andReturn(true); + expect(storage.deleteAcl(BLOB_INFO.getBlobId(), User.ofAllAuthenticatedUsers())).andReturn(true); replay(storage); initializeBlob(); assertTrue(blob.deleteAcl(User.ofAllAuthenticatedUsers())); @@ -390,8 +392,8 @@ public void testDeleteAcl() throws Exception { public void testCreateAcl() throws Exception { initializeExpectedBlob(1); expect(storage.options()).andReturn(mockOptions); - Acl returnedAcl = ACL.toBuilder().etag("ETAG").id("ID").build(); - expect(storage.createAcl(BLOB_INFO.blobId(), ACL)).andReturn(returnedAcl); + Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); + expect(storage.createAcl(BLOB_INFO.getBlobId(), ACL)).andReturn(returnedAcl); replay(storage); initializeBlob(); assertEquals(returnedAcl, blob.createAcl(ACL)); @@ -401,8 +403,8 @@ public void testCreateAcl() throws Exception { public void testUpdateAcl() throws Exception { initializeExpectedBlob(1); expect(storage.options()).andReturn(mockOptions); - Acl returnedAcl = ACL.toBuilder().etag("ETAG").id("ID").build(); - expect(storage.updateAcl(BLOB_INFO.blobId(), ACL)).andReturn(returnedAcl); + Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); + expect(storage.updateAcl(BLOB_INFO.getBlobId(), ACL)).andReturn(returnedAcl); replay(storage); initializeBlob(); assertEquals(returnedAcl, blob.updateAcl(ACL)); @@ -412,7 +414,7 @@ public void testUpdateAcl() throws Exception { public void testListAcls() throws Exception { initializeExpectedBlob(1); expect(storage.options()).andReturn(mockOptions); - expect(storage.listAcls(BLOB_INFO.blobId())).andReturn(ACLS); + expect(storage.listAcls(BLOB_INFO.getBlobId())).andReturn(ACLS); replay(storage); initializeBlob(); assertEquals(ACLS, blob.listAcls()); @@ -433,30 +435,114 @@ public void testToBuilder() { @Test public void testBuilder() { initializeExpectedBlob(4); - expect(storage.options()).andReturn(mockOptions).times(4); + expect(storage.options()).andReturn(mockOptions).times(6); + replay(storage); + Blob.Builder builder = new Blob.Builder(new Blob(storage, new BlobInfo.BuilderImpl(BLOB_INFO))); + Blob blob = builder.setAcl(ACLS) + .setComponentCount(COMPONENT_COUNT) + .setContentType(CONTENT_TYPE) + .setCacheControl(CACHE_CONTROL) + .setContentDisposition(CONTENT_DISPOSITION) + .setContentEncoding(CONTENT_ENCODING) + .setContentLanguage(CONTENT_LANGUAGE) + .setCrc32c(CRC32) + .setCreateTime(CREATE_TIME) + .setCustomerEncryption(CUSTOMER_ENCRYPTION) + .setDeleteTime(DELETE_TIME) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setMd5(MD5) + .setMediaLink(MEDIA_LINK) + .setMetadata(METADATA) + .setMetageneration(META_GENERATION) + .setOwner(OWNER) + .setSelfLink(SELF_LINK) + .setSize(SIZE) + .setUpdateTime(UPDATE_TIME) + .build(); + assertEquals("b", blob.getBucket()); + assertEquals("n", blob.getName()); + assertEquals(ACLS, blob.getAcl()); + assertEquals(COMPONENT_COUNT, blob.getComponentCount()); + assertEquals(CONTENT_TYPE, blob.getContentType()); + assertEquals(CACHE_CONTROL, blob.getCacheControl()); + assertEquals(CONTENT_DISPOSITION, blob.getContentDisposition()); + assertEquals(CONTENT_ENCODING, blob.getContentEncoding()); + assertEquals(CONTENT_LANGUAGE, blob.getContentLanguage()); + assertEquals(CRC32, blob.getCrc32c()); + assertEquals(CREATE_TIME, blob.getCreateTime()); + assertEquals(CUSTOMER_ENCRYPTION, blob.getCustomerEncryption()); + assertEquals(DELETE_TIME, blob.getDeleteTime()); + assertEquals(ETAG, blob.getEtag()); + assertEquals(GENERATED_ID, blob.getGeneratedId()); + assertEquals(MD5, blob.getMd5()); + assertEquals(MEDIA_LINK, blob.getMediaLink()); + assertEquals(METADATA, blob.getMetadata()); + assertEquals(META_GENERATION, blob.getMetageneration()); + assertEquals(OWNER, blob.getOwner()); + assertEquals(SELF_LINK, blob.getSelfLink()); + assertEquals(SIZE, blob.getSize()); + assertEquals(UPDATE_TIME, blob.getUpdateTime()); + assertEquals(storage.options(), blob.getStorage().options()); + assertFalse(blob.isDirectory()); + builder = new Blob.Builder(new Blob(storage, new BlobInfo.BuilderImpl(DIRECTORY_INFO))); + blob = builder.setBlobId(BlobId.of("b", "n/")) + .setIsDirectory(true) + .setSize(0L) + .build(); + assertEquals("b", blob.getBucket()); + assertEquals("n/", blob.getName()); + assertNull(blob.getAcl()); + assertNull(blob.getComponentCount()); + assertNull(blob.getContentType()); + assertNull(blob.getCacheControl()); + assertNull(blob.getContentDisposition()); + assertNull(blob.getContentEncoding()); + assertNull(blob.getContentLanguage()); + assertNull(blob.getCrc32c()); + assertNull(blob.getCreateTime()); + assertNull(blob.getCustomerEncryption()); + assertNull(blob.getDeleteTime()); + assertNull(blob.getEtag()); + assertNull(blob.getGeneratedId()); + assertNull(blob.getMd5()); + assertNull(blob.getMediaLink()); + assertNull(blob.getMetadata()); + assertNull(blob.getMetageneration()); + assertNull(blob.getOwner()); + assertNull(blob.getSelfLink()); + assertEquals(0L, (long) blob.getSize()); + assertNull(blob.getUpdateTime()); + assertTrue(blob.isDirectory()); + } + + @Test + public void testBuilderDeprecated() { + initializeExpectedBlob(4); + expect(storage.options()).andReturn(mockOptions).times(6); replay(storage); Blob.Builder builder = new Blob.Builder(new Blob(storage, new BlobInfo.BuilderImpl(BLOB_INFO))); Blob blob = builder.acl(ACLS) - .componentCount(COMPONENT_COUNT) + .setComponentCount(COMPONENT_COUNT) .contentType(CONTENT_TYPE) .cacheControl(CACHE_CONTROL) .contentDisposition(CONTENT_DISPOSITION) .contentEncoding(CONTENT_ENCODING) .contentLanguage(CONTENT_LANGUAGE) .crc32c(CRC32) - .createTime(CREATE_TIME) - .customerEncryption(CUSTOMER_ENCRYPTION) - .deleteTime(DELETE_TIME) - .etag(ETAG) - .generatedId(GENERATED_ID) + .setCreateTime(CREATE_TIME) + .setCustomerEncryption(CUSTOMER_ENCRYPTION) + .setDeleteTime(DELETE_TIME) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) .md5(MD5) - .mediaLink(MEDIA_LINK) + .setMediaLink(MEDIA_LINK) .metadata(METADATA) - .metageneration(META_GENERATION) - .owner(OWNER) - .selfLink(SELF_LINK) - .size(SIZE) - .updateTime(UPDATE_TIME) + .setMetageneration(META_GENERATION) + .setOwner(OWNER) + .setSelfLink(SELF_LINK) + .setSize(SIZE) + .setUpdateTime(UPDATE_TIME) .build(); assertEquals("b", blob.bucket()); assertEquals("n", blob.name()); @@ -481,11 +567,12 @@ public void testBuilder() { assertEquals(SELF_LINK, blob.selfLink()); assertEquals(SIZE, blob.size()); assertEquals(UPDATE_TIME, blob.updateTime()); + assertEquals(storage.options(), blob.storage().options()); assertFalse(blob.isDirectory()); builder = new Blob.Builder(new Blob(storage, new BlobInfo.BuilderImpl(DIRECTORY_INFO))); blob = builder.blobId(BlobId.of("b", "n/")) - .isDirectory(true) - .size(0L) + .setIsDirectory(true) + .setSize(0L) .build(); assertEquals("b", blob.bucket()); assertEquals("n/", blob.name()); diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/BucketInfoTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/BucketInfoTest.java index bcb4259ad564..2ccf8283d417 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/BucketInfoTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/BucketInfoTest.java @@ -49,7 +49,7 @@ public class BucketInfoTest { private static final User OWNER = new User("user@gmail.com"); private static final String SELF_LINK = "http://storage/b/n"; private static final Long CREATE_TIME = System.currentTimeMillis(); - private static final List CORS = Collections.singletonList(Cors.builder().build()); + private static final List CORS = Collections.singletonList(Cors.newBuilder().build()); private static final List DEFAULT_ACL = Collections.singletonList(Acl.of(User.ofAllAuthenticatedUsers(), Role.WRITER)); private static final List DELETE_RULES = @@ -59,15 +59,32 @@ public class BucketInfoTest { private static final String LOCATION = "ASIA"; private static final String STORAGE_CLASS = "STANDARD"; private static final Boolean VERSIONING_ENABLED = true; - private static final BucketInfo BUCKET_INFO = BucketInfo.builder("b") + private static final BucketInfo BUCKET_INFO = BucketInfo.newBuilder("b") + .setAcl(ACL) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setMetageneration(META_GENERATION) + .setOwner(OWNER) + .setSelfLink(SELF_LINK) + .setCors(CORS) + .setCreateTime(CREATE_TIME) + .setDefaultAcl(DEFAULT_ACL) + .setDeleteRules(DELETE_RULES) + .setIndexPage(INDEX_PAGE) + .setNotFoundPage(NOT_FOUND_PAGE) + .setLocation(LOCATION) + .setStorageClass(STORAGE_CLASS) + .setVersioningEnabled(VERSIONING_ENABLED) + .build(); + private static final BucketInfo DEPRECATED_BUCKET_INFO = BucketInfo.builder("b") .acl(ACL) - .etag(ETAG) - .generatedId(GENERATED_ID) - .metageneration(META_GENERATION) - .owner(OWNER) - .selfLink(SELF_LINK) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setMetageneration(META_GENERATION) + .setOwner(OWNER) + .setSelfLink(SELF_LINK) .cors(CORS) - .createTime(CREATE_TIME) + .setCreateTime(CREATE_TIME) .defaultAcl(DEFAULT_ACL) .deleteRules(DELETE_RULES) .indexPage(INDEX_PAGE) @@ -80,15 +97,31 @@ public class BucketInfoTest { @Test public void testToBuilder() { compareBuckets(BUCKET_INFO, BUCKET_INFO.toBuilder().build()); - BucketInfo bucketInfo = BUCKET_INFO.toBuilder().name("B").generatedId("id").build(); + BucketInfo bucketInfo = BUCKET_INFO.toBuilder().setName("B").setGeneratedId("id").build(); + assertEquals("B", bucketInfo.getName()); + assertEquals("id", bucketInfo.getGeneratedId()); + bucketInfo = bucketInfo.toBuilder().setName("b").setGeneratedId(GENERATED_ID).build(); + compareBuckets(BUCKET_INFO, bucketInfo); + } + + @Test + public void testToBuilderDeprecated() { + compareBuckets(BUCKET_INFO, BUCKET_INFO.toBuilder().build()); + BucketInfo bucketInfo = BUCKET_INFO.toBuilder().name("B").setGeneratedId("id").build(); assertEquals("B", bucketInfo.name()); assertEquals("id", bucketInfo.generatedId()); - bucketInfo = bucketInfo.toBuilder().name("b").generatedId(GENERATED_ID).build(); + bucketInfo = bucketInfo.toBuilder().name("b").setGeneratedId(GENERATED_ID).build(); compareBuckets(BUCKET_INFO, bucketInfo); } @Test public void testToBuilderIncomplete() { + BucketInfo incompleteBucketInfo = BucketInfo.newBuilder("b").build(); + compareBuckets(incompleteBucketInfo, incompleteBucketInfo.toBuilder().build()); + } + + @Test + public void testToBuilderIncompleteDeprecated() { BucketInfo incompleteBucketInfo = BucketInfo.builder("b").build(); compareBuckets(incompleteBucketInfo, incompleteBucketInfo.toBuilder().build()); } @@ -96,29 +129,49 @@ public void testToBuilderIncomplete() { @Test public void testOf() { BucketInfo bucketInfo = BucketInfo.of("bucket"); - assertEquals("bucket", bucketInfo.name()); + assertEquals("bucket", bucketInfo.getName()); } @Test public void testBuilder() { - assertEquals("b", BUCKET_INFO.name()); - assertEquals(ACL, BUCKET_INFO.acl()); - assertEquals(ETAG, BUCKET_INFO.etag()); - assertEquals(GENERATED_ID, BUCKET_INFO.generatedId()); - assertEquals(META_GENERATION, BUCKET_INFO.metageneration()); - assertEquals(OWNER, BUCKET_INFO.owner()); - assertEquals(SELF_LINK, BUCKET_INFO.selfLink()); - assertEquals(CREATE_TIME, BUCKET_INFO.createTime()); - assertEquals(CORS, BUCKET_INFO.cors()); - assertEquals(DEFAULT_ACL, BUCKET_INFO.defaultAcl()); - assertEquals(DELETE_RULES, BUCKET_INFO.deleteRules()); - assertEquals(INDEX_PAGE, BUCKET_INFO.indexPage()); - assertEquals(NOT_FOUND_PAGE, BUCKET_INFO.notFoundPage()); - assertEquals(LOCATION, BUCKET_INFO.location()); - assertEquals(STORAGE_CLASS, BUCKET_INFO.storageClass()); + assertEquals("b", BUCKET_INFO.getName()); + assertEquals(ACL, BUCKET_INFO.getAcl()); + assertEquals(ETAG, BUCKET_INFO.getEtag()); + assertEquals(GENERATED_ID, BUCKET_INFO.getGeneratedId()); + assertEquals(META_GENERATION, BUCKET_INFO.getMetageneration()); + assertEquals(OWNER, BUCKET_INFO.getOwner()); + assertEquals(SELF_LINK, BUCKET_INFO.getSelfLink()); + assertEquals(CREATE_TIME, BUCKET_INFO.getCreateTime()); + assertEquals(CORS, BUCKET_INFO.getCors()); + assertEquals(DEFAULT_ACL, BUCKET_INFO.getDefaultAcl()); + assertEquals(DELETE_RULES, BUCKET_INFO.getDeleteRules()); + assertEquals(INDEX_PAGE, BUCKET_INFO.getIndexPage()); + assertEquals(NOT_FOUND_PAGE, BUCKET_INFO.getNotFoundPage()); + assertEquals(LOCATION, BUCKET_INFO.getLocation()); + assertEquals(STORAGE_CLASS, BUCKET_INFO.getStorageClass()); assertEquals(VERSIONING_ENABLED, BUCKET_INFO.versioningEnabled()); } + @Test + public void testBuilderDeprecated() { + assertEquals("b", DEPRECATED_BUCKET_INFO.name()); + assertEquals(ACL, DEPRECATED_BUCKET_INFO.acl()); + assertEquals(ETAG, DEPRECATED_BUCKET_INFO.etag()); + assertEquals(GENERATED_ID, DEPRECATED_BUCKET_INFO.generatedId()); + assertEquals(META_GENERATION, DEPRECATED_BUCKET_INFO.metageneration()); + assertEquals(OWNER, DEPRECATED_BUCKET_INFO.owner()); + assertEquals(SELF_LINK, DEPRECATED_BUCKET_INFO.selfLink()); + assertEquals(CREATE_TIME, DEPRECATED_BUCKET_INFO.createTime()); + assertEquals(CORS, DEPRECATED_BUCKET_INFO.cors()); + assertEquals(DEFAULT_ACL, DEPRECATED_BUCKET_INFO.defaultAcl()); + assertEquals(DELETE_RULES, DEPRECATED_BUCKET_INFO.deleteRules()); + assertEquals(INDEX_PAGE, DEPRECATED_BUCKET_INFO.indexPage()); + assertEquals(NOT_FOUND_PAGE, DEPRECATED_BUCKET_INFO.notFoundPage()); + assertEquals(LOCATION, DEPRECATED_BUCKET_INFO.location()); + assertEquals(STORAGE_CLASS, DEPRECATED_BUCKET_INFO.storageClass()); + assertEquals(VERSIONING_ENABLED, DEPRECATED_BUCKET_INFO.versioningEnabled()); + } + @Test public void testToPbAndFromPb() { compareBuckets(BUCKET_INFO, BucketInfo.fromPb(BUCKET_INFO.toPb())); @@ -128,41 +181,77 @@ public void testToPbAndFromPb() { private void compareBuckets(BucketInfo expected, BucketInfo value) { assertEquals(expected, value); - assertEquals(expected.name(), value.name()); - assertEquals(expected.acl(), value.acl()); - assertEquals(expected.etag(), value.etag()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.metageneration(), value.metageneration()); - assertEquals(expected.owner(), value.owner()); - assertEquals(expected.selfLink(), value.selfLink()); - assertEquals(expected.createTime(), value.createTime()); - assertEquals(expected.cors(), value.cors()); - assertEquals(expected.defaultAcl(), value.defaultAcl()); - assertEquals(expected.deleteRules(), value.deleteRules()); - assertEquals(expected.indexPage(), value.indexPage()); - assertEquals(expected.notFoundPage(), value.notFoundPage()); - assertEquals(expected.location(), value.location()); - assertEquals(expected.storageClass(), value.storageClass()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getAcl(), value.getAcl()); + assertEquals(expected.getEtag(), value.getEtag()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getMetageneration(), value.getMetageneration()); + assertEquals(expected.getOwner(), value.getOwner()); + assertEquals(expected.getSelfLink(), value.getSelfLink()); + assertEquals(expected.getCreateTime(), value.getCreateTime()); + assertEquals(expected.getCors(), value.getCors()); + assertEquals(expected.getDefaultAcl(), value.getDefaultAcl()); + assertEquals(expected.getDeleteRules(), value.getDeleteRules()); + assertEquals(expected.getIndexPage(), value.getIndexPage()); + assertEquals(expected.getNotFoundPage(), value.getNotFoundPage()); + assertEquals(expected.getLocation(), value.getLocation()); + assertEquals(expected.getStorageClass(), value.getStorageClass()); assertEquals(expected.versioningEnabled(), value.versioningEnabled()); } @Test public void testDeleteRules() { + AgeDeleteRule ageRule = new AgeDeleteRule(10); + assertEquals(10, ageRule.getDaysToLive()); + assertEquals(10, ageRule.getDaysToLive()); + assertEquals(Type.AGE, ageRule.getType()); + assertEquals(Type.AGE, ageRule.getType()); + CreatedBeforeDeleteRule createBeforeRule = new CreatedBeforeDeleteRule(1); + assertEquals(1, createBeforeRule.getTimeMillis()); + assertEquals(1, createBeforeRule.getTimeMillis()); + assertEquals(Type.CREATE_BEFORE, createBeforeRule.getType()); + NumNewerVersionsDeleteRule versionsRule = new NumNewerVersionsDeleteRule(2); + assertEquals(2, versionsRule.getNumNewerVersions()); + assertEquals(2, versionsRule.getNumNewerVersions()); + assertEquals(Type.NUM_NEWER_VERSIONS, versionsRule.getType()); + IsLiveDeleteRule isLiveRule = new IsLiveDeleteRule(true); + assertTrue(isLiveRule.isLive()); + assertEquals(Type.IS_LIVE, isLiveRule.getType()); + assertEquals(Type.IS_LIVE, isLiveRule.getType()); + Rule rule = new Rule().set("a", "b"); + RawDeleteRule rawRule = new RawDeleteRule(rule); + assertEquals(Type.IS_LIVE, isLiveRule.getType()); + assertEquals(Type.IS_LIVE, isLiveRule.getType()); + ImmutableList rules = ImmutableList + .of(ageRule, createBeforeRule, versionsRule, isLiveRule, rawRule); + for (DeleteRule delRule : rules) { + assertEquals(delRule, DeleteRule.fromPb(delRule.toPb())); + } + } + + @Test + public void testDeleteRulesDeprecated() { AgeDeleteRule ageRule = new AgeDeleteRule(10); assertEquals(10, ageRule.daysToLive()); + assertEquals(10, ageRule.getDaysToLive()); assertEquals(Type.AGE, ageRule.type()); + assertEquals(Type.AGE, ageRule.getType()); CreatedBeforeDeleteRule createBeforeRule = new CreatedBeforeDeleteRule(1); assertEquals(1, createBeforeRule.timeMillis()); + assertEquals(1, createBeforeRule.getTimeMillis()); assertEquals(Type.CREATE_BEFORE, createBeforeRule.type()); NumNewerVersionsDeleteRule versionsRule = new NumNewerVersionsDeleteRule(2); assertEquals(2, versionsRule.numNewerVersions()); + assertEquals(2, versionsRule.getNumNewerVersions()); assertEquals(Type.NUM_NEWER_VERSIONS, versionsRule.type()); IsLiveDeleteRule isLiveRule = new IsLiveDeleteRule(true); assertTrue(isLiveRule.isLive()); assertEquals(Type.IS_LIVE, isLiveRule.type()); + assertEquals(Type.IS_LIVE, isLiveRule.getType()); Rule rule = new Rule().set("a", "b"); RawDeleteRule rawRule = new RawDeleteRule(rule); - assertEquals(Type.UNKNOWN, rawRule.type()); + assertEquals(Type.IS_LIVE, isLiveRule.type()); + assertEquals(Type.IS_LIVE, isLiveRule.getType()); ImmutableList rules = ImmutableList .of(ageRule, createBeforeRule, versionsRule, isLiveRule, rawRule); for (DeleteRule delRule : rules) { diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/BucketTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/BucketTest.java index ce1aa90bf869..e80339e36f52 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/BucketTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/BucketTest.java @@ -66,7 +66,7 @@ public class BucketTest { private static final User OWNER = new User("user@gmail.com"); private static final String SELF_LINK = "http://storage/b/n"; private static final Long CREATE_TIME = System.currentTimeMillis(); - private static final List CORS = Collections.singletonList(Cors.builder().build()); + private static final List CORS = Collections.singletonList(Cors.newBuilder().build()); private static final List DEFAULT_ACL = Collections.singletonList(Acl.of(User.ofAllAuthenticatedUsers(), WRITER)); private static final List DELETE_RULES = @@ -76,24 +76,25 @@ public class BucketTest { private static final String LOCATION = "ASIA"; private static final String STORAGE_CLASS = "STANDARD"; private static final Boolean VERSIONING_ENABLED = true; - private static final BucketInfo FULL_BUCKET_INFO = BucketInfo.builder("b") - .acl(ACLS) - .etag(ETAG) - .generatedId(GENERATED_ID) - .metageneration(META_GENERATION) - .owner(OWNER) - .selfLink(SELF_LINK) - .cors(CORS) - .createTime(CREATE_TIME) - .defaultAcl(DEFAULT_ACL) - .deleteRules(DELETE_RULES) - .indexPage(INDEX_PAGE) - .notFoundPage(NOT_FOUND_PAGE) - .location(LOCATION) - .storageClass(STORAGE_CLASS) - .versioningEnabled(VERSIONING_ENABLED) + private static final BucketInfo FULL_BUCKET_INFO = BucketInfo.newBuilder("b") + .setAcl(ACLS) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setMetageneration(META_GENERATION) + .setOwner(OWNER) + .setSelfLink(SELF_LINK) + .setCors(CORS) + .setCreateTime(CREATE_TIME) + .setDefaultAcl(DEFAULT_ACL) + .setDeleteRules(DELETE_RULES) + .setIndexPage(INDEX_PAGE) + .setNotFoundPage(NOT_FOUND_PAGE) + .setLocation(LOCATION) + .setStorageClass(STORAGE_CLASS) + .setVersioningEnabled(VERSIONING_ENABLED) .build(); - private static final BucketInfo BUCKET_INFO = BucketInfo.builder("b").metageneration(42L).build(); + private static final BucketInfo BUCKET_INFO = + BucketInfo.newBuilder("b").setMetageneration(42L).build(); private static final String CONTENT_TYPE = "text/plain"; private static final String BASE64_KEY = "JVzfVl8NLD9FjedFuStegjRfES5ll5zc59CIXw572OA="; private static final Key KEY = @@ -125,11 +126,11 @@ private void initializeExpectedBucket(int optionsCalls) { expectedBucket = new Bucket(serviceMockReturnsOptions, new BucketInfo.BuilderImpl(BUCKET_INFO)); blobResults = ImmutableList.of( new Blob(serviceMockReturnsOptions, - new BlobInfo.BuilderImpl(BlobInfo.builder("b", "n1").build())), + new BlobInfo.BuilderImpl(BlobInfo.newBuilder("b", "n1").build())), new Blob(serviceMockReturnsOptions, - new BlobInfo.BuilderImpl(BlobInfo.builder("b", "n2").build())), + new BlobInfo.BuilderImpl(BlobInfo.newBuilder("b", "n2").build())), new Blob(serviceMockReturnsOptions, - new BlobInfo.BuilderImpl(BlobInfo.builder("b", "n3").build()))); + new BlobInfo.BuilderImpl(BlobInfo.newBuilder("b", "n3").build()))); } private void initializeBucket() { @@ -141,7 +142,7 @@ public void testExists_True() throws Exception { initializeExpectedBucket(4); Storage.BucketGetOption[] expectedOptions = {Storage.BucketGetOption.fields()}; expect(storage.options()).andReturn(mockOptions); - expect(storage.get(BUCKET_INFO.name(), expectedOptions)).andReturn(expectedBucket); + expect(storage.get(BUCKET_INFO.getName(), expectedOptions)).andReturn(expectedBucket); replay(storage); initializeBucket(); assertTrue(bucket.exists()); @@ -152,7 +153,7 @@ public void testExists_False() throws Exception { initializeExpectedBucket(4); Storage.BucketGetOption[] expectedOptions = {Storage.BucketGetOption.fields()}; expect(storage.options()).andReturn(mockOptions); - expect(storage.get(BUCKET_INFO.name(), expectedOptions)).andReturn(null); + expect(storage.get(BUCKET_INFO.getName(), expectedOptions)).andReturn(null); replay(storage); initializeBucket(); assertFalse(bucket.exists()); @@ -161,11 +162,11 @@ public void testExists_False() throws Exception { @Test public void testReload() throws Exception { initializeExpectedBucket(5); - BucketInfo updatedInfo = BUCKET_INFO.toBuilder().notFoundPage("p").build(); + BucketInfo updatedInfo = BUCKET_INFO.toBuilder().setNotFoundPage("p").build(); Bucket expectedUpdatedBucket = new Bucket(serviceMockReturnsOptions, new BucketInfo.BuilderImpl(updatedInfo)); expect(storage.options()).andReturn(mockOptions); - expect(storage.get(updatedInfo.name())).andReturn(expectedUpdatedBucket); + expect(storage.get(updatedInfo.getName())).andReturn(expectedUpdatedBucket); replay(storage); initializeBucket(); Bucket updatedBucket = bucket.reload(); @@ -176,7 +177,7 @@ public void testReload() throws Exception { public void testReloadNull() throws Exception { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions); - expect(storage.get(BUCKET_INFO.name())).andReturn(null); + expect(storage.get(BUCKET_INFO.getName())).andReturn(null); replay(storage); initializeBucket(); assertNull(bucket.reload()); @@ -185,11 +186,11 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedBucket(5); - BucketInfo updatedInfo = BUCKET_INFO.toBuilder().notFoundPage("p").build(); + BucketInfo updatedInfo = BUCKET_INFO.toBuilder().setNotFoundPage("p").build(); Bucket expectedUpdatedBucket = new Bucket(serviceMockReturnsOptions, new BucketInfo.BuilderImpl(updatedInfo)); expect(storage.options()).andReturn(mockOptions); - expect(storage.get(updatedInfo.name(), Storage.BucketGetOption.metagenerationMatch(42L))) + expect(storage.get(updatedInfo.getName(), Storage.BucketGetOption.metagenerationMatch(42L))) .andReturn(expectedUpdatedBucket); replay(storage); initializeBucket(); @@ -200,7 +201,7 @@ public void testReloadWithOptions() throws Exception { @Test public void testUpdate() throws Exception { initializeExpectedBucket(5); - Bucket expectedUpdatedBucket = expectedBucket.toBuilder().notFoundPage("p").build(); + Bucket expectedUpdatedBucket = expectedBucket.toBuilder().setNotFoundPage("p").build(); expect(storage.options()).andReturn(mockOptions).times(2); expect(storage.update(expectedUpdatedBucket)).andReturn(expectedUpdatedBucket); replay(storage); @@ -214,7 +215,7 @@ public void testUpdate() throws Exception { public void testDelete() throws Exception { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions); - expect(storage.delete(BUCKET_INFO.name())).andReturn(true); + expect(storage.delete(BUCKET_INFO.getName())).andReturn(true); replay(storage); initializeBucket(); assertTrue(bucket.delete()); @@ -225,7 +226,7 @@ public void testList() throws Exception { initializeExpectedBucket(4); PageImpl expectedBlobPage = new PageImpl<>(null, "c", blobResults); expect(storage.options()).andReturn(mockOptions); - expect(storage.list(BUCKET_INFO.name())).andReturn(expectedBlobPage); + expect(storage.list(BUCKET_INFO.getName())).andReturn(expectedBlobPage); replay(storage); initializeBucket(); Page blobPage = bucket.list(); @@ -243,9 +244,9 @@ public void testList() throws Exception { public void testGet() throws Exception { initializeExpectedBucket(5); Blob expectedBlob = new Blob( - serviceMockReturnsOptions, new BlobInfo.BuilderImpl(BlobInfo.builder("b", "n").build())); + serviceMockReturnsOptions, new BlobInfo.BuilderImpl(BlobInfo.newBuilder("b", "n").build())); expect(storage.options()).andReturn(mockOptions); - expect(storage.get(BlobId.of(expectedBucket.name(), "n"), new Storage.BlobGetOption[0])) + expect(storage.get(BlobId.of(expectedBucket.getName(), "n"), new Storage.BlobGetOption[0])) .andReturn(expectedBlob); replay(storage); initializeBucket(); @@ -260,7 +261,7 @@ public void testGetAllArray() throws Exception { List blobIds = Lists.transform(blobResults, new Function() { @Override public BlobId apply(Blob blob) { - return blob.blobId(); + return blob.getBlobId(); } }); expect(storage.get(blobIds)).andReturn(blobResults); @@ -276,7 +277,7 @@ public void testGetAllIterable() throws Exception { List blobIds = Lists.transform(blobResults, new Function() { @Override public BlobId apply(Blob blob) { - return blob.blobId(); + return blob.getBlobId(); } }); expect(storage.get(blobIds)).andReturn(blobResults); @@ -288,7 +289,7 @@ public BlobId apply(Blob blob) { @Test public void testCreate() throws Exception { initializeExpectedBucket(5); - BlobInfo info = BlobInfo.builder("b", "n").contentType(CONTENT_TYPE).build(); + BlobInfo info = BlobInfo.newBuilder("b", "n").setContentType(CONTENT_TYPE).build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; expect(storage.options()).andReturn(mockOptions); @@ -302,7 +303,7 @@ public void testCreate() throws Exception { @Test public void testCreateNoContentType() throws Exception { initializeExpectedBucket(5); - BlobInfo info = BlobInfo.builder("b", "n").build(); + BlobInfo info = BlobInfo.newBuilder("b", "n").build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; expect(storage.options()).andReturn(mockOptions); @@ -316,9 +317,9 @@ public void testCreateNoContentType() throws Exception { @Test public void testCreateWithOptions() throws Exception { initializeExpectedBucket(5); - BlobInfo info = BlobInfo.builder(BlobId.of("b", "n", 42L)) - .contentType(CONTENT_TYPE) - .metageneration(24L) + BlobInfo info = BlobInfo.newBuilder(BlobId.of("b", "n", 42L)) + .setContentType(CONTENT_TYPE) + .setMetageneration(24L) .build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; @@ -341,7 +342,7 @@ public void testCreateWithOptions() throws Exception { @Test public void testCreateWithEncryptionKey() throws Exception { initializeExpectedBucket(5); - BlobInfo info = BlobInfo.builder(BlobId.of("b", "n")).contentType(CONTENT_TYPE).build(); + BlobInfo info = BlobInfo.newBuilder(BlobId.of("b", "n")).setContentType(CONTENT_TYPE).build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; expect(storage.options()).andReturn(mockOptions); @@ -357,7 +358,7 @@ public void testCreateWithEncryptionKey() throws Exception { @Test public void testCreateNotExists() throws Exception { initializeExpectedBucket(5); - BlobInfo info = BlobInfo.builder(BlobId.of("b", "n", 0L)).contentType(CONTENT_TYPE).build(); + BlobInfo info = BlobInfo.newBuilder(BlobId.of("b", "n", 0L)).setContentType(CONTENT_TYPE).build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; expect(storage.options()).andReturn(mockOptions); @@ -400,7 +401,7 @@ public void testCreateWithWrongMetagenerationOptions() throws Exception { @Test public void testCreateFromStream() throws Exception { initializeExpectedBucket(5); - BlobInfo info = BlobInfo.builder("b", "n").contentType(CONTENT_TYPE).build(); + BlobInfo info = BlobInfo.newBuilder("b", "n").setContentType(CONTENT_TYPE).build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; InputStream streamContent = new ByteArrayInputStream(content); @@ -415,7 +416,7 @@ public void testCreateFromStream() throws Exception { @Test public void testCreateFromStreamNoContentType() throws Exception { initializeExpectedBucket(5); - BlobInfo info = BlobInfo.builder("b", "n").build(); + BlobInfo info = BlobInfo.newBuilder("b", "n").build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; InputStream streamContent = new ByteArrayInputStream(content); @@ -430,11 +431,11 @@ public void testCreateFromStreamNoContentType() throws Exception { @Test public void testCreateFromStreamWithOptions() throws Exception { initializeExpectedBucket(5); - BlobInfo info = BlobInfo.builder(BlobId.of("b", "n", 42L)) - .contentType(CONTENT_TYPE) - .metageneration(24L) - .crc32c("crc") - .md5("md5") + BlobInfo info = BlobInfo.newBuilder(BlobId.of("b", "n", 42L)) + .setContentType(CONTENT_TYPE) + .setMetageneration(24L) + .setCrc32c("crc") + .setMd5("md5") .build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; @@ -459,7 +460,7 @@ public void testCreateFromStreamWithOptions() throws Exception { @Test public void testCreateFromStreamWithEncryptionKey() throws Exception { initializeExpectedBucket(5); - BlobInfo info = BlobInfo.builder(BlobId.of("b", "n")).contentType(CONTENT_TYPE).build(); + BlobInfo info = BlobInfo.newBuilder(BlobId.of("b", "n")).setContentType(CONTENT_TYPE).build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; InputStream streamContent = new ByteArrayInputStream(content); @@ -476,7 +477,8 @@ public void testCreateFromStreamWithEncryptionKey() throws Exception { @Test public void testCreateFromStreamNotExists() throws Exception { initializeExpectedBucket(5); - BlobInfo info = BlobInfo.builder(BlobId.of("b", "n", 0L)).contentType(CONTENT_TYPE).build(); + BlobInfo info = + BlobInfo.newBuilder(BlobId.of("b", "n", 0L)).setContentType(CONTENT_TYPE).build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; InputStream streamContent = new ByteArrayInputStream(content); @@ -524,7 +526,7 @@ public void testCreateFromStreamWithWrongMetagenerationOptions() throws Exceptio public void testGetAcl() throws Exception { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions); - expect(storage.getAcl(BUCKET_INFO.name(), User.ofAllAuthenticatedUsers())).andReturn(ACL); + expect(storage.getAcl(BUCKET_INFO.getName(), User.ofAllAuthenticatedUsers())).andReturn(ACL); replay(storage); initializeBucket(); assertEquals(ACL, bucket.getAcl(User.ofAllAuthenticatedUsers())); @@ -534,7 +536,7 @@ public void testGetAcl() throws Exception { public void testDeleteAcl() throws Exception { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions); - expect(storage.deleteAcl(BUCKET_INFO.name(), User.ofAllAuthenticatedUsers())).andReturn(true); + expect(storage.deleteAcl(BUCKET_INFO.getName(), User.ofAllAuthenticatedUsers())).andReturn(true); replay(storage); initializeBucket(); assertTrue(bucket.deleteAcl(User.ofAllAuthenticatedUsers())); @@ -544,8 +546,8 @@ public void testDeleteAcl() throws Exception { public void testCreateAcl() throws Exception { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions); - Acl returnedAcl = ACL.toBuilder().etag("ETAG").id("ID").build(); - expect(storage.createAcl(BUCKET_INFO.name(), ACL)).andReturn(returnedAcl); + Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); + expect(storage.createAcl(BUCKET_INFO.getName(), ACL)).andReturn(returnedAcl); replay(storage); initializeBucket(); assertEquals(returnedAcl, bucket.createAcl(ACL)); @@ -555,8 +557,8 @@ public void testCreateAcl() throws Exception { public void testUpdateAcl() throws Exception { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions); - Acl returnedAcl = ACL.toBuilder().etag("ETAG").id("ID").build(); - expect(storage.updateAcl(BUCKET_INFO.name(), ACL)).andReturn(returnedAcl); + Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); + expect(storage.updateAcl(BUCKET_INFO.getName(), ACL)).andReturn(returnedAcl); replay(storage); initializeBucket(); assertEquals(returnedAcl, bucket.updateAcl(ACL)); @@ -566,7 +568,7 @@ public void testUpdateAcl() throws Exception { public void testListAcls() throws Exception { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions); - expect(storage.listAcls(BUCKET_INFO.name())).andReturn(ACLS); + expect(storage.listAcls(BUCKET_INFO.getName())).andReturn(ACLS); replay(storage); initializeBucket(); assertEquals(ACLS, bucket.listAcls()); @@ -576,7 +578,7 @@ public void testListAcls() throws Exception { public void testGetDefaultAcl() throws Exception { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions); - expect(storage.getDefaultAcl(BUCKET_INFO.name(), User.ofAllAuthenticatedUsers())) + expect(storage.getDefaultAcl(BUCKET_INFO.getName(), User.ofAllAuthenticatedUsers())) .andReturn(ACL); replay(storage); initializeBucket(); @@ -587,7 +589,7 @@ public void testGetDefaultAcl() throws Exception { public void testDeleteDefaultAcl() throws Exception { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions); - expect(storage.deleteDefaultAcl(BUCKET_INFO.name(), User.ofAllAuthenticatedUsers())) + expect(storage.deleteDefaultAcl(BUCKET_INFO.getName(), User.ofAllAuthenticatedUsers())) .andReturn(true); replay(storage); initializeBucket(); @@ -598,8 +600,8 @@ public void testDeleteDefaultAcl() throws Exception { public void testCreateDefaultAcl() throws Exception { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions); - Acl returnedAcl = ACL.toBuilder().etag("ETAG").id("ID").build(); - expect(storage.createDefaultAcl(BUCKET_INFO.name(), ACL)).andReturn(returnedAcl); + Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); + expect(storage.createDefaultAcl(BUCKET_INFO.getName(), ACL)).andReturn(returnedAcl); replay(storage); initializeBucket(); assertEquals(returnedAcl, bucket.createDefaultAcl(ACL)); @@ -609,8 +611,8 @@ public void testCreateDefaultAcl() throws Exception { public void testUpdateDefaultAcl() throws Exception { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions); - Acl returnedAcl = ACL.toBuilder().etag("ETAG").id("ID").build(); - expect(storage.updateDefaultAcl(BUCKET_INFO.name(), ACL)).andReturn(returnedAcl); + Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); + expect(storage.updateDefaultAcl(BUCKET_INFO.getName(), ACL)).andReturn(returnedAcl); replay(storage); initializeBucket(); assertEquals(returnedAcl, bucket.updateDefaultAcl(ACL)); @@ -620,7 +622,7 @@ public void testUpdateDefaultAcl() throws Exception { public void testListDefaultAcls() throws Exception { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions); - expect(storage.listDefaultAcls(BUCKET_INFO.name())).andReturn(ACLS); + expect(storage.listDefaultAcls(BUCKET_INFO.getName())).andReturn(ACLS); replay(storage); initializeBucket(); assertEquals(ACLS, bucket.listDefaultAcls()); @@ -638,19 +640,61 @@ public void testToBuilder() { @Test public void testBuilder() { + initializeExpectedBucket(4); + expect(storage.options()).andReturn(mockOptions).times(4); + replay(storage); + Bucket.Builder builder = + new Bucket.Builder(new Bucket(storage, new BucketInfo.BuilderImpl(BUCKET_INFO))); + Bucket bucket = builder.setAcl(ACLS) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setMetageneration(META_GENERATION) + .setOwner(OWNER) + .setSelfLink(SELF_LINK) + .setCors(CORS) + .setCreateTime(CREATE_TIME) + .setDefaultAcl(DEFAULT_ACL) + .setDeleteRules(DELETE_RULES) + .setIndexPage(INDEX_PAGE) + .setNotFoundPage(NOT_FOUND_PAGE) + .setLocation(LOCATION) + .setStorageClass(STORAGE_CLASS) + .setVersioningEnabled(VERSIONING_ENABLED) + .build(); + assertEquals("b", bucket.getName()); + assertEquals(ACLS, bucket.getAcl()); + assertEquals(ETAG, bucket.getEtag()); + assertEquals(GENERATED_ID, bucket.getGeneratedId()); + assertEquals(META_GENERATION, bucket.getMetageneration()); + assertEquals(OWNER, bucket.getOwner()); + assertEquals(SELF_LINK, bucket.getSelfLink()); + assertEquals(CREATE_TIME, bucket.getCreateTime()); + assertEquals(CORS, bucket.getCors()); + assertEquals(DEFAULT_ACL, bucket.getDefaultAcl()); + assertEquals(DELETE_RULES, bucket.getDeleteRules()); + assertEquals(INDEX_PAGE, bucket.getIndexPage()); + assertEquals(NOT_FOUND_PAGE, bucket.getNotFoundPage()); + assertEquals(LOCATION, bucket.getLocation()); + assertEquals(STORAGE_CLASS, bucket.getStorageClass()); + assertEquals(VERSIONING_ENABLED, bucket.versioningEnabled()); + assertEquals(storage.options(), bucket.getStorage().options()); + } + + @Test + public void testBuilderDeprecated() { initializeExpectedBucket(4); expect(storage.options()).andReturn(mockOptions).times(4); replay(storage); Bucket.Builder builder = new Bucket.Builder(new Bucket(storage, new BucketInfo.BuilderImpl(BUCKET_INFO))); Bucket bucket = builder.acl(ACLS) - .etag(ETAG) - .generatedId(GENERATED_ID) - .metageneration(META_GENERATION) - .owner(OWNER) - .selfLink(SELF_LINK) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setMetageneration(META_GENERATION) + .setOwner(OWNER) + .setSelfLink(SELF_LINK) .cors(CORS) - .createTime(CREATE_TIME) + .setCreateTime(CREATE_TIME) .defaultAcl(DEFAULT_ACL) .deleteRules(DELETE_RULES) .indexPage(INDEX_PAGE) diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/CopyRequestTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/CopyRequestTest.java index 0649566864a1..f517c3246ceb 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/CopyRequestTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/CopyRequestTest.java @@ -38,14 +38,49 @@ public class CopyRequestTest { private static final String TARGET_BLOB_CONTENT_TYPE = "contentType"; private static final BlobId SOURCE_BLOB_ID = BlobId.of(SOURCE_BUCKET_NAME, SOURCE_BLOB_NAME); private static final BlobId TARGET_BLOB_ID = BlobId.of(TARGET_BUCKET_NAME, TARGET_BLOB_NAME); - private static final BlobInfo TARGET_BLOB_INFO = BlobInfo.builder(TARGET_BLOB_ID) - .contentType(TARGET_BLOB_CONTENT_TYPE).build(); + private static final BlobInfo TARGET_BLOB_INFO = BlobInfo.newBuilder(TARGET_BLOB_ID) + .setContentType(TARGET_BLOB_CONTENT_TYPE).build(); @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testCopyRequest() { + Storage.CopyRequest copyRequest1 = Storage.CopyRequest.newBuilder() + .setSource(SOURCE_BLOB_ID) + .setSourceOptions(BlobSourceOption.generationMatch(1)) + .setTarget(TARGET_BLOB_INFO, BlobTargetOption.predefinedAcl(PUBLIC_READ)) + .build(); + assertEquals(SOURCE_BLOB_ID, copyRequest1.getSource()); + assertEquals(1, copyRequest1.getSourceOptions().size()); + assertEquals(BlobSourceOption.generationMatch(1), copyRequest1.getSourceOptions().get(0)); + assertEquals(TARGET_BLOB_INFO, copyRequest1.getTarget()); + assertTrue(copyRequest1.overrideInfo()); + assertEquals(1, copyRequest1.getTargetOptions().size()); + assertEquals(BlobTargetOption.predefinedAcl(PUBLIC_READ), + copyRequest1.getTargetOptions().get(0)); + + Storage.CopyRequest copyRequest2 = Storage.CopyRequest.newBuilder() + .setSource(SOURCE_BUCKET_NAME, SOURCE_BLOB_NAME) + .setTarget(TARGET_BLOB_ID) + .build(); + assertEquals(SOURCE_BLOB_ID, copyRequest2.getSource()); + assertEquals(BlobInfo.newBuilder(TARGET_BLOB_ID).build(), copyRequest2.getTarget()); + assertFalse(copyRequest2.overrideInfo()); + + Storage.CopyRequest copyRequest3 = Storage.CopyRequest.newBuilder() + .setSource(SOURCE_BLOB_ID) + .setTarget(TARGET_BLOB_INFO, ImmutableList.of(BlobTargetOption.predefinedAcl(PUBLIC_READ))) + .build(); + assertEquals(SOURCE_BLOB_ID, copyRequest3.getSource()); + assertEquals(TARGET_BLOB_INFO, copyRequest3.getTarget()); + assertTrue(copyRequest3.overrideInfo()); + assertEquals(ImmutableList.of(BlobTargetOption.predefinedAcl(PUBLIC_READ)), + copyRequest3.getTargetOptions()); + } + + @Test + public void testCopyRequestDeprecated() { Storage.CopyRequest copyRequest1 = Storage.CopyRequest.builder() .source(SOURCE_BLOB_ID) .sourceOptions(BlobSourceOption.generationMatch(1)) @@ -81,38 +116,38 @@ public void testCopyRequest() { @Test public void testCopyRequestOf() { Storage.CopyRequest copyRequest1 = Storage.CopyRequest.of(SOURCE_BLOB_ID, TARGET_BLOB_INFO); - assertEquals(SOURCE_BLOB_ID, copyRequest1.source()); - assertEquals(TARGET_BLOB_INFO, copyRequest1.target()); + assertEquals(SOURCE_BLOB_ID, copyRequest1.getSource()); + assertEquals(TARGET_BLOB_INFO, copyRequest1.getTarget()); assertTrue(copyRequest1.overrideInfo()); Storage.CopyRequest copyRequest2 = Storage.CopyRequest.of(SOURCE_BLOB_ID, TARGET_BLOB_NAME); - assertEquals(SOURCE_BLOB_ID, copyRequest2.source()); - assertEquals(BlobInfo.builder(BlobId.of(SOURCE_BUCKET_NAME, TARGET_BLOB_NAME)).build(), - copyRequest2.target()); + assertEquals(SOURCE_BLOB_ID, copyRequest2.getSource()); + assertEquals(BlobInfo.newBuilder(BlobId.of(SOURCE_BUCKET_NAME, TARGET_BLOB_NAME)).build(), + copyRequest2.getTarget()); assertFalse(copyRequest2.overrideInfo()); Storage.CopyRequest copyRequest3 = Storage.CopyRequest.of(SOURCE_BUCKET_NAME, SOURCE_BLOB_NAME, TARGET_BLOB_INFO); - assertEquals(SOURCE_BLOB_ID, copyRequest3.source()); - assertEquals(TARGET_BLOB_INFO, copyRequest3.target()); + assertEquals(SOURCE_BLOB_ID, copyRequest3.getSource()); + assertEquals(TARGET_BLOB_INFO, copyRequest3.getTarget()); assertTrue(copyRequest3.overrideInfo()); Storage.CopyRequest copyRequest4 = Storage.CopyRequest.of(SOURCE_BUCKET_NAME, SOURCE_BLOB_NAME, TARGET_BLOB_NAME); - assertEquals(SOURCE_BLOB_ID, copyRequest4.source()); - assertEquals(BlobInfo.builder(BlobId.of(SOURCE_BUCKET_NAME, TARGET_BLOB_NAME)).build(), - copyRequest4.target()); + assertEquals(SOURCE_BLOB_ID, copyRequest4.getSource()); + assertEquals(BlobInfo.newBuilder(BlobId.of(SOURCE_BUCKET_NAME, TARGET_BLOB_NAME)).build(), + copyRequest4.getTarget()); assertFalse(copyRequest4.overrideInfo()); Storage.CopyRequest copyRequest5 = Storage.CopyRequest.of(SOURCE_BLOB_ID, TARGET_BLOB_ID); - assertEquals(SOURCE_BLOB_ID, copyRequest5.source()); - assertEquals(BlobInfo.builder(TARGET_BLOB_ID).build(), copyRequest5.target()); + assertEquals(SOURCE_BLOB_ID, copyRequest5.getSource()); + assertEquals(BlobInfo.newBuilder(TARGET_BLOB_ID).build(), copyRequest5.getTarget()); assertFalse(copyRequest5.overrideInfo()); Storage.CopyRequest copyRequest6 = Storage.CopyRequest.of(SOURCE_BUCKET_NAME, SOURCE_BLOB_NAME, TARGET_BLOB_ID); - assertEquals(SOURCE_BLOB_ID, copyRequest6.source()); - assertEquals(BlobInfo.builder(TARGET_BLOB_ID).build(), copyRequest6.target()); + assertEquals(SOURCE_BLOB_ID, copyRequest6.getSource()); + assertEquals(BlobInfo.newBuilder(TARGET_BLOB_ID).build(), copyRequest6.getTarget()); assertFalse(copyRequest6.overrideInfo()); } } diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/CopyWriterTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/CopyWriterTest.java index 5f5b9102c195..fe5e42a5abd1 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/CopyWriterTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/CopyWriterTest.java @@ -47,9 +47,10 @@ public class CopyWriterTest { private static final String DESTINATION_BLOB_NAME = "n1"; private static final BlobId BLOB_ID = BlobId.of(SOURCE_BUCKET_NAME, SOURCE_BLOB_NAME); private static final BlobInfo BLOB_INFO = - BlobInfo.builder(DESTINATION_BUCKET_NAME, DESTINATION_BLOB_NAME).build(); + BlobInfo.newBuilder(DESTINATION_BUCKET_NAME, DESTINATION_BLOB_NAME).build(); private static final BlobInfo RESULT_INFO = - BlobInfo.builder(DESTINATION_BUCKET_NAME, DESTINATION_BLOB_NAME).contentType("type").build(); + BlobInfo.newBuilder(DESTINATION_BUCKET_NAME, DESTINATION_BLOB_NAME).setContentType("type") + .build(); private static final Map EMPTY_OPTIONS = ImmutableMap.of(); private static final RewriteRequest REQUEST_WITH_OBJECT = new StorageRpc.RewriteRequest(BLOB_ID.toPb(), EMPTY_OPTIONS, true, BLOB_INFO.toPb(), @@ -93,7 +94,7 @@ public void tearDown() throws Exception { } @Test - public void testRewriteWithObject() { + public void testRewriteDeprecated() { EasyMock.expect(storageRpcMock.continueRewrite(RESPONSE_WITH_OBJECT)) .andReturn(RESPONSE_WITH_OBJECT_DONE); EasyMock.replay(storageRpcMock); @@ -104,16 +105,28 @@ public void testRewriteWithObject() { assertEquals(42L, copyWriter.blobSize()); } + @Test + public void testRewriteWithObject() { + EasyMock.expect(storageRpcMock.continueRewrite(RESPONSE_WITH_OBJECT)) + .andReturn(RESPONSE_WITH_OBJECT_DONE); + EasyMock.replay(storageRpcMock); + copyWriter = new CopyWriter(options, RESPONSE_WITH_OBJECT); + assertEquals(result, copyWriter.getResult()); + assertTrue(copyWriter.isDone()); + assertEquals(42L, copyWriter.getTotalBytesCopied()); + assertEquals(42L, copyWriter.getBlobSize()); + } + @Test public void testRewriteWithoutObject() { EasyMock.expect(storageRpcMock.continueRewrite(RESPONSE_WITHOUT_OBJECT)) .andReturn(RESPONSE_WITHOUT_OBJECT_DONE); EasyMock.replay(storageRpcMock); copyWriter = new CopyWriter(options, RESPONSE_WITHOUT_OBJECT); - assertEquals(result, copyWriter.result()); + assertEquals(result, copyWriter.getResult()); assertTrue(copyWriter.isDone()); - assertEquals(42L, copyWriter.totalBytesCopied()); - assertEquals(42L, copyWriter.blobSize()); + assertEquals(42L, copyWriter.getTotalBytesCopied()); + assertEquals(42L, copyWriter.getBlobSize()); } @Test @@ -124,10 +137,10 @@ public void testRewriteWithObjectMultipleRequests() { .andReturn(RESPONSE_WITH_OBJECT_DONE); EasyMock.replay(storageRpcMock); copyWriter = new CopyWriter(options, RESPONSE_WITH_OBJECT); - assertEquals(result, copyWriter.result()); + assertEquals(result, copyWriter.getResult()); assertTrue(copyWriter.isDone()); - assertEquals(42L, copyWriter.totalBytesCopied()); - assertEquals(42L, copyWriter.blobSize()); + assertEquals(42L, copyWriter.getTotalBytesCopied()); + assertEquals(42L, copyWriter.getBlobSize()); } @Test @@ -138,10 +151,10 @@ public void testRewriteWithoutObjectMultipleRequests() { .andReturn(RESPONSE_WITHOUT_OBJECT_DONE); EasyMock.replay(storageRpcMock); copyWriter = new CopyWriter(options, RESPONSE_WITHOUT_OBJECT); - assertEquals(result, copyWriter.result()); + assertEquals(result, copyWriter.getResult()); assertTrue(copyWriter.isDone()); - assertEquals(42L, copyWriter.totalBytesCopied()); - assertEquals(42L, copyWriter.blobSize()); + assertEquals(42L, copyWriter.getTotalBytesCopied()); + assertEquals(42L, copyWriter.getBlobSize()); } @Test @@ -154,14 +167,14 @@ public void testSaveAndRestoreWithObject() { copyWriter = new CopyWriter(options, RESPONSE_WITH_OBJECT); copyWriter.copyChunk(); assertTrue(!copyWriter.isDone()); - assertEquals(21L, copyWriter.totalBytesCopied()); - assertEquals(42L, copyWriter.blobSize()); + assertEquals(21L, copyWriter.getTotalBytesCopied()); + assertEquals(42L, copyWriter.getBlobSize()); RestorableState rewriterState = copyWriter.capture(); CopyWriter restoredRewriter = rewriterState.restore(); - assertEquals(result, restoredRewriter.result()); + assertEquals(result, restoredRewriter.getResult()); assertTrue(restoredRewriter.isDone()); - assertEquals(42L, restoredRewriter.totalBytesCopied()); - assertEquals(42L, restoredRewriter.blobSize()); + assertEquals(42L, restoredRewriter.getTotalBytesCopied()); + assertEquals(42L, restoredRewriter.getBlobSize()); } @Test @@ -174,14 +187,14 @@ public void testSaveAndRestoreWithoutObject() { copyWriter = new CopyWriter(options, RESPONSE_WITHOUT_OBJECT); copyWriter.copyChunk(); assertTrue(!copyWriter.isDone()); - assertEquals(21L, copyWriter.totalBytesCopied()); - assertEquals(42L, copyWriter.blobSize()); + assertEquals(21L, copyWriter.getTotalBytesCopied()); + assertEquals(42L, copyWriter.getBlobSize()); RestorableState rewriterState = copyWriter.capture(); CopyWriter restoredRewriter = rewriterState.restore(); - assertEquals(result, restoredRewriter.result()); + assertEquals(result, restoredRewriter.getResult()); assertTrue(restoredRewriter.isDone()); - assertEquals(42L, restoredRewriter.totalBytesCopied()); - assertEquals(42L, restoredRewriter.blobSize()); + assertEquals(42L, restoredRewriter.getTotalBytesCopied()); + assertEquals(42L, restoredRewriter.getBlobSize()); } @Test @@ -191,15 +204,15 @@ public void testSaveAndRestoreWithResult() { EasyMock.replay(storageRpcMock); copyWriter = new CopyWriter(options, RESPONSE_WITH_OBJECT); copyWriter.copyChunk(); - assertEquals(result, copyWriter.result()); + assertEquals(result, copyWriter.getResult()); assertTrue(copyWriter.isDone()); - assertEquals(42L, copyWriter.totalBytesCopied()); - assertEquals(42L, copyWriter.blobSize()); + assertEquals(42L, copyWriter.getTotalBytesCopied()); + assertEquals(42L, copyWriter.getBlobSize()); RestorableState rewriterState = copyWriter.capture(); CopyWriter restoredRewriter = rewriterState.restore(); - assertEquals(result, restoredRewriter.result()); + assertEquals(result, restoredRewriter.getResult()); assertTrue(restoredRewriter.isDone()); - assertEquals(42L, restoredRewriter.totalBytesCopied()); - assertEquals(42L, restoredRewriter.blobSize()); + assertEquals(42L, restoredRewriter.getTotalBytesCopied()); + assertEquals(42L, restoredRewriter.getBlobSize()); } } diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/CorsTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/CorsTest.java index b22547a34e54..8507c4bd6bf8 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/CorsTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/CorsTest.java @@ -36,6 +36,24 @@ public void testOrigin() { @Test public void corsTest() { + List origins = ImmutableList.of(Origin.any(), Origin.of("o")); + List headers = ImmutableList.of("h1", "h2"); + List methods = ImmutableList.of(HttpMethod.GET); + Cors cors = Cors.newBuilder() + .setMaxAgeSeconds(100) + .setOrigins(origins) + .setResponseHeaders(headers) + .setMethods(methods) + .build(); + + assertEquals(Integer.valueOf(100), cors.getMaxAgeSeconds()); + assertEquals(origins, cors.getOrigins()); + assertEquals(methods, cors.getMethods()); + assertEquals(headers, cors.getResponseHeaders()); + } + + @Test + public void corsTestDeprecated() { List origins = ImmutableList.of(Origin.any(), Origin.of("o")); List headers = ImmutableList.of("h1", "h2"); List methods = ImmutableList.of(HttpMethod.GET); diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/OptionTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/OptionTest.java index 6856745c0c4d..538ce10ab073 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/OptionTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/OptionTest.java @@ -54,11 +54,11 @@ public void testHashCode() { @Test public void testConstructor() { - assertEquals(RPC_OPTION, OPTION.rpcOption()); - assertEquals(VALUE, OPTION.value()); + assertEquals(RPC_OPTION, OPTION.getRpcOption()); + assertEquals(VALUE, OPTION.getValue()); Option option = new Option(RPC_OPTION, null) {}; - assertEquals(RPC_OPTION, option.rpcOption()); - assertNull(option.value()); + assertEquals(RPC_OPTION, option.getRpcOption()); + assertNull(option.getValue()); thrown.expect(NullPointerException.class); new Option(null, VALUE) {}; } diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java index a816415ddc02..8addc5c3a147 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java @@ -38,13 +38,13 @@ public class SerializationTest extends BaseSerializationTest { private static final Acl.User ACL_USER = new Acl.User("user"); private static final Acl.RawEntity ACL_RAW = new Acl.RawEntity("raw"); private static final Acl ACL = Acl.of(ACL_DOMAIN, Acl.Role.OWNER); - private static final BlobInfo BLOB_INFO = BlobInfo.builder("b", "n").build(); + private static final BlobInfo BLOB_INFO = BlobInfo.newBuilder("b", "n").build(); private static final BucketInfo BUCKET_INFO = BucketInfo.of("b"); private static final Blob BLOB = new Blob(STORAGE, new BlobInfo.BuilderImpl(BLOB_INFO)); private static final Bucket BUCKET = new Bucket(STORAGE, new BucketInfo.BuilderImpl(BUCKET_INFO)); private static final Cors.Origin ORIGIN = Cors.Origin.any(); private static final Cors CORS = - Cors.builder().maxAgeSeconds(1).origins(Collections.singleton(ORIGIN)).build(); + Cors.newBuilder().setMaxAgeSeconds(1).setOrigins(Collections.singleton(ORIGIN)).build(); private static final PageImpl PAGE_RESULT = new PageImpl<>(null, "c", Collections.singletonList(BLOB)); private static final StorageException STORAGE_EXCEPTION = new StorageException(42, "message"); @@ -85,8 +85,8 @@ protected Restorable[] restorableObjects() { new BlobReadChannel(options, BlobId.of("b", "n"), EMPTY_RPC_OPTIONS); // avoid closing when you don't want partial writes to GCS upon failure @SuppressWarnings("resource") - BlobWriteChannel writer = - new BlobWriteChannel(options, BlobInfo.builder(BlobId.of("b", "n")).build(), "upload-id"); + BlobWriteChannel writer = new BlobWriteChannel(options, + BlobInfo.newBuilder(BlobId.of("b", "n")).build(), "upload-id"); return new Restorable[]{reader, writer}; } } diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageBatchTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageBatchTest.java index 02f14fd457ed..48658b116468 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageBatchTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageBatchTest.java @@ -43,9 +43,9 @@ public class StorageBatchTest { private static final BlobId BLOB_ID = BlobId.of("b1", "n1"); private static final BlobId BLOB_ID_COMPLETE = BlobId.of("b1", "n1", 42L); - private static final BlobInfo BLOB_INFO = BlobInfo.builder(BLOB_ID).build(); - private static final BlobInfo BLOB_INFO_COMPLETE = BlobInfo.builder(BLOB_ID_COMPLETE) - .metageneration(42L) + private static final BlobInfo BLOB_INFO = BlobInfo.newBuilder(BLOB_ID).build(); + private static final BlobInfo BLOB_INFO_COMPLETE = BlobInfo.newBuilder(BLOB_ID_COMPLETE) + .setMetageneration(42L) .build(); private static final BlobGetOption[] BLOB_GET_OPTIONS = { BlobGetOption.generationMatch(42L), BlobGetOption.metagenerationMatch(42L)}; @@ -91,7 +91,8 @@ public void testDelete() { batchMock.addDelete(EasyMock.eq(BLOB_INFO.toPb()), EasyMock.capture(callback), EasyMock.eq(ImmutableMap.of())); EasyMock.replay(batchMock); - StorageBatchResult batchResult = dnsBatch.delete(BLOB_ID.bucket(), BLOB_ID.name()); + StorageBatchResult batchResult = + dnsBatch.delete(BLOB_ID.getBucket(), BLOB_ID.getName()); assertNotNull(callback.getValue()); try { batchResult.get(); @@ -122,7 +123,7 @@ public void testDeleteWithOptions() { assertNotNull(callback.getValue()); assertEquals(2, capturedOptions.getValue().size()); for (BlobSourceOption option : BLOB_SOURCE_OPTIONS) { - assertEquals(option.value(), capturedOptions.getValue().get(option.rpcOption())); + assertEquals(option.getValue(), capturedOptions.getValue().get(option.getRpcOption())); } RpcBatch.Callback capturedCallback = callback.getValue(); capturedCallback.onSuccess(null); @@ -168,8 +169,8 @@ public void testUpdateWithOptions() { StorageBatchResult batchResult = dnsBatch.update(BLOB_INFO_COMPLETE, BLOB_TARGET_OPTIONS); assertNotNull(callback.getValue()); assertEquals(2, capturedOptions.getValue().size()); - assertEquals(42L, capturedOptions.getValue().get(BLOB_TARGET_OPTIONS[0].rpcOption())); - assertEquals(42L, capturedOptions.getValue().get(BLOB_TARGET_OPTIONS[1].rpcOption())); + assertEquals(42L, capturedOptions.getValue().get(BLOB_TARGET_OPTIONS[0].getRpcOption())); + assertEquals(42L, capturedOptions.getValue().get(BLOB_TARGET_OPTIONS[1].getRpcOption())); RpcBatch.Callback capturedCallback = callback.getValue(); capturedCallback.onSuccess(BLOB_INFO.toPb()); assertEquals(new Blob(storage, new Blob.BuilderImpl(BLOB_INFO)), batchResult.get()); @@ -182,7 +183,7 @@ public void testGet() { batchMock.addGet(EasyMock.eq(BLOB_INFO.toPb()), EasyMock.capture(callback), EasyMock.eq(ImmutableMap.of())); EasyMock.replay(batchMock); - StorageBatchResult batchResult = dnsBatch.get(BLOB_ID.bucket(), BLOB_ID.name()); + StorageBatchResult batchResult = dnsBatch.get(BLOB_ID.getBucket(), BLOB_ID.getName()); assertNotNull(callback.getValue()); try { batchResult.get(); @@ -215,7 +216,7 @@ public void testGetWithOptions() { assertNotNull(callback.getValue()); assertEquals(2, capturedOptions.getValue().size()); for (BlobGetOption option : BLOB_GET_OPTIONS) { - assertEquals(option.value(), capturedOptions.getValue().get(option.rpcOption())); + assertEquals(option.getValue(), capturedOptions.getValue().get(option.getRpcOption())); } RpcBatch.Callback capturedCallback = callback.getValue(); capturedCallback.onSuccess(BLOB_INFO.toPb()); diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java index bfcf28bc12e6..261bfa31512a 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java @@ -102,14 +102,14 @@ public class StorageImplTest { // BucketInfo objects private static final BucketInfo BUCKET_INFO1 = - BucketInfo.builder(BUCKET_NAME1).metageneration(42L).build(); - private static final BucketInfo BUCKET_INFO2 = BucketInfo.builder(BUCKET_NAME2).build(); + BucketInfo.newBuilder(BUCKET_NAME1).setMetageneration(42L).build(); + private static final BucketInfo BUCKET_INFO2 = BucketInfo.newBuilder(BUCKET_NAME2).build(); // BlobInfo objects - private static final BlobInfo BLOB_INFO1 = BlobInfo.builder(BUCKET_NAME1, BLOB_NAME1, 24L) - .metageneration(42L).contentType("application/json").md5("md5string").build(); - private static final BlobInfo BLOB_INFO2 = BlobInfo.builder(BUCKET_NAME1, BLOB_NAME2).build(); - private static final BlobInfo BLOB_INFO3 = BlobInfo.builder(BUCKET_NAME1, BLOB_NAME3).build(); + private static final BlobInfo BLOB_INFO1 = BlobInfo.newBuilder(BUCKET_NAME1, BLOB_NAME1, 24L) + .setMetageneration(42L).setContentType("application/json").setMd5("md5string").build(); + private static final BlobInfo BLOB_INFO2 = BlobInfo.newBuilder(BUCKET_NAME1, BLOB_NAME2).build(); + private static final BlobInfo BLOB_INFO3 = BlobInfo.newBuilder(BUCKET_NAME1, BLOB_NAME3).build(); // Empty StorageRpc options private static final Map EMPTY_RPC_OPTIONS = ImmutableMap.of(); @@ -120,8 +120,8 @@ public class StorageImplTest { private static final Storage.BucketTargetOption BUCKET_TARGET_PREDEFINED_ACL = Storage.BucketTargetOption.predefinedAcl(Storage.PredefinedAcl.PRIVATE); private static final Map BUCKET_TARGET_OPTIONS = ImmutableMap.of( - StorageRpc.Option.IF_METAGENERATION_MATCH, BUCKET_INFO1.metageneration(), - StorageRpc.Option.PREDEFINED_ACL, BUCKET_TARGET_PREDEFINED_ACL.value()); + StorageRpc.Option.IF_METAGENERATION_MATCH, BUCKET_INFO1.getMetageneration(), + StorageRpc.Option.PREDEFINED_ACL, BUCKET_TARGET_PREDEFINED_ACL.getValue()); // Blob target options (create, update, compose) private static final BlobTargetOption BLOB_TARGET_GENERATION = BlobTargetOption.generationMatch(); @@ -131,15 +131,15 @@ public class StorageImplTest { private static final BlobTargetOption BLOB_TARGET_PREDEFINED_ACL = BlobTargetOption.predefinedAcl(Storage.PredefinedAcl.PRIVATE); private static final Map BLOB_TARGET_OPTIONS_CREATE = ImmutableMap.of( - StorageRpc.Option.IF_METAGENERATION_MATCH, BLOB_INFO1.metageneration(), + StorageRpc.Option.IF_METAGENERATION_MATCH, BLOB_INFO1.getMetageneration(), StorageRpc.Option.IF_GENERATION_MATCH, 0L, - StorageRpc.Option.PREDEFINED_ACL, BUCKET_TARGET_PREDEFINED_ACL.value()); + StorageRpc.Option.PREDEFINED_ACL, BUCKET_TARGET_PREDEFINED_ACL.getValue()); private static final Map BLOB_TARGET_OPTIONS_UPDATE = ImmutableMap.of( - StorageRpc.Option.IF_METAGENERATION_MATCH, BLOB_INFO1.metageneration(), - StorageRpc.Option.PREDEFINED_ACL, BUCKET_TARGET_PREDEFINED_ACL.value()); + StorageRpc.Option.IF_METAGENERATION_MATCH, BLOB_INFO1.getMetageneration(), + StorageRpc.Option.PREDEFINED_ACL, BUCKET_TARGET_PREDEFINED_ACL.getValue()); private static final Map BLOB_TARGET_OPTIONS_COMPOSE = ImmutableMap.of( - StorageRpc.Option.IF_GENERATION_MATCH, BLOB_INFO1.generation(), - StorageRpc.Option.IF_METAGENERATION_MATCH, BLOB_INFO1.metageneration()); + StorageRpc.Option.IF_GENERATION_MATCH, BLOB_INFO1.getGeneration(), + StorageRpc.Option.IF_METAGENERATION_MATCH, BLOB_INFO1.getMetageneration()); // Blob write options (create, writer) private static final BlobWriteOption BLOB_WRITE_METAGENERATION = @@ -152,23 +152,23 @@ public class StorageImplTest { // Bucket get/source options private static final BucketSourceOption BUCKET_SOURCE_METAGENERATION = - BucketSourceOption.metagenerationMatch(BUCKET_INFO1.metageneration()); + BucketSourceOption.metagenerationMatch(BUCKET_INFO1.getMetageneration()); private static final Map BUCKET_SOURCE_OPTIONS = ImmutableMap.of( - StorageRpc.Option.IF_METAGENERATION_MATCH, BUCKET_SOURCE_METAGENERATION.value()); + StorageRpc.Option.IF_METAGENERATION_MATCH, BUCKET_SOURCE_METAGENERATION.getValue()); private static final Storage.BucketGetOption BUCKET_GET_METAGENERATION = - Storage.BucketGetOption.metagenerationMatch(BUCKET_INFO1.metageneration()); + Storage.BucketGetOption.metagenerationMatch(BUCKET_INFO1.getMetageneration()); private static final Storage.BucketGetOption BUCKET_GET_FIELDS = Storage.BucketGetOption.fields(Storage.BucketField.LOCATION, Storage.BucketField.ACL); private static final Storage.BucketGetOption BUCKET_GET_EMPTY_FIELDS = Storage.BucketGetOption.fields(); private static final Map BUCKET_GET_OPTIONS = ImmutableMap.of( - StorageRpc.Option.IF_METAGENERATION_MATCH, BUCKET_SOURCE_METAGENERATION.value()); + StorageRpc.Option.IF_METAGENERATION_MATCH, BUCKET_SOURCE_METAGENERATION.getValue()); // Blob get/source options private static final Storage.BlobGetOption BLOB_GET_METAGENERATION = - Storage.BlobGetOption.metagenerationMatch(BLOB_INFO1.metageneration()); + Storage.BlobGetOption.metagenerationMatch(BLOB_INFO1.getMetageneration()); private static final Storage.BlobGetOption BLOB_GET_GENERATION = - Storage.BlobGetOption.generationMatch(BLOB_INFO1.generation()); + Storage.BlobGetOption.generationMatch(BLOB_INFO1.getGeneration()); private static final Storage.BlobGetOption BLOB_GET_GENERATION_FROM_BLOB_ID = Storage.BlobGetOption.generationMatch(); private static final Storage.BlobGetOption BLOB_GET_FIELDS = @@ -176,20 +176,20 @@ public class StorageImplTest { private static final Storage.BlobGetOption BLOB_GET_EMPTY_FIELDS = Storage.BlobGetOption.fields(); private static final Map BLOB_GET_OPTIONS = ImmutableMap.of( - StorageRpc.Option.IF_METAGENERATION_MATCH, BLOB_GET_METAGENERATION.value(), - StorageRpc.Option.IF_GENERATION_MATCH, BLOB_GET_GENERATION.value()); + StorageRpc.Option.IF_METAGENERATION_MATCH, BLOB_GET_METAGENERATION.getValue(), + StorageRpc.Option.IF_GENERATION_MATCH, BLOB_GET_GENERATION.getValue()); private static final BlobSourceOption BLOB_SOURCE_METAGENERATION = - BlobSourceOption.metagenerationMatch(BLOB_INFO1.metageneration()); + BlobSourceOption.metagenerationMatch(BLOB_INFO1.getMetageneration()); private static final BlobSourceOption BLOB_SOURCE_GENERATION = - BlobSourceOption.generationMatch(BLOB_INFO1.generation()); + BlobSourceOption.generationMatch(BLOB_INFO1.getGeneration()); private static final BlobSourceOption BLOB_SOURCE_GENERATION_FROM_BLOB_ID = BlobSourceOption.generationMatch(); private static final Map BLOB_SOURCE_OPTIONS = ImmutableMap.of( - StorageRpc.Option.IF_METAGENERATION_MATCH, BLOB_SOURCE_METAGENERATION.value(), - StorageRpc.Option.IF_GENERATION_MATCH, BLOB_SOURCE_GENERATION.value()); + StorageRpc.Option.IF_METAGENERATION_MATCH, BLOB_SOURCE_METAGENERATION.getValue(), + StorageRpc.Option.IF_GENERATION_MATCH, BLOB_SOURCE_GENERATION.getValue()); private static final Map BLOB_SOURCE_OPTIONS_COPY = ImmutableMap.of( - StorageRpc.Option.IF_SOURCE_METAGENERATION_MATCH, BLOB_SOURCE_METAGENERATION.value(), - StorageRpc.Option.IF_SOURCE_GENERATION_MATCH, BLOB_SOURCE_GENERATION.value()); + StorageRpc.Option.IF_SOURCE_METAGENERATION_MATCH, BLOB_SOURCE_METAGENERATION.getValue(), + StorageRpc.Option.IF_SOURCE_GENERATION_MATCH, BLOB_SOURCE_GENERATION.getValue()); // Bucket list options private static final Storage.BucketListOption BUCKET_LIST_PAGE_SIZE = @@ -201,8 +201,8 @@ public class StorageImplTest { private static final Storage.BucketListOption BUCKET_LIST_EMPTY_FIELDS = Storage.BucketListOption.fields(); private static final Map BUCKET_LIST_OPTIONS = ImmutableMap.of( - StorageRpc.Option.MAX_RESULTS, BUCKET_LIST_PAGE_SIZE.value(), - StorageRpc.Option.PREFIX, BUCKET_LIST_PREFIX.value()); + StorageRpc.Option.MAX_RESULTS, BUCKET_LIST_PAGE_SIZE.getValue(), + StorageRpc.Option.PREFIX, BUCKET_LIST_PREFIX.getValue()); // Blob list options private static final Storage.BlobListOption BLOB_LIST_PAGE_SIZE = @@ -216,9 +216,9 @@ public class StorageImplTest { private static final Storage.BlobListOption BLOB_LIST_EMPTY_FIELDS = Storage.BlobListOption.fields(); private static final Map BLOB_LIST_OPTIONS = ImmutableMap.of( - StorageRpc.Option.MAX_RESULTS, BLOB_LIST_PAGE_SIZE.value(), - StorageRpc.Option.PREFIX, BLOB_LIST_PREFIX.value(), - StorageRpc.Option.VERSIONS, BLOB_LIST_VERSIONS.value()); + StorageRpc.Option.MAX_RESULTS, BLOB_LIST_PAGE_SIZE.getValue(), + StorageRpc.Option.PREFIX, BLOB_LIST_PREFIX.getValue(), + StorageRpc.Option.VERSIONS, BLOB_LIST_VERSIONS.getValue()); // ACLs private static final Acl ACL = Acl.of(User.ofAllAuthenticatedUsers(), Role.OWNER); @@ -342,7 +342,10 @@ public void testCreateBucketWithOptions() { public void testCreateBlob() throws IOException { Capture capturedStream = Capture.newInstance(); EasyMock.expect(storageRpcMock.create( - EasyMock.eq(BLOB_INFO1.toBuilder().md5(CONTENT_MD5).crc32c(CONTENT_CRC32C).build().toPb()), + EasyMock.eq(BLOB_INFO1.toBuilder() + .setMd5(CONTENT_MD5) + .setCrc32c(CONTENT_CRC32C) + .build().toPb()), EasyMock.capture(capturedStream), EasyMock.eq(EMPTY_RPC_OPTIONS))) .andReturn(BLOB_INFO1.toPb()); @@ -362,8 +365,8 @@ public void testCreateEmptyBlob() throws IOException { Capture capturedStream = Capture.newInstance(); EasyMock.expect(storageRpcMock.create( EasyMock.eq(BLOB_INFO1.toBuilder() - .md5("1B2M2Y8AsgTpgAmY7PhCfg==") - .crc32c("AAAAAA==") + .setMd5("1B2M2Y8AsgTpgAmY7PhCfg==") + .setCrc32c("AAAAAA==") .build() .toPb()), EasyMock.capture(capturedStream), @@ -383,8 +386,8 @@ public void testCreateBlobWithOptions() throws IOException { Capture capturedStream = Capture.newInstance(); EasyMock.expect(storageRpcMock.create( EasyMock.eq(BLOB_INFO1.toBuilder() - .md5(CONTENT_MD5) - .crc32c(CONTENT_CRC32C) + .setMd5(CONTENT_MD5) + .setCrc32c(CONTENT_CRC32C) .build() .toPb()), EasyMock.capture(capturedStream), @@ -407,7 +410,10 @@ public void testCreateBlobWithOptions() throws IOException { public void testCreateBlobWithEncryptionKey() throws IOException { Capture capturedStream = Capture.newInstance(); EasyMock.expect(storageRpcMock.create( - EasyMock.eq(BLOB_INFO1.toBuilder().md5(CONTENT_MD5).crc32c(CONTENT_CRC32C).build().toPb()), + EasyMock.eq(BLOB_INFO1.toBuilder() + .setMd5(CONTENT_MD5). + setCrc32c(CONTENT_CRC32C) + .build().toPb()), EasyMock.capture(capturedStream), EasyMock.eq(ENCRYPTION_KEY_OPTIONS))) .andReturn(BLOB_INFO1.toPb()) @@ -434,8 +440,8 @@ public void testCreateBlobWithEncryptionKey() throws IOException { public void testCreateBlobFromStream() { ByteArrayInputStream fileStream = new ByteArrayInputStream(BLOB_CONTENT); BlobInfo.Builder infoBuilder = BLOB_INFO1.toBuilder(); - BlobInfo infoWithHashes = infoBuilder.md5(CONTENT_MD5).crc32c(CONTENT_CRC32C).build(); - BlobInfo infoWithoutHashes = infoBuilder.md5(null).crc32c(null).build(); + BlobInfo infoWithHashes = infoBuilder.setMd5(CONTENT_MD5).setCrc32c(CONTENT_CRC32C).build(); + BlobInfo infoWithoutHashes = infoBuilder.setMd5(null).setCrc32c(null).build(); EasyMock.expect(storageRpcMock.create(infoWithoutHashes.toPb(), fileStream, EMPTY_RPC_OPTIONS)) .andReturn(BLOB_INFO1.toPb()); EasyMock.replay(storageRpcMock); @@ -448,8 +454,8 @@ public void testCreateBlobFromStream() { public void testCreateBlobFromStreamWithEncryptionKey() throws IOException { ByteArrayInputStream fileStream = new ByteArrayInputStream(BLOB_CONTENT); BlobInfo.Builder infoBuilder = BLOB_INFO1.toBuilder(); - BlobInfo infoWithHashes = infoBuilder.md5(CONTENT_MD5).crc32c(CONTENT_CRC32C).build(); - BlobInfo infoWithoutHashes = infoBuilder.md5(null).crc32c(null).build(); + BlobInfo infoWithHashes = infoBuilder.setMd5(CONTENT_MD5).setCrc32c(CONTENT_CRC32C).build(); + BlobInfo infoWithoutHashes = infoBuilder.setMd5(null).setCrc32c(null).build(); EasyMock.expect( storageRpcMock.create(infoWithoutHashes.toPb(), fileStream, ENCRYPTION_KEY_OPTIONS)) .andReturn(BLOB_INFO1.toPb()).times(2); @@ -490,14 +496,14 @@ public void testGetBucketWithSelectedFields() { EasyMock.replay(storageRpcMock); initializeService(); Bucket bucket = storage.get(BUCKET_NAME1, BUCKET_GET_METAGENERATION, BUCKET_GET_FIELDS); - assertEquals(BUCKET_GET_METAGENERATION.value(), - capturedOptions.getValue().get(BUCKET_GET_METAGENERATION.rpcOption())); - String selector = (String) capturedOptions.getValue().get(BLOB_GET_FIELDS.rpcOption()); + assertEquals(BUCKET_GET_METAGENERATION.getValue(), + capturedOptions.getValue().get(BUCKET_GET_METAGENERATION.getRpcOption())); + String selector = (String) capturedOptions.getValue().get(BLOB_GET_FIELDS.getRpcOption()); assertTrue(selector.contains("name")); assertTrue(selector.contains("location")); assertTrue(selector.contains("acl")); assertEquals(17, selector.length()); - assertEquals(BUCKET_INFO1.name(), bucket.name()); + assertEquals(BUCKET_INFO1.getName(), bucket.getName()); } @Test @@ -509,12 +515,12 @@ public void testGetBucketWithEmptyFields() { initializeService(); Bucket bucket = storage.get(BUCKET_NAME1, BUCKET_GET_METAGENERATION, BUCKET_GET_EMPTY_FIELDS); - assertEquals(BUCKET_GET_METAGENERATION.value(), - capturedOptions.getValue().get(BUCKET_GET_METAGENERATION.rpcOption())); - String selector = (String) capturedOptions.getValue().get(BLOB_GET_FIELDS.rpcOption()); + assertEquals(BUCKET_GET_METAGENERATION.getValue(), + capturedOptions.getValue().get(BUCKET_GET_METAGENERATION.getRpcOption())); + String selector = (String) capturedOptions.getValue().get(BLOB_GET_FIELDS.getRpcOption()); assertTrue(selector.contains("name")); assertEquals(4, selector.length()); - assertEquals(BUCKET_INFO1.name(), bucket.name()); + assertEquals(BUCKET_INFO1.getName(), bucket.getName()); } @Test @@ -542,13 +548,12 @@ public void testGetBlobWithOptions() { @Test public void testGetBlobWithOptionsFromBlobId() { - EasyMock.expect( - storageRpcMock.get(BLOB_INFO1.blobId().toPb(), BLOB_GET_OPTIONS)) + EasyMock.expect(storageRpcMock.get(BLOB_INFO1.getBlobId().toPb(), BLOB_GET_OPTIONS)) .andReturn(BLOB_INFO1.toPb()); EasyMock.replay(storageRpcMock); initializeService(); - Blob blob = - storage.get(BLOB_INFO1.blobId(), BLOB_GET_METAGENERATION, BLOB_GET_GENERATION_FROM_BLOB_ID); + Blob blob = storage.get(BLOB_INFO1.getBlobId(), BLOB_GET_METAGENERATION, + BLOB_GET_GENERATION_FROM_BLOB_ID); assertEquals(expectedBlob1, blob); } @@ -562,11 +567,11 @@ public void testGetBlobWithSelectedFields() { Blob blob = storage.get( BUCKET_NAME1, BLOB_NAME1, BLOB_GET_METAGENERATION, BLOB_GET_GENERATION, BLOB_GET_FIELDS); - assertEquals(BLOB_GET_METAGENERATION.value(), - capturedOptions.getValue().get(BLOB_GET_METAGENERATION.rpcOption())); - assertEquals(BLOB_GET_GENERATION.value(), - capturedOptions.getValue().get(BLOB_GET_GENERATION.rpcOption())); - String selector = (String) capturedOptions.getValue().get(BLOB_GET_FIELDS.rpcOption()); + assertEquals(BLOB_GET_METAGENERATION.getValue(), + capturedOptions.getValue().get(BLOB_GET_METAGENERATION.getRpcOption())); + assertEquals(BLOB_GET_GENERATION.getValue(), + capturedOptions.getValue().get(BLOB_GET_GENERATION.getRpcOption())); + String selector = (String) capturedOptions.getValue().get(BLOB_GET_FIELDS.getRpcOption()); assertTrue(selector.contains("bucket")); assertTrue(selector.contains("name")); assertTrue(selector.contains("contentType")); @@ -584,11 +589,11 @@ public void testGetBlobWithEmptyFields() { initializeService(); Blob blob = storage.get(BUCKET_NAME1, BLOB_NAME1, BLOB_GET_METAGENERATION, BLOB_GET_GENERATION, BLOB_GET_EMPTY_FIELDS); - assertEquals(BLOB_GET_METAGENERATION.value(), - capturedOptions.getValue().get(BLOB_GET_METAGENERATION.rpcOption())); - assertEquals(BLOB_GET_GENERATION.value(), - capturedOptions.getValue().get(BLOB_GET_GENERATION.rpcOption())); - String selector = (String) capturedOptions.getValue().get(BLOB_GET_FIELDS.rpcOption()); + assertEquals(BLOB_GET_METAGENERATION.getValue(), + capturedOptions.getValue().get(BLOB_GET_METAGENERATION.getRpcOption())); + assertEquals(BLOB_GET_GENERATION.getValue(), + capturedOptions.getValue().get(BLOB_GET_GENERATION.getRpcOption())); + String selector = (String) capturedOptions.getValue().get(BLOB_GET_FIELDS.getRpcOption()); assertTrue(selector.contains("bucket")); assertTrue(selector.contains("name")); assertEquals(11, selector.length()); @@ -648,7 +653,7 @@ public void testListBucketsWithSelectedFields() { initializeService(); ImmutableList bucketList = ImmutableList.of(expectedBucket1, expectedBucket2); Page page = storage.list(BUCKET_LIST_FIELDS); - String selector = (String) capturedOptions.getValue().get(BUCKET_LIST_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(BUCKET_LIST_FIELDS.getRpcOption()); assertTrue(selector.contains("items(")); assertTrue(selector.contains("name")); assertTrue(selector.contains("acl")); @@ -672,7 +677,7 @@ public void testListBucketsWithEmptyFields() { initializeService(); ImmutableList bucketList = ImmutableList.of(expectedBucket1, expectedBucket2); Page page = storage.list(BUCKET_LIST_EMPTY_FIELDS); - String selector = (String) capturedOptions.getValue().get(BUCKET_LIST_EMPTY_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(BUCKET_LIST_EMPTY_FIELDS.getRpcOption()); assertTrue(selector.contains("items(")); assertTrue(selector.contains("name")); assertTrue(selector.contains("nextPageToken")); @@ -740,11 +745,11 @@ public void testListBlobsWithSelectedFields() { ImmutableList blobList = ImmutableList.of(expectedBlob1, expectedBlob2); Page page = storage.list(BUCKET_NAME1, BLOB_LIST_PAGE_SIZE, BLOB_LIST_PREFIX, BLOB_LIST_FIELDS); - assertEquals(BLOB_LIST_PAGE_SIZE.value(), - capturedOptions.getValue().get(BLOB_LIST_PAGE_SIZE.rpcOption())); - assertEquals(BLOB_LIST_PREFIX.value(), - capturedOptions.getValue().get(BLOB_LIST_PREFIX.rpcOption())); - String selector = (String) capturedOptions.getValue().get(BLOB_LIST_FIELDS.rpcOption()); + assertEquals(BLOB_LIST_PAGE_SIZE.getValue(), + capturedOptions.getValue().get(BLOB_LIST_PAGE_SIZE.getRpcOption())); + assertEquals(BLOB_LIST_PREFIX.getValue(), + capturedOptions.getValue().get(BLOB_LIST_PREFIX.getRpcOption())); + String selector = (String) capturedOptions.getValue().get(BLOB_LIST_FIELDS.getRpcOption()); assertTrue(selector.contains("prefixes")); assertTrue(selector.contains("items(")); assertTrue(selector.contains("bucket")); @@ -773,11 +778,11 @@ public void testListBlobsWithEmptyFields() { ImmutableList blobList = ImmutableList.of(expectedBlob1, expectedBlob2); Page page = storage.list(BUCKET_NAME1, BLOB_LIST_PAGE_SIZE, BLOB_LIST_PREFIX, BLOB_LIST_EMPTY_FIELDS); - assertEquals(BLOB_LIST_PAGE_SIZE.value(), - capturedOptions.getValue().get(BLOB_LIST_PAGE_SIZE.rpcOption())); - assertEquals(BLOB_LIST_PREFIX.value(), - capturedOptions.getValue().get(BLOB_LIST_PREFIX.rpcOption())); - String selector = (String) capturedOptions.getValue().get(BLOB_LIST_EMPTY_FIELDS.rpcOption()); + assertEquals(BLOB_LIST_PAGE_SIZE.getValue(), + capturedOptions.getValue().get(BLOB_LIST_PAGE_SIZE.getRpcOption())); + assertEquals(BLOB_LIST_PREFIX.getValue(), + capturedOptions.getValue().get(BLOB_LIST_PREFIX.getRpcOption())); + String selector = (String) capturedOptions.getValue().get(BLOB_LIST_EMPTY_FIELDS.getRpcOption()); assertTrue(selector.contains("prefixes")); assertTrue(selector.contains("items(")); assertTrue(selector.contains("bucket")); @@ -807,7 +812,7 @@ public void testListBlobsCurrentDirectory() { @Test public void testUpdateBucket() { - BucketInfo updatedBucketInfo = BUCKET_INFO1.toBuilder().indexPage("some-page").build(); + BucketInfo updatedBucketInfo = BUCKET_INFO1.toBuilder().setIndexPage("some-page").build(); EasyMock.expect(storageRpcMock.patch(updatedBucketInfo.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(updatedBucketInfo.toPb()); EasyMock.replay(storageRpcMock); @@ -818,7 +823,7 @@ public void testUpdateBucket() { @Test public void testUpdateBucketWithOptions() { - BucketInfo updatedBucketInfo = BUCKET_INFO1.toBuilder().indexPage("some-page").build(); + BucketInfo updatedBucketInfo = BUCKET_INFO1.toBuilder().setIndexPage("some-page").build(); EasyMock.expect(storageRpcMock.patch(updatedBucketInfo.toPb(), BUCKET_TARGET_OPTIONS)) .andReturn(updatedBucketInfo.toPb()); EasyMock.replay(storageRpcMock); @@ -831,7 +836,7 @@ public void testUpdateBucketWithOptions() { @Test public void testUpdateBlob() { - BlobInfo updatedBlobInfo = BLOB_INFO1.toBuilder().contentType("some-content-type").build(); + BlobInfo updatedBlobInfo = BLOB_INFO1.toBuilder().setContentType("some-content-type").build(); EasyMock.expect(storageRpcMock.patch(updatedBlobInfo.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(updatedBlobInfo.toPb()); EasyMock.replay(storageRpcMock); @@ -842,7 +847,7 @@ public void testUpdateBlob() { @Test public void testUpdateBlobWithOptions() { - BlobInfo updatedBlobInfo = BLOB_INFO1.toBuilder().contentType("some-content-type").build(); + BlobInfo updatedBlobInfo = BLOB_INFO1.toBuilder().setContentType("some-content-type").build(); EasyMock.expect(storageRpcMock.patch(updatedBlobInfo.toPb(), BLOB_TARGET_OPTIONS_UPDATE)) .andReturn(updatedBlobInfo.toPb()); EasyMock.replay(storageRpcMock); @@ -894,20 +899,19 @@ public void testDeleteBlobWithOptions() { @Test public void testDeleteBlobWithOptionsFromBlobId() { - EasyMock.expect( - storageRpcMock.delete(BLOB_INFO1.blobId().toPb(), BLOB_SOURCE_OPTIONS)) + EasyMock.expect(storageRpcMock.delete(BLOB_INFO1.getBlobId().toPb(), BLOB_SOURCE_OPTIONS)) .andReturn(true); EasyMock.replay(storageRpcMock); initializeService(); - assertTrue(storage.delete(BLOB_INFO1.blobId(), BLOB_SOURCE_GENERATION_FROM_BLOB_ID, + assertTrue(storage.delete(BLOB_INFO1.getBlobId(), BLOB_SOURCE_GENERATION_FROM_BLOB_ID, BLOB_SOURCE_METAGENERATION)); } @Test public void testCompose() { - Storage.ComposeRequest req = Storage.ComposeRequest.builder() + Storage.ComposeRequest req = Storage.ComposeRequest.newBuilder() .addSource(BLOB_NAME2, BLOB_NAME3) - .target(BLOB_INFO1) + .setTarget(BLOB_INFO1) .build(); EasyMock.expect(storageRpcMock.compose(ImmutableList.of(BLOB_INFO2.toPb(), BLOB_INFO3.toPb()), BLOB_INFO1.toPb(), EMPTY_RPC_OPTIONS)).andReturn(BLOB_INFO1.toPb()); @@ -919,10 +923,10 @@ public void testCompose() { @Test public void testComposeWithOptions() { - Storage.ComposeRequest req = Storage.ComposeRequest.builder() + Storage.ComposeRequest req = Storage.ComposeRequest.newBuilder() .addSource(BLOB_NAME2, BLOB_NAME3) - .target(BLOB_INFO1) - .targetOptions(BLOB_TARGET_GENERATION, BLOB_TARGET_METAGENERATION) + .setTarget(BLOB_INFO1) + .setTargetOptions(BLOB_TARGET_GENERATION, BLOB_TARGET_METAGENERATION) .build(); EasyMock.expect(storageRpcMock.compose(ImmutableList.of(BLOB_INFO2.toPb(), BLOB_INFO3.toPb()), BLOB_INFO1.toPb(), BLOB_TARGET_OPTIONS_COMPOSE)).andReturn(BLOB_INFO1.toPb()); @@ -934,8 +938,8 @@ public void testComposeWithOptions() { @Test public void testCopy() { - CopyRequest request = Storage.CopyRequest.of(BLOB_INFO1.blobId(), BLOB_INFO2.blobId()); - StorageRpc.RewriteRequest rpcRequest = new StorageRpc.RewriteRequest(request.source().toPb(), + CopyRequest request = Storage.CopyRequest.of(BLOB_INFO1.getBlobId(), BLOB_INFO2.getBlobId()); + StorageRpc.RewriteRequest rpcRequest = new StorageRpc.RewriteRequest(request.getSource().toPb(), EMPTY_RPC_OPTIONS, false, BLOB_INFO2.toPb(), EMPTY_RPC_OPTIONS, null); StorageRpc.RewriteResponse rpcResponse = new StorageRpc.RewriteResponse(rpcRequest, null, 42L, false, "token", 21L); @@ -943,84 +947,86 @@ public void testCopy() { EasyMock.replay(storageRpcMock); initializeService(); CopyWriter writer = storage.copy(request); - assertEquals(42L, writer.blobSize()); - assertEquals(21L, writer.totalBytesCopied()); + assertEquals(42L, writer.getBlobSize()); + assertEquals(21L, writer.getTotalBytesCopied()); assertTrue(!writer.isDone()); } @Test public void testCopyWithOptions() { - CopyRequest request = Storage.CopyRequest.builder() - .source(BLOB_INFO2.blobId()) - .sourceOptions(BLOB_SOURCE_GENERATION, BLOB_SOURCE_METAGENERATION) - .target(BLOB_INFO1, BLOB_TARGET_GENERATION, BLOB_TARGET_METAGENERATION) + CopyRequest request = Storage.CopyRequest.newBuilder() + .setSource(BLOB_INFO2.getBlobId()) + .setSourceOptions(BLOB_SOURCE_GENERATION, BLOB_SOURCE_METAGENERATION) + .setTarget(BLOB_INFO1, BLOB_TARGET_GENERATION, BLOB_TARGET_METAGENERATION) .build(); - StorageRpc.RewriteRequest rpcRequest = new StorageRpc.RewriteRequest(request.source().toPb(), - BLOB_SOURCE_OPTIONS_COPY, true, request.target().toPb(), BLOB_TARGET_OPTIONS_COMPOSE, null); + StorageRpc.RewriteRequest rpcRequest = new StorageRpc.RewriteRequest(request.getSource().toPb(), + BLOB_SOURCE_OPTIONS_COPY, true, request.getTarget().toPb(), BLOB_TARGET_OPTIONS_COMPOSE, + null); StorageRpc.RewriteResponse rpcResponse = new StorageRpc.RewriteResponse(rpcRequest, null, 42L, false, "token", 21L); EasyMock.expect(storageRpcMock.openRewrite(rpcRequest)).andReturn(rpcResponse); EasyMock.replay(storageRpcMock); initializeService(); CopyWriter writer = storage.copy(request); - assertEquals(42L, writer.blobSize()); - assertEquals(21L, writer.totalBytesCopied()); + assertEquals(42L, writer.getBlobSize()); + assertEquals(21L, writer.getTotalBytesCopied()); assertTrue(!writer.isDone()); } @Test public void testCopyWithEncryptionKey() { - CopyRequest request = Storage.CopyRequest.builder() - .source(BLOB_INFO2.blobId()) - .sourceOptions(BlobSourceOption.decryptionKey(KEY)) - .target(BLOB_INFO1, BlobTargetOption.encryptionKey(BASE64_KEY)) + CopyRequest request = Storage.CopyRequest.newBuilder() + .setSource(BLOB_INFO2.getBlobId()) + .setSourceOptions(BlobSourceOption.decryptionKey(KEY)) + .setTarget(BLOB_INFO1, BlobTargetOption.encryptionKey(BASE64_KEY)) .build(); - StorageRpc.RewriteRequest rpcRequest = new StorageRpc.RewriteRequest(request.source().toPb(), - ENCRYPTION_KEY_OPTIONS, true, request.target().toPb(), ENCRYPTION_KEY_OPTIONS, null); + StorageRpc.RewriteRequest rpcRequest = new StorageRpc.RewriteRequest(request.getSource().toPb(), + ENCRYPTION_KEY_OPTIONS, true, request.getTarget().toPb(), ENCRYPTION_KEY_OPTIONS, null); StorageRpc.RewriteResponse rpcResponse = new StorageRpc.RewriteResponse(rpcRequest, null, 42L, false, "token", 21L); EasyMock.expect(storageRpcMock.openRewrite(rpcRequest)).andReturn(rpcResponse).times(2); EasyMock.replay(storageRpcMock); initializeService(); CopyWriter writer = storage.copy(request); - assertEquals(42L, writer.blobSize()); - assertEquals(21L, writer.totalBytesCopied()); + assertEquals(42L, writer.getBlobSize()); + assertEquals(21L, writer.getTotalBytesCopied()); assertTrue(!writer.isDone()); - request = Storage.CopyRequest.builder() - .source(BLOB_INFO2.blobId()) - .sourceOptions(BlobSourceOption.decryptionKey(BASE64_KEY)) - .target(BLOB_INFO1, BlobTargetOption.encryptionKey(KEY)) + request = Storage.CopyRequest.newBuilder() + .setSource(BLOB_INFO2.getBlobId()) + .setSourceOptions(BlobSourceOption.decryptionKey(BASE64_KEY)) + .setTarget(BLOB_INFO1, BlobTargetOption.encryptionKey(KEY)) .build(); writer = storage.copy(request); - assertEquals(42L, writer.blobSize()); - assertEquals(21L, writer.totalBytesCopied()); + assertEquals(42L, writer.getBlobSize()); + assertEquals(21L, writer.getTotalBytesCopied()); assertTrue(!writer.isDone()); } @Test public void testCopyWithOptionsFromBlobId() { - CopyRequest request = Storage.CopyRequest.builder() - .source(BLOB_INFO1.blobId()) - .sourceOptions(BLOB_SOURCE_GENERATION_FROM_BLOB_ID, BLOB_SOURCE_METAGENERATION) - .target(BLOB_INFO1, BLOB_TARGET_GENERATION, BLOB_TARGET_METAGENERATION) + CopyRequest request = Storage.CopyRequest.newBuilder() + .setSource(BLOB_INFO1.getBlobId()) + .setSourceOptions(BLOB_SOURCE_GENERATION_FROM_BLOB_ID, BLOB_SOURCE_METAGENERATION) + .setTarget(BLOB_INFO1, BLOB_TARGET_GENERATION, BLOB_TARGET_METAGENERATION) .build(); - StorageRpc.RewriteRequest rpcRequest = new StorageRpc.RewriteRequest(request.source().toPb(), - BLOB_SOURCE_OPTIONS_COPY, true, request.target().toPb(), BLOB_TARGET_OPTIONS_COMPOSE, null); + StorageRpc.RewriteRequest rpcRequest = new StorageRpc.RewriteRequest(request.getSource().toPb(), + BLOB_SOURCE_OPTIONS_COPY, true, request.getTarget().toPb(), BLOB_TARGET_OPTIONS_COMPOSE, + null); StorageRpc.RewriteResponse rpcResponse = new StorageRpc.RewriteResponse(rpcRequest, null, 42L, false, "token", 21L); EasyMock.expect(storageRpcMock.openRewrite(rpcRequest)).andReturn(rpcResponse); EasyMock.replay(storageRpcMock); initializeService(); CopyWriter writer = storage.copy(request); - assertEquals(42L, writer.blobSize()); - assertEquals(21L, writer.totalBytesCopied()); + assertEquals(42L, writer.getBlobSize()); + assertEquals(21L, writer.getTotalBytesCopied()); assertTrue(!writer.isDone()); } @Test public void testCopyMultipleRequests() { - CopyRequest request = Storage.CopyRequest.of(BLOB_INFO1.blobId(), BLOB_INFO2.blobId()); - StorageRpc.RewriteRequest rpcRequest = new StorageRpc.RewriteRequest(request.source().toPb(), + CopyRequest request = Storage.CopyRequest.of(BLOB_INFO1.getBlobId(), BLOB_INFO2.getBlobId()); + StorageRpc.RewriteRequest rpcRequest = new StorageRpc.RewriteRequest(request.getSource().toPb(), EMPTY_RPC_OPTIONS, false, BLOB_INFO2.toPb(), EMPTY_RPC_OPTIONS, null); StorageRpc.RewriteResponse rpcResponse1 = new StorageRpc.RewriteResponse(rpcRequest, null, 42L, false, "token", 21L); @@ -1031,13 +1037,13 @@ public void testCopyMultipleRequests() { EasyMock.replay(storageRpcMock); initializeService(); CopyWriter writer = storage.copy(request); - assertEquals(42L, writer.blobSize()); - assertEquals(21L, writer.totalBytesCopied()); + assertEquals(42L, writer.getBlobSize()); + assertEquals(21L, writer.getTotalBytesCopied()); assertTrue(!writer.isDone()); - assertEquals(expectedBlob1, writer.result()); + assertEquals(expectedBlob1, writer.getResult()); assertTrue(writer.isDone()); - assertEquals(42L, writer.totalBytesCopied()); - assertEquals(42L, writer.blobSize()); + assertEquals(42L, writer.getTotalBytesCopied()); + assertEquals(42L, writer.getBlobSize()); } @Test @@ -1081,11 +1087,11 @@ public void testReadAllBytesWithDecriptionKey() { @Test public void testReadAllBytesFromBlobIdWithOptions() { EasyMock.expect( - storageRpcMock.load(BLOB_INFO1.blobId().toPb(), BLOB_SOURCE_OPTIONS)) + storageRpcMock.load(BLOB_INFO1.getBlobId().toPb(), BLOB_SOURCE_OPTIONS)) .andReturn(BLOB_CONTENT); EasyMock.replay(storageRpcMock); initializeService(); - byte[] readBytes = storage.readAllBytes(BLOB_INFO1.blobId(), + byte[] readBytes = storage.readAllBytes(BLOB_INFO1.getBlobId(), BLOB_SOURCE_GENERATION_FROM_BLOB_ID, BLOB_SOURCE_METAGENERATION); assertArrayEquals(BLOB_CONTENT, readBytes); } @@ -1093,15 +1099,15 @@ public void testReadAllBytesFromBlobIdWithOptions() { @Test public void testReadAllBytesFromBlobIdWithDecriptionKey() { EasyMock.expect( - storageRpcMock.load(BLOB_INFO1.blobId().toPb(), ENCRYPTION_KEY_OPTIONS)) + storageRpcMock.load(BLOB_INFO1.getBlobId().toPb(), ENCRYPTION_KEY_OPTIONS)) .andReturn(BLOB_CONTENT).times(2); EasyMock.replay(storageRpcMock); initializeService(); byte[] readBytes = - storage.readAllBytes(BLOB_INFO1.blobId(), BlobSourceOption.decryptionKey(KEY)); + storage.readAllBytes(BLOB_INFO1.getBlobId(), BlobSourceOption.decryptionKey(KEY)); assertArrayEquals(BLOB_CONTENT, readBytes); readBytes = - storage.readAllBytes(BLOB_INFO1.blobId(), BlobSourceOption.decryptionKey(BASE64_KEY)); + storage.readAllBytes(BLOB_INFO1.getBlobId(), BlobSourceOption.decryptionKey(BASE64_KEY)); assertArrayEquals(BLOB_CONTENT, readBytes); } @@ -1164,12 +1170,11 @@ public void testReaderWithDecryptionKey() throws IOException { @Test public void testReaderWithOptionsFromBlobId() throws IOException { byte[] result = new byte[DEFAULT_CHUNK_SIZE]; - EasyMock.expect( - storageRpcMock.read(BLOB_INFO1.blobId().toPb(), BLOB_SOURCE_OPTIONS, 0, DEFAULT_CHUNK_SIZE)) - .andReturn(StorageRpc.Tuple.of("etag", result)); + EasyMock.expect(storageRpcMock.read(BLOB_INFO1.getBlobId().toPb(), BLOB_SOURCE_OPTIONS, 0, + DEFAULT_CHUNK_SIZE)).andReturn(StorageRpc.Tuple.of("etag", result)); EasyMock.replay(storageRpcMock); initializeService(); - ReadChannel channel = storage.reader(BLOB_INFO1.blobId(), + ReadChannel channel = storage.reader(BLOB_INFO1.getBlobId(), BLOB_SOURCE_GENERATION_FROM_BLOB_ID, BLOB_SOURCE_METAGENERATION); assertNotNull(channel); assertTrue(channel.isOpen()); @@ -1179,8 +1184,8 @@ public void testReaderWithOptionsFromBlobId() throws IOException { @Test public void testWriter() { BlobInfo.Builder infoBuilder = BLOB_INFO1.toBuilder(); - BlobInfo infoWithHashes = infoBuilder.md5(CONTENT_MD5).crc32c(CONTENT_CRC32C).build(); - BlobInfo infoWithoutHashes = infoBuilder.md5(null).crc32c(null).build(); + BlobInfo infoWithHashes = infoBuilder.setMd5(CONTENT_MD5).setCrc32c(CONTENT_CRC32C).build(); + BlobInfo infoWithoutHashes = infoBuilder.setMd5(null).setCrc32c(null).build(); EasyMock.expect(storageRpcMock.open(infoWithoutHashes.toPb(), EMPTY_RPC_OPTIONS)) .andReturn("upload-id"); EasyMock.replay(storageRpcMock); @@ -1192,7 +1197,7 @@ public void testWriter() { @Test public void testWriterWithOptions() { - BlobInfo info = BLOB_INFO1.toBuilder().md5(CONTENT_MD5).crc32c(CONTENT_CRC32C).build(); + BlobInfo info = BLOB_INFO1.toBuilder().setMd5(CONTENT_MD5).setCrc32c(CONTENT_CRC32C).build(); EasyMock.expect(storageRpcMock.open(info.toPb(), BLOB_TARGET_OPTIONS_CREATE)) .andReturn("upload-id"); EasyMock.replay(storageRpcMock); @@ -1205,7 +1210,7 @@ public void testWriterWithOptions() { @Test public void testWriterWithEncryptionKey() { - BlobInfo info = BLOB_INFO1.toBuilder().md5(null).crc32c(null).build(); + BlobInfo info = BLOB_INFO1.toBuilder().setMd5(null).setCrc32c(null).build(); EasyMock.expect(storageRpcMock.open(info.toPb(), ENCRYPTION_KEY_OPTIONS)) .andReturn("upload-id").times(2); EasyMock.replay(storageRpcMock); @@ -1252,7 +1257,8 @@ public void testSignUrlLeadingSlash() throws NoSuchAlgorithmException, InvalidKe ServiceAccountAuthCredentials authCredentials = ServiceAccountAuthCredentials.createFor(ACCOUNT, privateKey); storage = options.toBuilder().authCredentials(authCredentials).build().service(); - URL url = storage.signUrl(BlobInfo.builder(BUCKET_NAME1, blobName).build(), 14, TimeUnit.DAYS); + URL url = + storage.signUrl(BlobInfo.newBuilder(BUCKET_NAME1, blobName).build(), 14, TimeUnit.DAYS); String escapedBlobName = UrlEscapers.urlPathSegmentEscaper().escape(blobName); String stringUrl = url.toString(); String expectedUrl = new StringBuilder("https://storage.googleapis.com/").append(BUCKET_NAME1) @@ -1290,9 +1296,9 @@ public void testSignUrlWithOptions() throws NoSuchAlgorithmException, InvalidKey String signature = stringUrl.substring(expectedUrl.length()); StringBuilder signedMessageBuilder = new StringBuilder(); - signedMessageBuilder.append(HttpMethod.POST).append('\n').append(BLOB_INFO1.md5()).append('\n') - .append(BLOB_INFO1.contentType()).append('\n').append(42L + 1209600).append("\n/") - .append(BUCKET_NAME1).append('/').append(BLOB_NAME1); + signedMessageBuilder.append(HttpMethod.POST).append('\n').append(BLOB_INFO1.getMd5()) + .append('\n').append(BLOB_INFO1.getContentType()).append('\n').append(42L + 1209600) + .append("\n/").append(BUCKET_NAME1).append('/').append(BLOB_NAME1); Signature signer = Signature.getInstance("SHA256withRSA"); signer.initVerify(publicKey); @@ -1316,7 +1322,7 @@ public void testSignUrlForBlobWithSpecialChars() throws NoSuchAlgorithmException for (char specialChar : specialChars) { String blobName = "/a" + specialChar + "b"; URL url = - storage.signUrl(BlobInfo.builder(BUCKET_NAME1, blobName).build(), 14, TimeUnit.DAYS); + storage.signUrl(BlobInfo.newBuilder(BUCKET_NAME1, blobName).build(), 14, TimeUnit.DAYS); String escapedBlobName = UrlEscapers.urlPathSegmentEscaper().escape(blobName); String stringUrl = url.toString(); String expectedUrl = new StringBuilder("https://storage.googleapis.com/").append(BUCKET_NAME1) @@ -1506,7 +1512,7 @@ public void testDeleteBucketAcl() { @Test public void testCreateBucketAcl() { - Acl returnedAcl = ACL.toBuilder().etag("ETAG").id("ID").build(); + Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); EasyMock.expect(storageRpcMock.createAcl(ACL.toBucketPb().setBucket(BUCKET_NAME1))) .andReturn(returnedAcl.toBucketPb()); EasyMock.replay(storageRpcMock); @@ -1517,7 +1523,7 @@ public void testCreateBucketAcl() { @Test public void testUpdateBucketAcl() { - Acl returnedAcl = ACL.toBuilder().etag("ETAG").id("ID").build(); + Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); EasyMock.expect(storageRpcMock.patchAcl(ACL.toBucketPb().setBucket(BUCKET_NAME1))) .andReturn(returnedAcl.toBucketPb()); EasyMock.replay(storageRpcMock); @@ -1566,7 +1572,7 @@ public void testDeleteDefaultBucketAcl() { @Test public void testCreateDefaultBucketAcl() { - Acl returnedAcl = ACL.toBuilder().etag("ETAG").id("ID").build(); + Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); EasyMock.expect(storageRpcMock.createDefaultAcl(ACL.toObjectPb().setBucket(BUCKET_NAME1))) .andReturn(returnedAcl.toObjectPb()); EasyMock.replay(storageRpcMock); @@ -1577,7 +1583,7 @@ public void testCreateDefaultBucketAcl() { @Test public void testUpdateDefaultBucketAcl() { - Acl returnedAcl = ACL.toBuilder().etag("ETAG").id("ID").build(); + Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); EasyMock.expect(storageRpcMock.patchDefaultAcl(ACL.toObjectPb().setBucket(BUCKET_NAME1))) .andReturn(returnedAcl.toObjectPb()); EasyMock.replay(storageRpcMock); @@ -1631,7 +1637,7 @@ public void testDeleteBlobAcl() { @Test public void testCreateBlobAcl() { BlobId blobId = BlobId.of(BUCKET_NAME1, BLOB_NAME1, 42L); - Acl returnedAcl = ACL.toBuilder().etag("ETAG").id("ID").build(); + Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); EasyMock.expect(storageRpcMock.createAcl(ACL.toObjectPb() .setBucket(BUCKET_NAME1) .setObject(BLOB_NAME1) @@ -1646,7 +1652,7 @@ public void testCreateBlobAcl() { @Test public void testUpdateBlobAcl() { BlobId blobId = BlobId.of(BUCKET_NAME1, BLOB_NAME1, 42L); - Acl returnedAcl = ACL.toBuilder().etag("ETAG").id("ID").build(); + Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); EasyMock.expect(storageRpcMock.patchAcl(ACL.toObjectPb() .setBucket(BUCKET_NAME1) .setObject(BLOB_NAME1) diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java index cc2f820f6675..3a9b7c16c93c 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java @@ -104,7 +104,7 @@ public class ITStorageTest { @BeforeClass public static void beforeClass() throws NoSuchAlgorithmException, InvalidKeySpecException { RemoteStorageHelper helper = RemoteStorageHelper.create(); - storage = helper.options().service(); + storage = helper.getOptions().service(); storage.create(BucketInfo.of(BUCKET)); } @@ -129,45 +129,45 @@ public void testListBuckets() throws InterruptedException { } while (bucketIterator.hasNext()) { Bucket remoteBucket = bucketIterator.next(); - assertTrue(remoteBucket.name().startsWith(BUCKET)); - assertNull(remoteBucket.createTime()); - assertNull(remoteBucket.selfLink()); + assertTrue(remoteBucket.getName().startsWith(BUCKET)); + assertNull(remoteBucket.getCreateTime()); + assertNull(remoteBucket.getSelfLink()); } } @Test public void testGetBucketSelectedFields() { Bucket remoteBucket = storage.get(BUCKET, Storage.BucketGetOption.fields(BucketField.ID)); - assertEquals(BUCKET, remoteBucket.name()); - assertNull(remoteBucket.createTime()); - assertNotNull(remoteBucket.generatedId()); + assertEquals(BUCKET, remoteBucket.getName()); + assertNull(remoteBucket.getCreateTime()); + assertNotNull(remoteBucket.getGeneratedId()); } @Test public void testGetBucketAllSelectedFields() { Bucket remoteBucket = storage.get(BUCKET, Storage.BucketGetOption.fields(BucketField.values())); - assertEquals(BUCKET, remoteBucket.name()); - assertNotNull(remoteBucket.createTime()); - assertNotNull(remoteBucket.selfLink()); + assertEquals(BUCKET, remoteBucket.getName()); + assertNotNull(remoteBucket.getCreateTime()); + assertNotNull(remoteBucket.getSelfLink()); } @Test public void testGetBucketEmptyFields() { Bucket remoteBucket = storage.get(BUCKET, Storage.BucketGetOption.fields()); - assertEquals(BUCKET, remoteBucket.name()); - assertNull(remoteBucket.createTime()); - assertNull(remoteBucket.selfLink()); + assertEquals(BUCKET, remoteBucket.getName()); + assertNull(remoteBucket.getCreateTime()); + assertNull(remoteBucket.getSelfLink()); } @Test public void testCreateBlob() { String blobName = "test-create-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob, BLOB_BYTE_CONTENT); assertNotNull(remoteBlob); - assertEquals(blob.bucket(), remoteBlob.bucket()); - assertEquals(blob.name(), remoteBlob.name()); + assertEquals(blob.getBucket(), remoteBlob.getBucket()); + assertEquals(blob.getName(), remoteBlob.getName()); byte[] readBytes = storage.readAllBytes(BUCKET, blobName); assertArrayEquals(BLOB_BYTE_CONTENT, readBytes); assertTrue(remoteBlob.delete()); @@ -176,12 +176,12 @@ public void testCreateBlob() { @Test public void testCreateBlobWithEncryptionKey() { String blobName = "test-create-with-customer-key-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob, BLOB_BYTE_CONTENT, Storage.BlobTargetOption.encryptionKey(KEY)); assertNotNull(remoteBlob); - assertEquals(blob.bucket(), remoteBlob.bucket()); - assertEquals(blob.name(), remoteBlob.name()); + assertEquals(blob.getBucket(), remoteBlob.getBucket()); + assertEquals(blob.getName(), remoteBlob.getName()); byte[] readBytes = storage.readAllBytes(BUCKET, blobName, Storage.BlobSourceOption.decryptionKey(BASE64_KEY)); assertArrayEquals(BLOB_BYTE_CONTENT, readBytes); @@ -191,11 +191,11 @@ public void testCreateBlobWithEncryptionKey() { @Test public void testCreateEmptyBlob() { String blobName = "test-create-empty-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob); assertNotNull(remoteBlob); - assertEquals(blob.bucket(), remoteBlob.bucket()); - assertEquals(blob.name(), remoteBlob.name()); + assertEquals(blob.getBucket(), remoteBlob.getBucket()); + assertEquals(blob.getName(), remoteBlob.getName()); byte[] readBytes = storage.readAllBytes(BUCKET, blobName); assertArrayEquals(new byte[0], readBytes); assertTrue(remoteBlob.delete()); @@ -204,13 +204,13 @@ public void testCreateEmptyBlob() { @Test public void testCreateBlobStream() { String blobName = "test-create-blob-stream"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).contentType(CONTENT_TYPE).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).setContentType(CONTENT_TYPE).build(); ByteArrayInputStream stream = new ByteArrayInputStream(BLOB_STRING_CONTENT.getBytes(UTF_8)); Blob remoteBlob = storage.create(blob, stream); assertNotNull(remoteBlob); - assertEquals(blob.bucket(), remoteBlob.bucket()); - assertEquals(blob.name(), remoteBlob.name()); - assertEquals(blob.contentType(), remoteBlob.contentType()); + assertEquals(blob.getBucket(), remoteBlob.getBucket()); + assertEquals(blob.getName(), remoteBlob.getName()); + assertEquals(blob.getContentType(), remoteBlob.getContentType()); byte[] readBytes = storage.readAllBytes(BUCKET, blobName); assertEquals(BLOB_STRING_CONTENT, new String(readBytes, UTF_8)); assertTrue(remoteBlob.delete()); @@ -219,10 +219,10 @@ public void testCreateBlobStream() { @Test public void testCreateBlobFail() { String blobName = "test-create-blob-fail"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob); assertNotNull(remoteBlob); - BlobInfo wrongGenerationBlob = BlobInfo.builder(BUCKET, blobName, -1L).build(); + BlobInfo wrongGenerationBlob = BlobInfo.newBuilder(BUCKET, blobName, -1L).build(); try { storage.create(wrongGenerationBlob, BLOB_BYTE_CONTENT, Storage.BlobTargetOption.generationMatch()); @@ -236,9 +236,9 @@ public void testCreateBlobFail() { @Test public void testCreateBlobMd5Fail() { String blobName = "test-create-blob-md5-fail"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName) - .contentType(CONTENT_TYPE) - .md5("O1R4G1HJSDUISJjoIYmVhQ==") + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName) + .setContentType(CONTENT_TYPE) + .setMd5("O1R4G1HJSDUISJjoIYmVhQ==") .build(); ByteArrayInputStream stream = new ByteArrayInputStream(BLOB_STRING_CONTENT.getBytes(UTF_8)); try { @@ -252,52 +252,52 @@ public void testCreateBlobMd5Fail() { @Test public void testGetBlobEmptySelectedFields() { String blobName = "test-get-empty-selected-fields-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).contentType(CONTENT_TYPE).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).setContentType(CONTENT_TYPE).build(); assertNotNull(storage.create(blob)); - Blob remoteBlob = storage.get(blob.blobId(), Storage.BlobGetOption.fields()); - assertEquals(blob.blobId(), remoteBlob.blobId()); - assertNull(remoteBlob.contentType()); + Blob remoteBlob = storage.get(blob.getBlobId(), Storage.BlobGetOption.fields()); + assertEquals(blob.getBlobId(), remoteBlob.getBlobId()); + assertNull(remoteBlob.getContentType()); assertTrue(remoteBlob.delete()); } @Test public void testGetBlobSelectedFields() { String blobName = "test-get-selected-fields-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName) - .contentType(CONTENT_TYPE) - .metadata(ImmutableMap.of("k", "v")) + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName) + .setContentType(CONTENT_TYPE) + .setMetadata(ImmutableMap.of("k", "v")) .build(); assertNotNull(storage.create(blob)); - Blob remoteBlob = storage.get(blob.blobId(), Storage.BlobGetOption.fields( + Blob remoteBlob = storage.get(blob.getBlobId(), Storage.BlobGetOption.fields( BlobField.METADATA)); - assertEquals(blob.blobId(), remoteBlob.blobId()); - assertEquals(ImmutableMap.of("k", "v"), remoteBlob.metadata()); - assertNull(remoteBlob.contentType()); + assertEquals(blob.getBlobId(), remoteBlob.getBlobId()); + assertEquals(ImmutableMap.of("k", "v"), remoteBlob.getMetadata()); + assertNull(remoteBlob.getContentType()); assertTrue(remoteBlob.delete()); } @Test public void testGetBlobAllSelectedFields() { String blobName = "test-get-all-selected-fields-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName) - .contentType(CONTENT_TYPE) - .metadata(ImmutableMap.of("k", "v")) + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName) + .setContentType(CONTENT_TYPE) + .setMetadata(ImmutableMap.of("k", "v")) .build(); assertNotNull(storage.create(blob)); - Blob remoteBlob = storage.get(blob.blobId(), + Blob remoteBlob = storage.get(blob.getBlobId(), Storage.BlobGetOption.fields(BlobField.values())); - assertEquals(blob.bucket(), remoteBlob.bucket()); - assertEquals(blob.name(), remoteBlob.name()); - assertEquals(ImmutableMap.of("k", "v"), remoteBlob.metadata()); - assertNotNull(remoteBlob.generatedId()); - assertNotNull(remoteBlob.selfLink()); + assertEquals(blob.getBucket(), remoteBlob.getBucket()); + assertEquals(blob.getName(), remoteBlob.getName()); + assertEquals(ImmutableMap.of("k", "v"), remoteBlob.getMetadata()); + assertNotNull(remoteBlob.getGeneratedId()); + assertNotNull(remoteBlob.getSelfLink()); assertTrue(remoteBlob.delete()); } @Test public void testGetBlobFail() { String blobName = "test-get-blob-fail"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob); assertNotNull(remoteBlob); BlobId wrongGenerationBlob = BlobId.of(BUCKET, blobName); @@ -313,7 +313,7 @@ public void testGetBlobFail() { @Test public void testGetBlobFailNonExistingGeneration() { String blobName = "test-get-blob-fail-non-existing-generation"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob); assertNotNull(remoteBlob); BlobId wrongGenerationBlob = BlobId.of(BUCKET, blobName, -1L); @@ -326,13 +326,13 @@ public void testListBlobsSelectedFields() throws InterruptedException { String[] blobNames = {"test-list-blobs-selected-fields-blob1", "test-list-blobs-selected-fields-blob2"}; ImmutableMap metadata = ImmutableMap.of("k", "v"); - BlobInfo blob1 = BlobInfo.builder(BUCKET, blobNames[0]) - .contentType(CONTENT_TYPE) - .metadata(metadata) + BlobInfo blob1 = BlobInfo.newBuilder(BUCKET, blobNames[0]) + .setContentType(CONTENT_TYPE) + .setMetadata(metadata) .build(); - BlobInfo blob2 = BlobInfo.builder(BUCKET, blobNames[1]) - .contentType(CONTENT_TYPE) - .metadata(metadata) + BlobInfo blob2 = BlobInfo.newBuilder(BUCKET, blobNames[1]) + .setContentType(CONTENT_TYPE) + .setMetadata(metadata) .build(); Blob remoteBlob1 = storage.create(blob1); Blob remoteBlob2 = storage.create(blob2); @@ -353,10 +353,10 @@ public void testListBlobsSelectedFields() throws InterruptedException { Iterator iterator = page.iterateAll(); while (iterator.hasNext()) { Blob remoteBlob = iterator.next(); - assertEquals(BUCKET, remoteBlob.bucket()); - assertTrue(blobSet.contains(remoteBlob.name())); - assertEquals(metadata, remoteBlob.metadata()); - assertNull(remoteBlob.contentType()); + assertEquals(BUCKET, remoteBlob.getBucket()); + assertTrue(blobSet.contains(remoteBlob.getName())); + assertEquals(metadata, remoteBlob.getMetadata()); + assertNull(remoteBlob.getContentType()); } assertTrue(remoteBlob1.delete()); assertTrue(remoteBlob2.delete()); @@ -366,11 +366,11 @@ public void testListBlobsSelectedFields() throws InterruptedException { public void testListBlobsEmptySelectedFields() throws InterruptedException { String[] blobNames = {"test-list-blobs-empty-selected-fields-blob1", "test-list-blobs-empty-selected-fields-blob2"}; - BlobInfo blob1 = BlobInfo.builder(BUCKET, blobNames[0]) - .contentType(CONTENT_TYPE) + BlobInfo blob1 = BlobInfo.newBuilder(BUCKET, blobNames[0]) + .setContentType(CONTENT_TYPE) .build(); - BlobInfo blob2 = BlobInfo.builder(BUCKET, blobNames[1]) - .contentType(CONTENT_TYPE) + BlobInfo blob2 = BlobInfo.newBuilder(BUCKET, blobNames[1]) + .setContentType(CONTENT_TYPE) .build(); Blob remoteBlob1 = storage.create(blob1); Blob remoteBlob2 = storage.create(blob2); @@ -391,9 +391,9 @@ public void testListBlobsEmptySelectedFields() throws InterruptedException { Iterator iterator = page.iterateAll(); while (iterator.hasNext()) { Blob remoteBlob = iterator.next(); - assertEquals(BUCKET, remoteBlob.bucket()); - assertTrue(blobSet.contains(remoteBlob.name())); - assertNull(remoteBlob.contentType()); + assertEquals(BUCKET, remoteBlob.getBucket()); + assertTrue(blobSet.contains(remoteBlob.getName())); + assertNull(remoteBlob.getContentType()); } assertTrue(remoteBlob1.delete()); assertTrue(remoteBlob2.delete()); @@ -402,14 +402,15 @@ public void testListBlobsEmptySelectedFields() throws InterruptedException { @Test(timeout = 15000) public void testListBlobsVersioned() throws ExecutionException, InterruptedException { String bucketName = RemoteStorageHelper.generateBucketName(); - Bucket bucket = storage.create(BucketInfo.builder(bucketName).versioningEnabled(true).build()); + Bucket bucket = + storage.create(BucketInfo.newBuilder(bucketName).setVersioningEnabled(true).build()); try { String[] blobNames = {"test-list-blobs-versioned-blob1", "test-list-blobs-versioned-blob2"}; - BlobInfo blob1 = BlobInfo.builder(bucket, blobNames[0]) - .contentType(CONTENT_TYPE) + BlobInfo blob1 = BlobInfo.newBuilder(bucket, blobNames[0]) + .setContentType(CONTENT_TYPE) .build(); - BlobInfo blob2 = BlobInfo.builder(bucket, blobNames[1]) - .contentType(CONTENT_TYPE) + BlobInfo blob2 = BlobInfo.newBuilder(bucket, blobNames[1]) + .setContentType(CONTENT_TYPE) .build(); Blob remoteBlob1 = storage.create(blob1); Blob remoteBlob2 = storage.create(blob2); @@ -432,9 +433,9 @@ public void testListBlobsVersioned() throws ExecutionException, InterruptedExcep Iterator iterator = page.iterateAll(); while (iterator.hasNext()) { Blob remoteBlob = iterator.next(); - assertEquals(bucketName, remoteBlob.bucket()); - assertTrue(blobSet.contains(remoteBlob.name())); - assertNotNull(remoteBlob.generation()); + assertEquals(bucketName, remoteBlob.getBucket()); + assertTrue(blobSet.contains(remoteBlob.getName())); + assertNotNull(remoteBlob.getGeneration()); } assertTrue(remoteBlob1.delete()); assertTrue(remoteBlob2.delete()); @@ -450,11 +451,11 @@ public void testListBlobsCurrentDirectory() throws InterruptedException { String subdirectoryName = "subdirectory/"; String[] blobNames = {directoryName + subdirectoryName + "blob1", directoryName + "blob2"}; - BlobInfo blob1 = BlobInfo.builder(BUCKET, blobNames[0]) - .contentType(CONTENT_TYPE) + BlobInfo blob1 = BlobInfo.newBuilder(BUCKET, blobNames[0]) + .setContentType(CONTENT_TYPE) .build(); - BlobInfo blob2 = BlobInfo.builder(BUCKET, blobNames[1]) - .contentType(CONTENT_TYPE) + BlobInfo blob2 = BlobInfo.newBuilder(BUCKET, blobNames[1]) + .setContentType(CONTENT_TYPE) .build(); Blob remoteBlob1 = storage.create(blob1, BLOB_BYTE_CONTENT); Blob remoteBlob2 = storage.create(blob2, BLOB_BYTE_CONTENT); @@ -474,16 +475,16 @@ public void testListBlobsCurrentDirectory() throws InterruptedException { Iterator iterator = page.iterateAll(); while (iterator.hasNext()) { Blob remoteBlob = iterator.next(); - assertEquals(BUCKET, remoteBlob.bucket()); - if (remoteBlob.name().equals(blobNames[1])) { - assertEquals(CONTENT_TYPE, remoteBlob.contentType()); - assertEquals(BLOB_BYTE_CONTENT.length, (long) remoteBlob.size()); + assertEquals(BUCKET, remoteBlob.getBucket()); + if (remoteBlob.getName().equals(blobNames[1])) { + assertEquals(CONTENT_TYPE, remoteBlob.getContentType()); + assertEquals(BLOB_BYTE_CONTENT.length, (long) remoteBlob.getSize()); assertFalse(remoteBlob.isDirectory()); - } else if (remoteBlob.name().equals(directoryName + subdirectoryName)) { - assertEquals(0L, (long) remoteBlob.size()); + } else if (remoteBlob.getName().equals(directoryName + subdirectoryName)) { + assertEquals(0L, (long) remoteBlob.getSize()); assertTrue(remoteBlob.isDirectory()); } else { - fail("Unexpected blob with name " + remoteBlob.name()); + fail("Unexpected blob with name " + remoteBlob.getName()); } } assertTrue(remoteBlob1.delete()); @@ -493,14 +494,14 @@ public void testListBlobsCurrentDirectory() throws InterruptedException { @Test public void testUpdateBlob() { String blobName = "test-update-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob); assertNotNull(remoteBlob); - Blob updatedBlob = remoteBlob.toBuilder().contentType(CONTENT_TYPE).build().update(); + Blob updatedBlob = remoteBlob.toBuilder().setContentType(CONTENT_TYPE).build().update(); assertNotNull(updatedBlob); - assertEquals(blob.name(), updatedBlob.name()); - assertEquals(blob.bucket(), updatedBlob.bucket()); - assertEquals(CONTENT_TYPE, updatedBlob.contentType()); + assertEquals(blob.getName(), updatedBlob.getName()); + assertEquals(blob.getBucket(), updatedBlob.getBucket()); + assertEquals(CONTENT_TYPE, updatedBlob.getContentType()); assertTrue(updatedBlob.delete()); } @@ -509,19 +510,19 @@ public void testUpdateBlobReplaceMetadata() { String blobName = "test-update-blob-replace-metadata"; ImmutableMap metadata = ImmutableMap.of("k1", "a"); ImmutableMap newMetadata = ImmutableMap.of("k2", "b"); - BlobInfo blob = BlobInfo.builder(BUCKET, blobName) - .contentType(CONTENT_TYPE) - .metadata(metadata) + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName) + .setContentType(CONTENT_TYPE) + .setMetadata(metadata) .build(); Blob remoteBlob = storage.create(blob); assertNotNull(remoteBlob); - Blob updatedBlob = remoteBlob.toBuilder().metadata(null).build().update(); + Blob updatedBlob = remoteBlob.toBuilder().setMetadata(null).build().update(); assertNotNull(updatedBlob); - assertNull(updatedBlob.metadata()); - updatedBlob = remoteBlob.toBuilder().metadata(newMetadata).build().update(); - assertEquals(blob.name(), updatedBlob.name()); - assertEquals(blob.bucket(), updatedBlob.bucket()); - assertEquals(newMetadata, updatedBlob.metadata()); + assertNull(updatedBlob.getMetadata()); + updatedBlob = remoteBlob.toBuilder().setMetadata(newMetadata).build().update(); + assertEquals(blob.getName(), updatedBlob.getName()); + assertEquals(blob.getBucket(), updatedBlob.getBucket()); + assertEquals(newMetadata, updatedBlob.getMetadata()); assertTrue(updatedBlob.delete()); } @@ -531,17 +532,17 @@ public void testUpdateBlobMergeMetadata() { ImmutableMap metadata = ImmutableMap.of("k1", "a"); ImmutableMap newMetadata = ImmutableMap.of("k2", "b"); ImmutableMap expectedMetadata = ImmutableMap.of("k1", "a", "k2", "b"); - BlobInfo blob = BlobInfo.builder(BUCKET, blobName) - .contentType(CONTENT_TYPE) - .metadata(metadata) + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName) + .setContentType(CONTENT_TYPE) + .setMetadata(metadata) .build(); Blob remoteBlob = storage.create(blob); assertNotNull(remoteBlob); - Blob updatedBlob = remoteBlob.toBuilder().metadata(newMetadata).build().update(); + Blob updatedBlob = remoteBlob.toBuilder().setMetadata(newMetadata).build().update(); assertNotNull(updatedBlob); - assertEquals(blob.name(), updatedBlob.name()); - assertEquals(blob.bucket(), updatedBlob.bucket()); - assertEquals(expectedMetadata, updatedBlob.metadata()); + assertEquals(blob.getName(), updatedBlob.getName()); + assertEquals(blob.getBucket(), updatedBlob.getBucket()); + assertEquals(expectedMetadata, updatedBlob.getMetadata()); assertTrue(updatedBlob.delete()); } @@ -553,28 +554,28 @@ public void testUpdateBlobUnsetMetadata() { newMetadata.put("k1", "a"); newMetadata.put("k2", null); ImmutableMap expectedMetadata = ImmutableMap.of("k1", "a"); - BlobInfo blob = BlobInfo.builder(BUCKET, blobName) - .contentType(CONTENT_TYPE) - .metadata(metadata) + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName) + .setContentType(CONTENT_TYPE) + .setMetadata(metadata) .build(); Blob remoteBlob = storage.create(blob); assertNotNull(remoteBlob); - Blob updatedBlob = remoteBlob.toBuilder().metadata(newMetadata).build().update(); + Blob updatedBlob = remoteBlob.toBuilder().setMetadata(newMetadata).build().update(); assertNotNull(updatedBlob); - assertEquals(blob.name(), updatedBlob.name()); - assertEquals(blob.bucket(), updatedBlob.bucket()); - assertEquals(expectedMetadata, updatedBlob.metadata()); + assertEquals(blob.getName(), updatedBlob.getName()); + assertEquals(blob.getBucket(), updatedBlob.getBucket()); + assertEquals(expectedMetadata, updatedBlob.getMetadata()); assertTrue(updatedBlob.delete()); } @Test public void testUpdateBlobFail() { String blobName = "test-update-blob-fail"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob); assertNotNull(remoteBlob); - BlobInfo wrongGenerationBlob = BlobInfo.builder(BUCKET, blobName, -1L) - .contentType(CONTENT_TYPE) + BlobInfo wrongGenerationBlob = BlobInfo.newBuilder(BUCKET, blobName, -1L) + .setContentType(CONTENT_TYPE) .build(); try { storage.update(wrongGenerationBlob, Storage.BlobTargetOption.generationMatch()); @@ -594,7 +595,7 @@ public void testDeleteNonExistingBlob() { @Test public void testDeleteBlobNonExistingGeneration() { String blobName = "test-delete-blob-non-existing-generation"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); assertNotNull(storage.create(blob)); assertFalse(storage.delete(BlobId.of(BUCKET, blobName, -1L))); } @@ -602,11 +603,11 @@ public void testDeleteBlobNonExistingGeneration() { @Test public void testDeleteBlobFail() { String blobName = "test-delete-blob-fail"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob); assertNotNull(remoteBlob); try { - storage.delete(BUCKET, blob.name(), Storage.BlobSourceOption.generationMatch(-1L)); + storage.delete(BUCKET, blob.getName(), Storage.BlobSourceOption.generationMatch(-1L)); fail("StorageException was expected"); } catch (StorageException ex) { // expected @@ -618,21 +619,21 @@ public void testDeleteBlobFail() { public void testComposeBlob() { String sourceBlobName1 = "test-compose-blob-source-1"; String sourceBlobName2 = "test-compose-blob-source-2"; - BlobInfo sourceBlob1 = BlobInfo.builder(BUCKET, sourceBlobName1).build(); - BlobInfo sourceBlob2 = BlobInfo.builder(BUCKET, sourceBlobName2).build(); + BlobInfo sourceBlob1 = BlobInfo.newBuilder(BUCKET, sourceBlobName1).build(); + BlobInfo sourceBlob2 = BlobInfo.newBuilder(BUCKET, sourceBlobName2).build(); Blob remoteSourceBlob1 = storage.create(sourceBlob1, BLOB_BYTE_CONTENT); Blob remoteSourceBlob2 = storage.create(sourceBlob2, BLOB_BYTE_CONTENT); assertNotNull(remoteSourceBlob1); assertNotNull(remoteSourceBlob2); String targetBlobName = "test-compose-blob-target"; - BlobInfo targetBlob = BlobInfo.builder(BUCKET, targetBlobName).build(); + BlobInfo targetBlob = BlobInfo.newBuilder(BUCKET, targetBlobName).build(); Storage.ComposeRequest req = Storage.ComposeRequest.of(ImmutableList.of(sourceBlobName1, sourceBlobName2), targetBlob); Blob remoteTargetBlob = storage.compose(req); assertNotNull(remoteTargetBlob); - assertEquals(targetBlob.name(), remoteTargetBlob.name()); - assertEquals(targetBlob.bucket(), remoteTargetBlob.bucket()); - assertNull(remoteTargetBlob.contentType()); + assertEquals(targetBlob.getName(), remoteTargetBlob.getName()); + assertEquals(targetBlob.getBucket(), remoteTargetBlob.getBucket()); + assertNull(remoteTargetBlob.getContentType()); byte[] readBytes = storage.readAllBytes(BUCKET, targetBlobName); byte[] composedBytes = Arrays.copyOf(BLOB_BYTE_CONTENT, BLOB_BYTE_CONTENT.length * 2); System.arraycopy(BLOB_BYTE_CONTENT, 0, composedBytes, BLOB_BYTE_CONTENT.length, @@ -647,22 +648,22 @@ public void testComposeBlob() { public void testComposeBlobWithContentType() { String sourceBlobName1 = "test-compose-blob-with-content-type-source-1"; String sourceBlobName2 = "test-compose-blob-with-content-type-source-2"; - BlobInfo sourceBlob1 = BlobInfo.builder(BUCKET, sourceBlobName1).build(); - BlobInfo sourceBlob2 = BlobInfo.builder(BUCKET, sourceBlobName2).build(); + BlobInfo sourceBlob1 = BlobInfo.newBuilder(BUCKET, sourceBlobName1).build(); + BlobInfo sourceBlob2 = BlobInfo.newBuilder(BUCKET, sourceBlobName2).build(); Blob remoteSourceBlob1 = storage.create(sourceBlob1, BLOB_BYTE_CONTENT); Blob remoteSourceBlob2 = storage.create(sourceBlob2, BLOB_BYTE_CONTENT); assertNotNull(remoteSourceBlob1); assertNotNull(remoteSourceBlob2); String targetBlobName = "test-compose-blob-with-content-type-target"; BlobInfo targetBlob = - BlobInfo.builder(BUCKET, targetBlobName).contentType(CONTENT_TYPE).build(); + BlobInfo.newBuilder(BUCKET, targetBlobName).setContentType(CONTENT_TYPE).build(); Storage.ComposeRequest req = Storage.ComposeRequest.of(ImmutableList.of(sourceBlobName1, sourceBlobName2), targetBlob); Blob remoteTargetBlob = storage.compose(req); assertNotNull(remoteTargetBlob); - assertEquals(targetBlob.name(), remoteTargetBlob.name()); - assertEquals(targetBlob.bucket(), remoteTargetBlob.bucket()); - assertEquals(CONTENT_TYPE, remoteTargetBlob.contentType()); + assertEquals(targetBlob.getName(), remoteTargetBlob.getName()); + assertEquals(targetBlob.getBucket(), remoteTargetBlob.getBucket()); + assertEquals(CONTENT_TYPE, remoteTargetBlob.getContentType()); byte[] readBytes = storage.readAllBytes(BUCKET, targetBlobName); byte[] composedBytes = Arrays.copyOf(BLOB_BYTE_CONTENT, BLOB_BYTE_CONTENT.length * 2); System.arraycopy(BLOB_BYTE_CONTENT, 0, composedBytes, BLOB_BYTE_CONTENT.length, @@ -677,18 +678,18 @@ public void testComposeBlobWithContentType() { public void testComposeBlobFail() { String sourceBlobName1 = "test-compose-blob-fail-source-1"; String sourceBlobName2 = "test-compose-blob-fail-source-2"; - BlobInfo sourceBlob1 = BlobInfo.builder(BUCKET, sourceBlobName1).build(); - BlobInfo sourceBlob2 = BlobInfo.builder(BUCKET, sourceBlobName2).build(); + BlobInfo sourceBlob1 = BlobInfo.newBuilder(BUCKET, sourceBlobName1).build(); + BlobInfo sourceBlob2 = BlobInfo.newBuilder(BUCKET, sourceBlobName2).build(); Blob remoteSourceBlob1 = storage.create(sourceBlob1); Blob remoteSourceBlob2 = storage.create(sourceBlob2); assertNotNull(remoteSourceBlob1); assertNotNull(remoteSourceBlob2); String targetBlobName = "test-compose-blob-fail-target"; - BlobInfo targetBlob = BlobInfo.builder(BUCKET, targetBlobName).build(); - Storage.ComposeRequest req = Storage.ComposeRequest.builder() + BlobInfo targetBlob = BlobInfo.newBuilder(BUCKET, targetBlobName).build(); + Storage.ComposeRequest req = Storage.ComposeRequest.newBuilder() .addSource(sourceBlobName1, -1L) .addSource(sourceBlobName2, -1L) - .target(targetBlob) + .setTarget(targetBlob) .build(); try { storage.compose(req); @@ -705,19 +706,19 @@ public void testCopyBlob() { String sourceBlobName = "test-copy-blob-source"; BlobId source = BlobId.of(BUCKET, sourceBlobName); ImmutableMap metadata = ImmutableMap.of("k", "v"); - BlobInfo blob = BlobInfo.builder(source) - .contentType(CONTENT_TYPE) - .metadata(metadata) + BlobInfo blob = BlobInfo.newBuilder(source) + .setContentType(CONTENT_TYPE) + .setMetadata(metadata) .build(); Blob remoteBlob = storage.create(blob, BLOB_BYTE_CONTENT); assertNotNull(remoteBlob); String targetBlobName = "test-copy-blob-target"; Storage.CopyRequest req = Storage.CopyRequest.of(source, BlobId.of(BUCKET, targetBlobName)); CopyWriter copyWriter = storage.copy(req); - assertEquals(BUCKET, copyWriter.result().bucket()); - assertEquals(targetBlobName, copyWriter.result().name()); - assertEquals(CONTENT_TYPE, copyWriter.result().contentType()); - assertEquals(metadata, copyWriter.result().metadata()); + assertEquals(BUCKET, copyWriter.getResult().getBucket()); + assertEquals(targetBlobName, copyWriter.getResult().getName()); + assertEquals(CONTENT_TYPE, copyWriter.getResult().getContentType()); + assertEquals(metadata, copyWriter.getResult().getMetadata()); assertTrue(copyWriter.isDone()); assertTrue(remoteBlob.delete()); assertTrue(storage.delete(BUCKET, targetBlobName)); @@ -728,38 +729,38 @@ public void testCopyBlobWithEncryptionKeys() { String sourceBlobName = "test-copy-blob-encryption-key-source"; BlobId source = BlobId.of(BUCKET, sourceBlobName); ImmutableMap metadata = ImmutableMap.of("k", "v"); - Blob remoteBlob = storage.create(BlobInfo.builder(source).build(), BLOB_BYTE_CONTENT, + Blob remoteBlob = storage.create(BlobInfo.newBuilder(source).build(), BLOB_BYTE_CONTENT, Storage.BlobTargetOption.encryptionKey(KEY)); assertNotNull(remoteBlob); String targetBlobName = "test-copy-blob-encryption-key-target"; - BlobInfo target = BlobInfo.builder(BUCKET, targetBlobName) - .contentType(CONTENT_TYPE) - .metadata(metadata) + BlobInfo target = BlobInfo.newBuilder(BUCKET, targetBlobName) + .setContentType(CONTENT_TYPE) + .setMetadata(metadata) .build(); - Storage.CopyRequest req = Storage.CopyRequest.builder() - .source(source) - .target(target, Storage.BlobTargetOption.encryptionKey(OTHER_BASE64_KEY)) - .sourceOptions(Storage.BlobSourceOption.decryptionKey(BASE64_KEY)) + Storage.CopyRequest req = Storage.CopyRequest.newBuilder() + .setSource(source) + .setTarget(target, Storage.BlobTargetOption.encryptionKey(OTHER_BASE64_KEY)) + .setSourceOptions(Storage.BlobSourceOption.decryptionKey(BASE64_KEY)) .build(); CopyWriter copyWriter = storage.copy(req); - assertEquals(BUCKET, copyWriter.result().bucket()); - assertEquals(targetBlobName, copyWriter.result().name()); - assertEquals(CONTENT_TYPE, copyWriter.result().contentType()); + assertEquals(BUCKET, copyWriter.getResult().getBucket()); + assertEquals(targetBlobName, copyWriter.getResult().getName()); + assertEquals(CONTENT_TYPE, copyWriter.getResult().getContentType()); assertArrayEquals(BLOB_BYTE_CONTENT, - copyWriter.result().content(Blob.BlobSourceOption.decryptionKey(OTHER_BASE64_KEY))); - assertEquals(metadata, copyWriter.result().metadata()); + copyWriter.getResult().getContent(Blob.BlobSourceOption.decryptionKey(OTHER_BASE64_KEY))); + assertEquals(metadata, copyWriter.getResult().getMetadata()); assertTrue(copyWriter.isDone()); - req = Storage.CopyRequest.builder() - .source(source) - .target(target) - .sourceOptions(Storage.BlobSourceOption.decryptionKey(BASE64_KEY)) + req = Storage.CopyRequest.newBuilder() + .setSource(source) + .setTarget(target) + .setSourceOptions(Storage.BlobSourceOption.decryptionKey(BASE64_KEY)) .build(); copyWriter = storage.copy(req); - assertEquals(BUCKET, copyWriter.result().bucket()); - assertEquals(targetBlobName, copyWriter.result().name()); - assertEquals(CONTENT_TYPE, copyWriter.result().contentType()); - assertArrayEquals(BLOB_BYTE_CONTENT, copyWriter.result().content()); - assertEquals(metadata, copyWriter.result().metadata()); + assertEquals(BUCKET, copyWriter.getResult().getBucket()); + assertEquals(targetBlobName, copyWriter.getResult().getName()); + assertEquals(CONTENT_TYPE, copyWriter.getResult().getContentType()); + assertArrayEquals(BLOB_BYTE_CONTENT, copyWriter.getResult().getContent()); + assertEquals(metadata, copyWriter.getResult().getMetadata()); assertTrue(copyWriter.isDone()); assertTrue(remoteBlob.delete()); assertTrue(storage.delete(BUCKET, targetBlobName)); @@ -769,20 +770,20 @@ public void testCopyBlobWithEncryptionKeys() { public void testCopyBlobUpdateMetadata() { String sourceBlobName = "test-copy-blob-update-metadata-source"; BlobId source = BlobId.of(BUCKET, sourceBlobName); - Blob remoteSourceBlob = storage.create(BlobInfo.builder(source).build(), BLOB_BYTE_CONTENT); + Blob remoteSourceBlob = storage.create(BlobInfo.newBuilder(source).build(), BLOB_BYTE_CONTENT); assertNotNull(remoteSourceBlob); String targetBlobName = "test-copy-blob-update-metadata-target"; ImmutableMap metadata = ImmutableMap.of("k", "v"); - BlobInfo target = BlobInfo.builder(BUCKET, targetBlobName) - .contentType(CONTENT_TYPE) - .metadata(metadata) + BlobInfo target = BlobInfo.newBuilder(BUCKET, targetBlobName) + .setContentType(CONTENT_TYPE) + .setMetadata(metadata) .build(); Storage.CopyRequest req = Storage.CopyRequest.of(source, target); CopyWriter copyWriter = storage.copy(req); - assertEquals(BUCKET, copyWriter.result().bucket()); - assertEquals(targetBlobName, copyWriter.result().name()); - assertEquals(CONTENT_TYPE, copyWriter.result().contentType()); - assertEquals(metadata, copyWriter.result().metadata()); + assertEquals(BUCKET, copyWriter.getResult().getBucket()); + assertEquals(targetBlobName, copyWriter.getResult().getName()); + assertEquals(CONTENT_TYPE, copyWriter.getResult().getContentType()); + assertEquals(metadata, copyWriter.getResult().getMetadata()); assertTrue(copyWriter.isDone()); assertTrue(remoteSourceBlob.delete()); assertTrue(storage.delete(BUCKET, targetBlobName)); @@ -792,17 +793,17 @@ public void testCopyBlobUpdateMetadata() { public void testCopyBlobNoContentType() { String sourceBlobName = "test-copy-blob-no-content-type-source"; BlobId source = BlobId.of(BUCKET, sourceBlobName); - Blob remoteSourceBlob = storage.create(BlobInfo.builder(source).build(), BLOB_BYTE_CONTENT); + Blob remoteSourceBlob = storage.create(BlobInfo.newBuilder(source).build(), BLOB_BYTE_CONTENT); assertNotNull(remoteSourceBlob); String targetBlobName = "test-copy-blob-no-content-type-target"; ImmutableMap metadata = ImmutableMap.of("k", "v"); - BlobInfo target = BlobInfo.builder(BUCKET, targetBlobName).metadata(metadata).build(); + BlobInfo target = BlobInfo.newBuilder(BUCKET, targetBlobName).setMetadata(metadata).build(); Storage.CopyRequest req = Storage.CopyRequest.of(source, target); CopyWriter copyWriter = storage.copy(req); - assertEquals(BUCKET, copyWriter.result().bucket()); - assertEquals(targetBlobName, copyWriter.result().name()); - assertNull(copyWriter.result().contentType()); - assertEquals(metadata, copyWriter.result().metadata()); + assertEquals(BUCKET, copyWriter.getResult().getBucket()); + assertEquals(targetBlobName, copyWriter.getResult().getName()); + assertNull(copyWriter.getResult().getContentType()); + assertEquals(metadata, copyWriter.getResult().getMetadata()); assertTrue(copyWriter.isDone()); assertTrue(remoteSourceBlob.delete()); assertTrue(storage.delete(BUCKET, targetBlobName)); @@ -812,14 +813,14 @@ public void testCopyBlobNoContentType() { public void testCopyBlobFail() { String sourceBlobName = "test-copy-blob-source-fail"; BlobId source = BlobId.of(BUCKET, sourceBlobName, -1L); - Blob remoteSourceBlob = storage.create(BlobInfo.builder(source).build(), BLOB_BYTE_CONTENT); + Blob remoteSourceBlob = storage.create(BlobInfo.newBuilder(source).build(), BLOB_BYTE_CONTENT); assertNotNull(remoteSourceBlob); String targetBlobName = "test-copy-blob-target-fail"; - BlobInfo target = BlobInfo.builder(BUCKET, targetBlobName).contentType(CONTENT_TYPE).build(); - Storage.CopyRequest req = Storage.CopyRequest.builder() - .source(BUCKET, sourceBlobName) - .sourceOptions(Storage.BlobSourceOption.generationMatch(-1L)) - .target(target) + BlobInfo target = BlobInfo.newBuilder(BUCKET, targetBlobName).setContentType(CONTENT_TYPE).build(); + Storage.CopyRequest req = Storage.CopyRequest.newBuilder() + .setSource(BUCKET, sourceBlobName) + .setSourceOptions(Storage.BlobSourceOption.generationMatch(-1L)) + .setTarget(target) .build(); try { storage.copy(req); @@ -827,10 +828,10 @@ public void testCopyBlobFail() { } catch (StorageException ex) { // expected } - Storage.CopyRequest req2 = Storage.CopyRequest.builder() - .source(source) - .sourceOptions(Storage.BlobSourceOption.generationMatch()) - .target(target) + Storage.CopyRequest req2 = Storage.CopyRequest.newBuilder() + .setSource(source) + .setSourceOptions(Storage.BlobSourceOption.generationMatch()) + .setTarget(target) .build(); try { storage.copy(req2); @@ -845,26 +846,26 @@ public void testCopyBlobFail() { public void testBatchRequest() { String sourceBlobName1 = "test-batch-request-blob-1"; String sourceBlobName2 = "test-batch-request-blob-2"; - BlobInfo sourceBlob1 = BlobInfo.builder(BUCKET, sourceBlobName1).build(); - BlobInfo sourceBlob2 = BlobInfo.builder(BUCKET, sourceBlobName2).build(); + BlobInfo sourceBlob1 = BlobInfo.newBuilder(BUCKET, sourceBlobName1).build(); + BlobInfo sourceBlob2 = BlobInfo.newBuilder(BUCKET, sourceBlobName2).build(); assertNotNull(storage.create(sourceBlob1)); assertNotNull(storage.create(sourceBlob2)); // Batch update request - BlobInfo updatedBlob1 = sourceBlob1.toBuilder().contentType(CONTENT_TYPE).build(); - BlobInfo updatedBlob2 = sourceBlob2.toBuilder().contentType(CONTENT_TYPE).build(); + BlobInfo updatedBlob1 = sourceBlob1.toBuilder().setContentType(CONTENT_TYPE).build(); + BlobInfo updatedBlob2 = sourceBlob2.toBuilder().setContentType(CONTENT_TYPE).build(); StorageBatch updateBatch = storage.batch(); StorageBatchResult updateResult1 = updateBatch.update(updatedBlob1); StorageBatchResult updateResult2 = updateBatch.update(updatedBlob2); updateBatch.submit(); Blob remoteUpdatedBlob1 = updateResult1.get(); Blob remoteUpdatedBlob2 = updateResult2.get(); - assertEquals(sourceBlob1.bucket(), remoteUpdatedBlob1.bucket()); - assertEquals(sourceBlob1.name(), remoteUpdatedBlob1.name()); - assertEquals(sourceBlob2.bucket(), remoteUpdatedBlob2.bucket()); - assertEquals(sourceBlob2.name(), remoteUpdatedBlob2.name()); - assertEquals(updatedBlob1.contentType(), remoteUpdatedBlob1.contentType()); - assertEquals(updatedBlob2.contentType(), remoteUpdatedBlob2.contentType()); + assertEquals(sourceBlob1.getBucket(), remoteUpdatedBlob1.getBucket()); + assertEquals(sourceBlob1.getName(), remoteUpdatedBlob1.getName()); + assertEquals(sourceBlob2.getBucket(), remoteUpdatedBlob2.getBucket()); + assertEquals(sourceBlob2.getName(), remoteUpdatedBlob2.getName()); + assertEquals(updatedBlob1.getContentType(), remoteUpdatedBlob1.getContentType()); + assertEquals(updatedBlob2.getContentType(), remoteUpdatedBlob2.getContentType()); // Batch get request StorageBatch getBatch = storage.batch(); @@ -904,18 +905,18 @@ public void testBatchRequestManyOperations() { } for (int i = 0; i < MAX_BATCH_SIZE / 2; i++) { BlobInfo blob = - BlobInfo.builder(BlobId.of(BUCKET, "test-batch-request-many-operations-blob-" + i)) + BlobInfo.newBuilder(BlobId.of(BUCKET, "test-batch-request-many-operations-blob-" + i)) .build(); updateResults.add(batch.update(blob)); } String sourceBlobName1 = "test-batch-request-many-operations-source-blob-1"; String sourceBlobName2 = "test-batch-request-many-operations-source-blob-2"; - BlobInfo sourceBlob1 = BlobInfo.builder(BUCKET, sourceBlobName1).build(); - BlobInfo sourceBlob2 = BlobInfo.builder(BUCKET, sourceBlobName2).build(); + BlobInfo sourceBlob1 = BlobInfo.newBuilder(BUCKET, sourceBlobName1).build(); + BlobInfo sourceBlob2 = BlobInfo.newBuilder(BUCKET, sourceBlobName2).build(); assertNotNull(storage.create(sourceBlob1)); assertNotNull(storage.create(sourceBlob2)); - BlobInfo updatedBlob2 = sourceBlob2.toBuilder().contentType(CONTENT_TYPE).build(); + BlobInfo updatedBlob2 = sourceBlob2.toBuilder().setContentType(CONTENT_TYPE).build(); StorageBatchResult getResult = batch.get(BUCKET, sourceBlobName1); StorageBatchResult updateResult = batch.update(updatedBlob2); @@ -932,8 +933,8 @@ public void testBatchRequestManyOperations() { assertNull(failedGetResult.get()); } Blob remoteBlob1 = getResult.get(); - assertEquals(sourceBlob1.bucket(), remoteBlob1.bucket()); - assertEquals(sourceBlob1.name(), remoteBlob1.name()); + assertEquals(sourceBlob1.getBucket(), remoteBlob1.getBucket()); + assertEquals(sourceBlob1.getName(), remoteBlob1.getName()); // Check updates for (StorageBatchResult failedUpdateResult : updateResults) { @@ -945,9 +946,9 @@ public void testBatchRequestManyOperations() { } } Blob remoteUpdatedBlob2 = updateResult.get(); - assertEquals(sourceBlob2.bucket(), remoteUpdatedBlob2.bucket()); - assertEquals(sourceBlob2.name(), remoteUpdatedBlob2.name()); - assertEquals(updatedBlob2.contentType(), remoteUpdatedBlob2.contentType()); + assertEquals(sourceBlob2.getBucket(), remoteUpdatedBlob2.getBucket()); + assertEquals(sourceBlob2.getName(), remoteUpdatedBlob2.getName()); + assertEquals(updatedBlob2.getContentType(), remoteUpdatedBlob2.getContentType()); assertTrue(remoteBlob1.delete()); assertTrue(remoteUpdatedBlob2.delete()); @@ -956,10 +957,10 @@ public void testBatchRequestManyOperations() { @Test public void testBatchRequestFail() { String blobName = "test-batch-request-blob-fail"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob); assertNotNull(remoteBlob); - BlobInfo updatedBlob = BlobInfo.builder(BUCKET, blobName, -1L).build(); + BlobInfo updatedBlob = BlobInfo.newBuilder(BUCKET, blobName, -1L).build(); StorageBatch batch = storage.batch(); StorageBatchResult updateResult = batch.update(updatedBlob, Storage.BlobTargetOption.generationMatch()); @@ -995,7 +996,7 @@ public void testBatchRequestFail() { @Test public void testReadAndWriteChannels() throws IOException { String blobName = "test-read-and-write-channels-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); byte[] stringBytes; try (WriteChannel writer = storage.writer(blob)) { stringBytes = BLOB_STRING_CONTENT.getBytes(UTF_8); @@ -1004,7 +1005,7 @@ public void testReadAndWriteChannels() throws IOException { } ByteBuffer readBytes; ByteBuffer readStringBytes; - try (ReadChannel reader = storage.reader(blob.blobId())) { + try (ReadChannel reader = storage.reader(blob.getBlobId())) { readBytes = ByteBuffer.allocate(BLOB_BYTE_CONTENT.length); readStringBytes = ByteBuffer.allocate(stringBytes.length); reader.read(readBytes); @@ -1018,7 +1019,7 @@ public void testReadAndWriteChannels() throws IOException { @Test public void testReadAndWriteChannelWithEncryptionKey() throws IOException { String blobName = "test-read-write-channel-with-customer-key-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); byte[] stringBytes; try (WriteChannel writer = storage.writer(blob, Storage.BlobWriteOption.encryptionKey(BASE64_KEY))) { @@ -1029,7 +1030,7 @@ public void testReadAndWriteChannelWithEncryptionKey() throws IOException { ByteBuffer readBytes; ByteBuffer readStringBytes; try (ReadChannel reader = - storage.reader(blob.blobId(), Storage.BlobSourceOption.decryptionKey(KEY))) { + storage.reader(blob.getBlobId(), Storage.BlobSourceOption.decryptionKey(KEY))) { readBytes = ByteBuffer.allocate(BLOB_BYTE_CONTENT.length); readStringBytes = ByteBuffer.allocate(stringBytes.length); reader.read(readBytes); @@ -1047,14 +1048,14 @@ public void testReadAndWriteChannelsWithDifferentFileSize() throws IOException { Random rnd = new Random(); for (int blobSize : blobSizes) { String blobName = blobNamePrefix + blobSize; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); byte[] bytes = new byte[blobSize]; rnd.nextBytes(bytes); try (WriteChannel writer = storage.writer(blob)) { writer.write(ByteBuffer.wrap(bytes)); } ByteArrayOutputStream output = new ByteArrayOutputStream(); - try (ReadChannel reader = storage.reader(blob.blobId())) { + try (ReadChannel reader = storage.reader(blob.getBlobId())) { ByteBuffer buffer = ByteBuffer.allocate(64 * 1024); while (reader.read(buffer) > 0) { buffer.flip(); @@ -1070,7 +1071,7 @@ public void testReadAndWriteChannelsWithDifferentFileSize() throws IOException { @Test public void testReadAndWriteCaptureChannels() throws IOException { String blobName = "test-read-and-write-capture-channels-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); byte[] stringBytes; WriteChannel writer = storage.writer(blob); stringBytes = BLOB_STRING_CONTENT.getBytes(UTF_8); @@ -1081,7 +1082,7 @@ public void testReadAndWriteCaptureChannels() throws IOException { secondWriter.close(); ByteBuffer readBytes; ByteBuffer readStringBytes; - ReadChannel reader = storage.reader(blob.blobId()); + ReadChannel reader = storage.reader(blob.getBlobId()); reader.chunkSize(BLOB_BYTE_CONTENT.length); readBytes = ByteBuffer.allocate(BLOB_BYTE_CONTENT.length); reader.read(readBytes); @@ -1099,18 +1100,18 @@ public void testReadAndWriteCaptureChannels() throws IOException { @Test public void testReadChannelFail() throws IOException { String blobName = "test-read-channel-blob-fail"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob); assertNotNull(remoteBlob); try (ReadChannel reader = - storage.reader(blob.blobId(), Storage.BlobSourceOption.metagenerationMatch(-1L))) { + storage.reader(blob.getBlobId(), Storage.BlobSourceOption.metagenerationMatch(-1L))) { reader.read(ByteBuffer.allocate(42)); fail("StorageException was expected"); } catch (StorageException ex) { // expected } try (ReadChannel reader = - storage.reader(blob.blobId(), Storage.BlobSourceOption.generationMatch(-1L))) { + storage.reader(blob.getBlobId(), Storage.BlobSourceOption.generationMatch(-1L))) { reader.read(ByteBuffer.allocate(42)); fail("StorageException was expected"); } catch (StorageException ex) { @@ -1130,7 +1131,7 @@ public void testReadChannelFail() throws IOException { @Test public void testReadChannelFailUpdatedGeneration() throws IOException { String blobName = "test-read-blob-fail-updated-generation"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Random random = new Random(); int chunkSize = 1024; int blobSize = 2 * chunkSize; @@ -1138,8 +1139,8 @@ public void testReadChannelFailUpdatedGeneration() throws IOException { random.nextBytes(content); Blob remoteBlob = storage.create(blob, content); assertNotNull(remoteBlob); - assertEquals(blobSize, (long) remoteBlob.size()); - try (ReadChannel reader = storage.reader(blob.blobId())) { + assertEquals(blobSize, (long) remoteBlob.getSize()); + try (ReadChannel reader = storage.reader(blob.getBlobId())) { reader.chunkSize(chunkSize); ByteBuffer readBytes = ByteBuffer.allocate(chunkSize); int numReadBytes = reader.read(readBytes); @@ -1156,7 +1157,7 @@ public void testReadChannelFailUpdatedGeneration() throws IOException { fail("StorageException was expected"); } catch (StorageException ex) { StringBuilder messageBuilder = new StringBuilder(); - messageBuilder.append("Blob ").append(blob.blobId()).append(" was updated while reading"); + messageBuilder.append("Blob ").append(blob.getBlobId()).append(" was updated while reading"); assertEquals(messageBuilder.toString(), ex.getMessage()); } assertTrue(storage.delete(BUCKET, blobName)); @@ -1165,7 +1166,7 @@ public void testReadChannelFailUpdatedGeneration() throws IOException { @Test public void testWriteChannelFail() throws IOException { String blobName = "test-write-channel-blob-fail"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName, -1L).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName, -1L).build(); try { try (WriteChannel writer = storage.writer(blob, Storage.BlobWriteOption.generationMatch())) { writer.write(ByteBuffer.allocate(42)); @@ -1179,21 +1180,21 @@ public void testWriteChannelFail() throws IOException { @Test public void testWriteChannelExistingBlob() throws IOException { String blobName = "test-write-channel-existing-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); storage.create(blob); byte[] stringBytes; try (WriteChannel writer = storage.writer(blob)) { stringBytes = BLOB_STRING_CONTENT.getBytes(UTF_8); writer.write(ByteBuffer.wrap(stringBytes)); } - assertArrayEquals(stringBytes, storage.readAllBytes(blob.blobId())); + assertArrayEquals(stringBytes, storage.readAllBytes(blob.getBlobId())); assertTrue(storage.delete(BUCKET, blobName)); } @Test public void testGetSignedUrl() throws IOException { String blobName = "test-get-signed-url-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob, BLOB_BYTE_CONTENT); assertNotNull(remoteBlob); URL url = storage.signUrl(blob, 1, TimeUnit.HOURS); @@ -1209,7 +1210,7 @@ public void testGetSignedUrl() throws IOException { @Test public void testPostSignedUrl() throws IOException { String blobName = "test-post-signed-url-blob"; - BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build(); + BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); assertNotNull(storage.create(blob)); URL url = storage.signUrl(blob, 1, TimeUnit.HOURS, Storage.SignUrlOption.httpMethod(HttpMethod.POST)); @@ -1218,8 +1219,8 @@ public void testPostSignedUrl() throws IOException { connection.connect(); Blob remoteBlob = storage.get(BUCKET, blobName); assertNotNull(remoteBlob); - assertEquals(blob.bucket(), remoteBlob.bucket()); - assertEquals(blob.name(), remoteBlob.name()); + assertEquals(blob.getBucket(), remoteBlob.getBucket()); + assertEquals(blob.getName(), remoteBlob.getName()); assertTrue(remoteBlob.delete()); } @@ -1227,15 +1228,15 @@ public void testPostSignedUrl() throws IOException { public void testGetBlobs() { String sourceBlobName1 = "test-get-blobs-1"; String sourceBlobName2 = "test-get-blobs-2"; - BlobInfo sourceBlob1 = BlobInfo.builder(BUCKET, sourceBlobName1).build(); - BlobInfo sourceBlob2 = BlobInfo.builder(BUCKET, sourceBlobName2).build(); + BlobInfo sourceBlob1 = BlobInfo.newBuilder(BUCKET, sourceBlobName1).build(); + BlobInfo sourceBlob2 = BlobInfo.newBuilder(BUCKET, sourceBlobName2).build(); assertNotNull(storage.create(sourceBlob1)); assertNotNull(storage.create(sourceBlob2)); - List remoteBlobs = storage.get(sourceBlob1.blobId(), sourceBlob2.blobId()); - assertEquals(sourceBlob1.bucket(), remoteBlobs.get(0).bucket()); - assertEquals(sourceBlob1.name(), remoteBlobs.get(0).name()); - assertEquals(sourceBlob2.bucket(), remoteBlobs.get(1).bucket()); - assertEquals(sourceBlob2.name(), remoteBlobs.get(1).name()); + List remoteBlobs = storage.get(sourceBlob1.getBlobId(), sourceBlob2.getBlobId()); + assertEquals(sourceBlob1.getBucket(), remoteBlobs.get(0).getBucket()); + assertEquals(sourceBlob1.getName(), remoteBlobs.get(0).getName()); + assertEquals(sourceBlob2.getBucket(), remoteBlobs.get(1).getBucket()); + assertEquals(sourceBlob2.getName(), remoteBlobs.get(1).getName()); assertTrue(remoteBlobs.get(0).delete()); assertTrue(remoteBlobs.get(1).delete()); } @@ -1244,12 +1245,12 @@ public void testGetBlobs() { public void testGetBlobsFail() { String sourceBlobName1 = "test-get-blobs-fail-1"; String sourceBlobName2 = "test-get-blobs-fail-2"; - BlobInfo sourceBlob1 = BlobInfo.builder(BUCKET, sourceBlobName1).build(); - BlobInfo sourceBlob2 = BlobInfo.builder(BUCKET, sourceBlobName2).build(); + BlobInfo sourceBlob1 = BlobInfo.newBuilder(BUCKET, sourceBlobName1).build(); + BlobInfo sourceBlob2 = BlobInfo.newBuilder(BUCKET, sourceBlobName2).build(); assertNotNull(storage.create(sourceBlob1)); - List remoteBlobs = storage.get(sourceBlob1.blobId(), sourceBlob2.blobId()); - assertEquals(sourceBlob1.bucket(), remoteBlobs.get(0).bucket()); - assertEquals(sourceBlob1.name(), remoteBlobs.get(0).name()); + List remoteBlobs = storage.get(sourceBlob1.getBlobId(), sourceBlob2.getBlobId()); + assertEquals(sourceBlob1.getBucket(), remoteBlobs.get(0).getBucket()); + assertEquals(sourceBlob1.getName(), remoteBlobs.get(0).getName()); assertNull(remoteBlobs.get(1)); assertTrue(remoteBlobs.get(0).delete()); } @@ -1258,11 +1259,11 @@ public void testGetBlobsFail() { public void testDeleteBlobs() { String sourceBlobName1 = "test-delete-blobs-1"; String sourceBlobName2 = "test-delete-blobs-2"; - BlobInfo sourceBlob1 = BlobInfo.builder(BUCKET, sourceBlobName1).build(); - BlobInfo sourceBlob2 = BlobInfo.builder(BUCKET, sourceBlobName2).build(); + BlobInfo sourceBlob1 = BlobInfo.newBuilder(BUCKET, sourceBlobName1).build(); + BlobInfo sourceBlob2 = BlobInfo.newBuilder(BUCKET, sourceBlobName2).build(); assertNotNull(storage.create(sourceBlob1)); assertNotNull(storage.create(sourceBlob2)); - List deleteStatus = storage.delete(sourceBlob1.blobId(), sourceBlob2.blobId()); + List deleteStatus = storage.delete(sourceBlob1.getBlobId(), sourceBlob2.getBlobId()); assertTrue(deleteStatus.get(0)); assertTrue(deleteStatus.get(1)); } @@ -1271,10 +1272,10 @@ public void testDeleteBlobs() { public void testDeleteBlobsFail() { String sourceBlobName1 = "test-delete-blobs-fail-1"; String sourceBlobName2 = "test-delete-blobs-fail-2"; - BlobInfo sourceBlob1 = BlobInfo.builder(BUCKET, sourceBlobName1).build(); - BlobInfo sourceBlob2 = BlobInfo.builder(BUCKET, sourceBlobName2).build(); + BlobInfo sourceBlob1 = BlobInfo.newBuilder(BUCKET, sourceBlobName1).build(); + BlobInfo sourceBlob2 = BlobInfo.newBuilder(BUCKET, sourceBlobName2).build(); assertNotNull(storage.create(sourceBlob1)); - List deleteStatus = storage.delete(sourceBlob1.blobId(), sourceBlob2.blobId()); + List deleteStatus = storage.delete(sourceBlob1.getBlobId(), sourceBlob2.getBlobId()); assertTrue(deleteStatus.get(0)); assertFalse(deleteStatus.get(1)); } @@ -1283,21 +1284,21 @@ public void testDeleteBlobsFail() { public void testUpdateBlobs() { String sourceBlobName1 = "test-update-blobs-1"; String sourceBlobName2 = "test-update-blobs-2"; - BlobInfo sourceBlob1 = BlobInfo.builder(BUCKET, sourceBlobName1).build(); - BlobInfo sourceBlob2 = BlobInfo.builder(BUCKET, sourceBlobName2).build(); + BlobInfo sourceBlob1 = BlobInfo.newBuilder(BUCKET, sourceBlobName1).build(); + BlobInfo sourceBlob2 = BlobInfo.newBuilder(BUCKET, sourceBlobName2).build(); Blob remoteBlob1 = storage.create(sourceBlob1); Blob remoteBlob2 = storage.create(sourceBlob2); assertNotNull(remoteBlob1); assertNotNull(remoteBlob2); List updatedBlobs = storage.update( - remoteBlob1.toBuilder().contentType(CONTENT_TYPE).build(), - remoteBlob2.toBuilder().contentType(CONTENT_TYPE).build()); - assertEquals(sourceBlob1.bucket(), updatedBlobs.get(0).bucket()); - assertEquals(sourceBlob1.name(), updatedBlobs.get(0).name()); - assertEquals(CONTENT_TYPE, updatedBlobs.get(0).contentType()); - assertEquals(sourceBlob2.bucket(), updatedBlobs.get(1).bucket()); - assertEquals(sourceBlob2.name(), updatedBlobs.get(1).name()); - assertEquals(CONTENT_TYPE, updatedBlobs.get(1).contentType()); + remoteBlob1.toBuilder().setContentType(CONTENT_TYPE).build(), + remoteBlob2.toBuilder().setContentType(CONTENT_TYPE).build()); + assertEquals(sourceBlob1.getBucket(), updatedBlobs.get(0).getBucket()); + assertEquals(sourceBlob1.getName(), updatedBlobs.get(0).getName()); + assertEquals(CONTENT_TYPE, updatedBlobs.get(0).getContentType()); + assertEquals(sourceBlob2.getBucket(), updatedBlobs.get(1).getBucket()); + assertEquals(sourceBlob2.getName(), updatedBlobs.get(1).getName()); + assertEquals(CONTENT_TYPE, updatedBlobs.get(1).getContentType()); assertTrue(updatedBlobs.get(0).delete()); assertTrue(updatedBlobs.get(1).delete()); } @@ -1306,16 +1307,16 @@ public void testUpdateBlobs() { public void testUpdateBlobsFail() { String sourceBlobName1 = "test-update-blobs-fail-1"; String sourceBlobName2 = "test-update-blobs-fail-2"; - BlobInfo sourceBlob1 = BlobInfo.builder(BUCKET, sourceBlobName1).build(); - BlobInfo sourceBlob2 = BlobInfo.builder(BUCKET, sourceBlobName2).build(); + BlobInfo sourceBlob1 = BlobInfo.newBuilder(BUCKET, sourceBlobName1).build(); + BlobInfo sourceBlob2 = BlobInfo.newBuilder(BUCKET, sourceBlobName2).build(); BlobInfo remoteBlob1 = storage.create(sourceBlob1); assertNotNull(remoteBlob1); List updatedBlobs = storage.update( - remoteBlob1.toBuilder().contentType(CONTENT_TYPE).build(), - sourceBlob2.toBuilder().contentType(CONTENT_TYPE).build()); - assertEquals(sourceBlob1.bucket(), updatedBlobs.get(0).bucket()); - assertEquals(sourceBlob1.name(), updatedBlobs.get(0).name()); - assertEquals(CONTENT_TYPE, updatedBlobs.get(0).contentType()); + remoteBlob1.toBuilder().setContentType(CONTENT_TYPE).build(), + sourceBlob2.toBuilder().setContentType(CONTENT_TYPE).build()); + assertEquals(sourceBlob1.getBucket(), updatedBlobs.get(0).getBucket()); + assertEquals(sourceBlob1.getName(), updatedBlobs.get(0).getName()); + assertEquals(CONTENT_TYPE, updatedBlobs.get(0).getContentType()); assertNull(updatedBlobs.get(1)); assertTrue(updatedBlobs.get(0).delete()); } @@ -1326,8 +1327,8 @@ public void testBucketAcl() { assertFalse(storage.deleteAcl(BUCKET, User.ofAllAuthenticatedUsers())); Acl acl = Acl.of(User.ofAllAuthenticatedUsers(), Role.READER); assertNotNull(storage.createAcl(BUCKET, acl)); - Acl updatedAcl = storage.updateAcl(BUCKET, acl.toBuilder().role(Role.WRITER).build()); - assertEquals(Role.WRITER, updatedAcl.role()); + Acl updatedAcl = storage.updateAcl(BUCKET, acl.toBuilder().setRole(Role.WRITER).build()); + assertEquals(Role.WRITER, updatedAcl.getRole()); Set acls = Sets.newHashSet(storage.listAcls(BUCKET)); assertTrue(acls.contains(updatedAcl)); assertTrue(storage.deleteAcl(BUCKET, User.ofAllAuthenticatedUsers())); @@ -1340,8 +1341,8 @@ public void testBucketDefaultAcl() { assertFalse(storage.deleteDefaultAcl(BUCKET, User.ofAllAuthenticatedUsers())); Acl acl = Acl.of(User.ofAllAuthenticatedUsers(), Role.READER); assertNotNull(storage.createDefaultAcl(BUCKET, acl)); - Acl updatedAcl = storage.updateDefaultAcl(BUCKET, acl.toBuilder().role(Role.OWNER).build()); - assertEquals(Role.OWNER, updatedAcl.role()); + Acl updatedAcl = storage.updateDefaultAcl(BUCKET, acl.toBuilder().setRole(Role.OWNER).build()); + assertEquals(Role.OWNER, updatedAcl.getRole()); Set acls = Sets.newHashSet(storage.listDefaultAcls(BUCKET)); assertTrue(acls.contains(updatedAcl)); assertTrue(storage.deleteDefaultAcl(BUCKET, User.ofAllAuthenticatedUsers())); @@ -1351,13 +1352,13 @@ public void testBucketDefaultAcl() { @Test public void testBlobAcl() { BlobId blobId = BlobId.of(BUCKET, "test-blob-acl"); - BlobInfo blob = BlobInfo.builder(blobId).build(); + BlobInfo blob = BlobInfo.newBuilder(blobId).build(); storage.create(blob); assertNull(storage.getAcl(blobId, User.ofAllAuthenticatedUsers())); Acl acl = Acl.of(User.ofAllAuthenticatedUsers(), Role.READER); assertNotNull(storage.createAcl(blobId, acl)); - Acl updatedAcl = storage.updateAcl(blobId, acl.toBuilder().role(Role.OWNER).build()); - assertEquals(Role.OWNER, updatedAcl.role()); + Acl updatedAcl = storage.updateAcl(blobId, acl.toBuilder().setRole(Role.OWNER).build()); + assertEquals(Role.OWNER, updatedAcl.getRole()); Set acls = Sets.newHashSet(storage.listAcls(blobId)); assertTrue(acls.contains(updatedAcl)); assertTrue(storage.deleteAcl(blobId, User.ofAllAuthenticatedUsers())); diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/testing/RemoteStorageHelperTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/testing/RemoteStorageHelperTest.java index 3c29ca223c23..158cbcac9988 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/testing/RemoteStorageHelperTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/testing/RemoteStorageHelperTest.java @@ -117,9 +117,9 @@ public Iterator iterateAll() { @Test public void testForceDelete() throws InterruptedException, ExecutionException { Storage storageMock = EasyMock.createMock(Storage.class); - EasyMock.expect(blob1.blobId()).andReturn(BLOB_ID1); + EasyMock.expect(blob1.getBlobId()).andReturn(BLOB_ID1); EasyMock.expect(storageMock.delete(BLOB_ID1)).andReturn(true); - EasyMock.expect(blob2.blobId()).andReturn(BLOB_ID2); + EasyMock.expect(blob2.getBlobId()).andReturn(BLOB_ID2); EasyMock.expect(storageMock.delete(BLOB_ID2)).andReturn(true); EasyMock.expect(storageMock.list(BUCKET_NAME, BlobListOption.versions(true))) .andReturn(blobPage); @@ -132,9 +132,9 @@ public void testForceDelete() throws InterruptedException, ExecutionException { @Test public void testForceDeleteTimeout() throws InterruptedException, ExecutionException { Storage storageMock = EasyMock.createMock(Storage.class); - EasyMock.expect(blob1.blobId()).andReturn(BLOB_ID1).anyTimes(); + EasyMock.expect(blob1.getBlobId()).andReturn(BLOB_ID1).anyTimes(); EasyMock.expect(storageMock.delete(BLOB_ID1)).andReturn(true).anyTimes(); - EasyMock.expect(blob2.blobId()).andReturn(BLOB_ID2).anyTimes(); + EasyMock.expect(blob2.getBlobId()).andReturn(BLOB_ID2).anyTimes(); EasyMock.expect(storageMock.delete(BLOB_ID2)).andReturn(true).anyTimes(); EasyMock.expect(storageMock.list(BUCKET_NAME, BlobListOption.versions(true))) .andReturn(blobPage).anyTimes(); @@ -148,9 +148,9 @@ public void testForceDeleteTimeout() throws InterruptedException, ExecutionExcep @Test public void testForceDeleteFail() throws InterruptedException, ExecutionException { Storage storageMock = EasyMock.createMock(Storage.class); - EasyMock.expect(blob1.blobId()).andReturn(BLOB_ID1); + EasyMock.expect(blob1.getBlobId()).andReturn(BLOB_ID1); EasyMock.expect(storageMock.delete(BLOB_ID1)).andReturn(true); - EasyMock.expect(blob2.blobId()).andReturn(BLOB_ID2); + EasyMock.expect(blob2.getBlobId()).andReturn(BLOB_ID2); EasyMock.expect(storageMock.delete(BLOB_ID2)).andReturn(true); EasyMock.expect(storageMock.list(BUCKET_NAME, BlobListOption.versions(true))) .andReturn(blobPage); @@ -167,9 +167,9 @@ public void testForceDeleteFail() throws InterruptedException, ExecutionExceptio @Test public void testForceDeleteNoTimeout() { Storage storageMock = EasyMock.createMock(Storage.class); - EasyMock.expect(blob1.blobId()).andReturn(BLOB_ID1); + EasyMock.expect(blob1.getBlobId()).andReturn(BLOB_ID1); EasyMock.expect(storageMock.delete(BLOB_ID1)).andReturn(true); - EasyMock.expect(blob2.blobId()).andReturn(BLOB_ID2); + EasyMock.expect(blob2.getBlobId()).andReturn(BLOB_ID2); EasyMock.expect(storageMock.delete(BLOB_ID2)).andReturn(true); EasyMock.expect(storageMock.list(BUCKET_NAME, BlobListOption.versions(true))) .andReturn(blobPage); @@ -182,9 +182,9 @@ public void testForceDeleteNoTimeout() { @Test public void testForceDeleteNoTimeoutFail() { Storage storageMock = EasyMock.createMock(Storage.class); - EasyMock.expect(blob1.blobId()).andReturn(BLOB_ID1); + EasyMock.expect(blob1.getBlobId()).andReturn(BLOB_ID1); EasyMock.expect(storageMock.delete(BLOB_ID1)).andReturn(true); - EasyMock.expect(blob2.blobId()).andReturn(BLOB_ID2); + EasyMock.expect(blob2.getBlobId()).andReturn(BLOB_ID2); EasyMock.expect(storageMock.delete(BLOB_ID2)).andReturn(true); EasyMock.expect(storageMock.list(BUCKET_NAME, BlobListOption.versions(true))) .andReturn(blobPage); @@ -201,7 +201,8 @@ public void testForceDeleteNoTimeoutFail() { @Test public void testCreateFromStream() { RemoteStorageHelper helper = RemoteStorageHelper.create(PROJECT_ID, JSON_KEY_STREAM); - StorageOptions options = helper.options(); + StorageOptions options = helper.getOptions(); + assertEquals(options, helper.options()); assertEquals(PROJECT_ID, options.projectId()); assertEquals(60000, options.connectTimeout()); assertEquals(60000, options.readTimeout()); From 82b5032e95a38e4f67f710c2e4e4c25516e63594 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Fri, 21 Oct 2016 11:18:38 +0200 Subject: [PATCH 14/32] Rename setters/getters/builders for PubSub classes to meet proto conventions (#1312) * Rename setters/getters/builders for PubSub classes to meet proto conventions * Update PubSub examples, snippets and READMEs to use renamed getters/setters/builders * Make deprecated methods call renamed ones --- README.md | 2 +- TESTING.md | 2 +- .../cloud/examples/pubsub/PubSubExample.java | 6 +- .../CreateSubscriptionAndPullMessages.java | 2 +- google-cloud-pubsub/README.md | 2 +- .../java/com/google/cloud/pubsub/Message.java | 129 ++++++++++-- .../java/com/google/cloud/pubsub/Option.java | 4 +- .../google/cloud/pubsub/PubSubFactory.java | 3 +- .../com/google/cloud/pubsub/PubSubImpl.java | 2 +- .../com/google/cloud/pubsub/PushConfig.java | 107 +++++++++- .../google/cloud/pubsub/ReceivedMessage.java | 57 +++++- .../com/google/cloud/pubsub/Subscription.java | 86 ++++++-- .../google/cloud/pubsub/SubscriptionId.java | 16 ++ .../google/cloud/pubsub/SubscriptionInfo.java | 190 +++++++++++++++++- .../java/com/google/cloud/pubsub/Topic.java | 52 +++-- .../java/com/google/cloud/pubsub/TopicId.java | 17 ++ .../com/google/cloud/pubsub/TopicInfo.java | 44 +++- .../pubsub/testing/LocalPubsubHelper.java | 9 + .../cloud/pubsub/testing/package-info.java | 2 +- .../google/cloud/pubsub/BaseSystemTest.java | 141 ++++++------- .../google/cloud/pubsub/LocalSystemTest.java | 2 +- .../com/google/cloud/pubsub/MessageTest.java | 115 +++++++---- .../com/google/cloud/pubsub/OptionTest.java | 8 +- .../google/cloud/pubsub/PubSubImplTest.java | 19 +- .../com/google/cloud/pubsub/PubSubTest.java | 16 +- .../google/cloud/pubsub/PushConfigTest.java | 46 +++-- .../cloud/pubsub/ReceivedMessageTest.java | 66 ++++-- .../cloud/pubsub/SubscriptionIdTest.java | 14 +- .../cloud/pubsub/SubscriptionInfoTest.java | 103 ++++++---- .../google/cloud/pubsub/SubscriptionTest.java | 43 +++- .../com/google/cloud/pubsub/TopicIdTest.java | 19 +- .../google/cloud/pubsub/TopicInfoTest.java | 20 +- .../com/google/cloud/pubsub/TopicTest.java | 17 +- 33 files changed, 1050 insertions(+), 311 deletions(-) diff --git a/README.md b/README.md index fe73f9e44561..d85c8ab3bcf4 100644 --- a/README.md +++ b/README.md @@ -477,7 +477,7 @@ try (PubSub pubsub = PubSubOptions.defaultInstance().service()) { MessageProcessor callback = new MessageProcessor() { @Override public void process(Message message) throws Exception { - System.out.printf("Received message \"%s\"%n", message.payloadAsString()); + System.out.printf("Received message \"%s\"%n", message.getPayloadAsString()); } }; // Create a message consumer and pull messages (for 60 seconds) diff --git a/TESTING.md b/TESTING.md index 7d37f1c7d466..606caddda375 100644 --- a/TESTING.md +++ b/TESTING.md @@ -190,7 +190,7 @@ and `start` methods. This will bind a port for communication with the local Pub/ 2. Create and use a `PubSub` object with the options given by the `LocalPubSubHelper` instance. For example: ```java - PubSub localPubsub = helper.options().service(); + PubSub localPubsub = helper.getOptions().service(); ``` 3. Run your tests. diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/PubSubExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/PubSubExample.java index 7396de7d1df5..b1d448adaf9d 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/PubSubExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/PubSubExample.java @@ -360,7 +360,7 @@ private static class CreateSubscriptionAction extends PubSubAction attributes); + /** + * Sets the message attributes to the provided map. Message attributes are key-value pairs that + * a publisher can define for a message. For example, a key {@code iana.org/language_tag} and + * value {@code en} could be added to messages to mark them as readable by an English-speaking + * subscriber. + */ + public abstract Builder setAttributes(Map attributes); + /** * Adds a new attribute to the message attributes. If an attribute with name {@code name} was * already set, its value is updated. @@ -121,7 +142,7 @@ public abstract static class Builder { */ public abstract Builder clearAttributes(); - abstract Builder publishTime(long publishTime); + abstract Builder setPublishTime(long publishTime); /** * Creates a message object. @@ -146,18 +167,30 @@ private BuilderImpl() {} } @Override - BuilderImpl id(String id) { + BuilderImpl setId(String id) { this.id = checkNotNull(id); return this; } @Override + @Deprecated public Builder payload(String payload) { - return payload(ByteArray.copyFrom(payload)); + return setPayload(payload); + } + + @Override + public Builder setPayload(String payload) { + return setPayload(ByteArray.copyFrom(payload)); } @Override + @Deprecated public Builder payload(ByteArray payload) { + return setPayload(payload); + } + + @Override + public Builder setPayload(ByteArray payload) { this.payload = payload; return this; } @@ -169,7 +202,13 @@ public Builder addAttribute(String name, String value) { } @Override + @Deprecated public Builder attributes(Map attributes) { + return setAttributes(attributes); + } + + @Override + public Builder setAttributes(Map attributes) { this.attributes = new HashMap<>(attributes); return this; } @@ -187,7 +226,7 @@ public Builder clearAttributes() { } @Override - Builder publishTime(long publishTime) { + Builder setPublishTime(long publishTime) { this.publishTime = publishTime; return this; } @@ -209,7 +248,16 @@ public Message build() { * Returns the time in milliseconds at which the message was published. This value is set by the * server when it receives the publish call. If not set, this method returns {@code null}. */ + @Deprecated public Long publishTime() { + return getPublishTime(); + } + + /** + * Returns the time in milliseconds at which the message was published. This value is set by the + * server when it receives the publish call. If not set, this method returns {@code null}. + */ + public Long getPublishTime() { return publishTime; } @@ -218,7 +266,17 @@ public Long publishTime() { * define for a message. For example, a key {@code iana.org/language_tag} and value {@code en} * could be added to messages to mark them as readable by an English-speaking subscriber. */ + @Deprecated public Map attributes() { + return getAttributes(); + } + + /** + * Returns the message attributes. Message attributes are key-value pairs that a publisher can + * define for a message. For example, a key {@code iana.org/language_tag} and value {@code en} + * could be added to messages to mark them as readable by an English-speaking subscriber. + */ + public Map getAttributes() { return attributes; } @@ -228,21 +286,48 @@ public Map attributes() { * a Pub/Sub message via a pull call or a push delivery. If not set, this method returns * {@code null}. */ + @Deprecated public String id() { + return getId(); + } + + /** + * Returns the id of this message, set by the server when the message is published. The id is + * guaranteed to be unique within the topic. This value may be read by a subscriber that receives + * a Pub/Sub message via a pull call or a push delivery. If not set, this method returns + * {@code null}. + */ + public String getId() { return id; } /** * Returns the message payload as a string, decoded using {@code UTF-8}. */ + @Deprecated public String payloadAsString() { + return getPayloadAsString(); + } + + /** + * Returns the message payload as a string, decoded using {@code UTF-8}. + */ + public String getPayloadAsString() { return payload.toStringUtf8(); } /** * Returns the message payload. */ + @Deprecated public ByteArray payload() { + return getPayload(); + } + + /** + * Returns the message payload. + */ + public ByteArray getPayload() { return payload; } @@ -293,18 +378,18 @@ PubsubMessage toPb() { } static Message fromPb(PubsubMessage messagePb) { - Builder builder = builder(new InternalByteArray(messagePb.getData())); + Builder builder = newBuilder(new InternalByteArray(messagePb.getData())); if (messagePb.hasPublishTime()) { Timestamp ts = messagePb.getPublishTime(); Long millis = ts.getSeconds() * MILLIS_PER_SECOND + ts.getNanos() / NANOS_PER_MILLISECOND; if (millis != 0) { - builder.publishTime(millis); + builder.setPublishTime(millis); } } if (!Objects.equals(messagePb.getMessageId(), "")) { - builder.id(messagePb.getMessageId()); + builder.setId(messagePb.getMessageId()); } - for (Map.Entry entry : messagePb.getAttributes().entrySet()) { + for (Map.Entry entry : messagePb.getAttributesMap().entrySet()) { builder.addAttribute(entry.getKey(), entry.getValue()); } return builder.build(); @@ -322,7 +407,7 @@ public Builder toBuilder() { * {@code UTF-8}. */ public static Message of(String payload) { - return builder(payload).build(); + return newBuilder(payload).build(); } /** @@ -330,22 +415,40 @@ public static Message of(String payload) { * message must have a non-empty payload. */ public static Message of(ByteArray payload) { - return builder(payload).build(); + return newBuilder(payload).build(); } /** * Creates a builder for {@code Message} objects given the payload as a string. The string is * enconded using {@code UTF-8}. To be published a message must have a non-empty payload. */ + @Deprecated public static Builder builder(String payload) { - return new BuilderImpl().payload(payload); + return newBuilder(payload); + } + + /** + * Creates a builder for {@code Message} objects given the payload as a string. The string is + * enconded using {@code UTF-8}. To be published a message must have a non-empty payload. + */ + public static Builder newBuilder(String payload) { + return new BuilderImpl().setPayload(payload); } /** * Creates a builder for {@code Message} objects given the payload as a {@link ByteArray}. To be * published a message must have a non-empty payload, or at least one attribute. */ + @Deprecated public static Builder builder(ByteArray payload) { - return new BuilderImpl().payload(payload); + return newBuilder(payload); + } + + /** + * Creates a builder for {@code Message} objects given the payload as a {@link ByteArray}. To be + * published a message must have a non-empty payload, or at least one attribute. + */ + public static Builder newBuilder(ByteArray payload) { + return new BuilderImpl().setPayload(payload); } } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Option.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Option.java index 5359d1797f55..b64dc80733d4 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Option.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Option.java @@ -44,11 +44,11 @@ interface OptionType { } @SuppressWarnings("unchecked") - T optionType() { + T getOptionType() { return (T) optionType; } - Object value() { + Object getValue() { return value; } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubFactory.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubFactory.java index 8aa073f3a10a..38f922dbce3b 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubFactory.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubFactory.java @@ -21,5 +21,4 @@ /** * An interface for Pub/Sub factories. */ -public interface PubSubFactory - extends ServiceFactory {} +public interface PubSubFactory extends ServiceFactory {} diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubImpl.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubImpl.java index d830290eb732..f9ed0a1178b1 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubImpl.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubImpl.java @@ -714,7 +714,7 @@ public List apply(TestIamPermissionsResponse response) { static Map optionMap(Option... options) { Map optionMap = Maps.newHashMap(); for (Option option : options) { - Object prev = optionMap.put(option.optionType(), option.value()); + Object prev = optionMap.put(option.getOptionType(), option.getValue()); checkArgument(prev == null, "Duplicate option %s", option); } return optionMap; diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PushConfig.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PushConfig.java index b8e9fae3f578..cd5c4aa06cda 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PushConfig.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PushConfig.java @@ -60,7 +60,16 @@ private Builder() { * Sets the URL locating the endpoint to which messages should be pushed. For example, an * endpoint might use {@code https://example.com/push}. */ + @Deprecated public Builder endpoint(String endpoint) { + return setEndpoint(endpoint); + } + + /** + * Sets the URL locating the endpoint to which messages should be pushed. For example, an + * endpoint might use {@code https://example.com/push}. + */ + public Builder setEndpoint(String endpoint) { this.endpoint = checkNotNull(endpoint); return this; } @@ -112,7 +121,33 @@ public Builder addAttribute(String name, String value) { * * @see Message Format */ + @Deprecated public Builder attributes(Map attributes) { + return setAttributes(attributes); + } + + /** + * Sets the API-supported attributes that can be used to control different aspects of the + * message delivery. + * + *

The currently supported attribute is {@code x-goog-version}, which can be used to change + * the format of the push message. This attribute indicates the version of the data expected by + * the endpoint. The endpoint version is based on the version of the Pub/Sub API. Possible + * values for this attribute are: + *

    + *
  • {@code v1beta1}: uses the push format defined in the v1beta1 Pub/Sub API + *
  • {@code v1} or {@code v1beta2}: uses the push format defined in the v1 Pub/Sub API + *
+ * + *

If the {@code x-goog-version} attribute is not present when a subscription is created (see + * {@link PubSub#create(SubscriptionInfo)} and {@link PubSub#createAsync(SubscriptionInfo)}), it + * will default to {@code v1}. If it is not present when modifying the push config (see + * {@link PubSub#replacePushConfig(String, PushConfig)} and + * {@link PubSub#replacePushConfigAsync(String, PushConfig)}), its value will not be changed. + * + * @see Message Format + */ + public Builder setAttributes(Map attributes) { this.attributes = new HashMap<>(attributes); return this; } @@ -150,7 +185,16 @@ private PushConfig(Builder builder) { * Returns the URL locating the endpoint to which messages should be pushed. For example, an * endpoint might use {@code https://example.com/push}. */ + @Deprecated public String endpoint() { + return getEndpoint(); + } + + /** + * Returns the URL locating the endpoint to which messages should be pushed. For example, an + * endpoint might use {@code https://example.com/push}. + */ + public String getEndpoint() { return endpoint; } @@ -175,7 +219,33 @@ public String endpoint() { * * @see Message Format */ + @Deprecated public Map attributes() { + return getAttributes(); + } + + /** + * Returns the API-supported attributes that can be used to control different aspects of the + * message delivery. + * + *

The currently supported attribute is {@code x-goog-version}, which can be used to change + * the format of the push message. This attribute indicates the version of the data expected by + * the endpoint. The endpoint version is based on the version of the Pub/Sub API. Possible + * values for this attribute are: + *

    + *
  • {@code v1beta1}: uses the push format defined in the v1beta1 Pub/Sub API + *
  • {@code v1} or {@code v1beta2}: uses the push format defined in the v1 Pub/Sub API + *
+ * + *

If the {@code x-goog-version} attribute is not present when a subscription is created (see + * {@link PubSub#create(SubscriptionInfo)} and {@link PubSub#createAsync(SubscriptionInfo)}), it + * will default to {@code v1}. If it is not present when modifying the push config (see + * {@link PubSub#replacePushConfig(String, PushConfig)} and + * {@link PubSub#replacePushConfigAsync(String, PushConfig)}), its value will not be changed. + * + * @see Message Format + */ + public Map getAttributes() { return attributes; } @@ -208,7 +278,7 @@ public String toString() { * Returns a builder for the {@code PushConfig} object. */ public Builder toBuilder() { - return builder(endpoint, attributes); + return newBuilder(endpoint, attributes); } /** @@ -218,7 +288,7 @@ public Builder toBuilder() { * an endpoint might use {@code https://example.com/push}. */ public static PushConfig of(String endpoint) { - return builder(endpoint).build(); + return newBuilder(endpoint).build(); } /** @@ -231,7 +301,7 @@ public static PushConfig of(String endpoint) { * {@link Builder#attributes(Map)} for more details. */ public static PushConfig of(String endpoint, Map attributes) { - return builder(endpoint, attributes).build(); + return newBuilder(endpoint, attributes).build(); } /** @@ -240,8 +310,19 @@ public static PushConfig of(String endpoint, Map attributes) { * @param endpoint the URL locating the endpoint to which messages should be pushed. For example, * an endpoint might use {@code https://example.com/push}. */ + @Deprecated public static Builder builder(String endpoint) { - return new Builder().endpoint(endpoint); + return newBuilder(endpoint); + } + + /** + * Creates a builder for {@code PushConfig} objects given the push endpoint. + * + * @param endpoint the URL locating the endpoint to which messages should be pushed. For example, + * an endpoint might use {@code https://example.com/push}. + */ + public static Builder newBuilder(String endpoint) { + return new Builder().setEndpoint(endpoint); } /** @@ -253,8 +334,22 @@ public static Builder builder(String endpoint) { * @param attributes API supported attributes used to control message delivery. See * {@link Builder#attributes(Map)} for more details. */ + @Deprecated public static Builder builder(String endpoint, Map attributes) { - return builder(endpoint).attributes(attributes); + return newBuilder(endpoint, attributes); + } + + /** + * Creates a builder for {@code PushConfig} objects given the push endpoint and the API-supported + * attributes that can be used to control different aspects of the message delivery. + * + * @param endpoint the URL locating the endpoint to which messages should be pushed. For example, + * an endpoint might use {@code https://example.com/push}. + * @param attributes API supported attributes used to control message delivery. See + * {@link Builder#attributes(Map)} for more details. + */ + public static Builder newBuilder(String endpoint, Map attributes) { + return newBuilder(endpoint).setAttributes(attributes); } com.google.pubsub.v1.PushConfig toPb() { @@ -263,6 +358,6 @@ com.google.pubsub.v1.PushConfig toPb() { } static PushConfig fromPb(com.google.pubsub.v1.PushConfig pushConfigPb) { - return builder(pushConfigPb.getPushEndpoint(), pushConfigPb.getAttributes()).build(); + return newBuilder(pushConfigPb.getPushEndpoint(), pushConfigPb.getAttributesMap()).build(); } } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/ReceivedMessage.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/ReceivedMessage.java index 1af9a5ae46d2..1ebfd6bdcab1 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/ReceivedMessage.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/ReceivedMessage.java @@ -60,26 +60,44 @@ private Builder(String subscription, String ackId, PubSub pubsub, BuilderImpl de } @Override - Builder id(String id) { - delegate.id(id); + Builder setId(String id) { + delegate.setId(id); return this; } @Override + @Deprecated public Builder payload(String payload) { - delegate.payload(payload); + return setPayload(payload); + } + + @Override + public Builder setPayload(String payload) { + delegate.setPayload(payload); return this; } @Override + @Deprecated public Builder payload(ByteArray payload) { - delegate.payload(payload); + return setPayload(payload); + } + + @Override + public Builder setPayload(ByteArray payload) { + delegate.setPayload(payload); return this; } @Override + @Deprecated public Builder attributes(Map attributes) { - delegate.attributes(attributes); + return setAttributes(attributes); + } + + @Override + public Builder setAttributes(Map attributes) { + delegate.setAttributes(attributes); return this; } @@ -102,8 +120,8 @@ public Builder clearAttributes() { } @Override - Builder publishTime(long publishTime) { - delegate.publishTime(publishTime); + Builder setPublishTime(long publishTime) { + delegate.setPublishTime(publishTime); return this; } @@ -146,14 +164,30 @@ public boolean equals(Object obj) { /** * Returns the received message's {@code PubSub} object used to issue requests. */ + @Deprecated public PubSub pubsub() { + return getPubsub(); + } + + /** + * Returns the received message's {@code PubSub} object used to issue requests. + */ + public PubSub getPubsub() { return pubsub; } /** * Returns the name of the subscription this message was received from. */ + @Deprecated public String subscription() { + return getSubscription(); + } + + /** + * Returns the name of the subscription this message was received from. + */ + public String getSubscription() { return subscription; } @@ -161,7 +195,16 @@ public String subscription() { * Returns the acknowledge id of the message. The ack id can be used to acknowledge the received * message. */ + @Deprecated public String ackId() { + return getAckId(); + } + + /** + * Returns the acknowledge id of the message. The ack id can be used to acknowledge the received + * message. + */ + public String getAckId() { return ackId; } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Subscription.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Subscription.java index 4860ac829fdb..0c847a23932b 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Subscription.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Subscription.java @@ -80,38 +80,74 @@ private Builder(Subscription subscription) { } @Override + @Deprecated public Builder topic(TopicId topic) { - delegate.topic(topic); + return setTopic(topic); + } + + @Override + public Builder setTopic(TopicId topic) { + delegate.setTopic(topic); return this; } @Override + @Deprecated public Builder topic(String project, String topic) { - delegate.topic(project, topic); + return setTopic(project, topic); + } + + @Override + public Builder setTopic(String project, String topic) { + delegate.setTopic(project, topic); return this; } @Override + @Deprecated public Builder topic(String topic) { - delegate.topic(topic); + return setTopic(topic); + } + + @Override + public Builder setTopic(String topic) { + delegate.setTopic(topic); return this; } @Override + @Deprecated public Builder name(String name) { - delegate.name(name); + return setName(name); + } + + @Override + public Builder setName(String name) { + delegate.setName(name); return this; } @Override + @Deprecated public Builder pushConfig(PushConfig pushConfig) { - delegate.pushConfig(pushConfig); + return setPushConfig(pushConfig); + } + + @Override + public Builder setPushConfig(PushConfig pushConfig) { + delegate.setPushConfig(pushConfig); return this; } @Override + @Deprecated public Builder ackDeadLineSeconds(int ackDeadLineSeconds) { - delegate.ackDeadLineSeconds(ackDeadLineSeconds); + return setAckDeadLineSeconds(ackDeadLineSeconds); + } + + @Override + public Builder setAckDeadLineSeconds(int ackDeadLineSeconds) { + delegate.setAckDeadLineSeconds(ackDeadLineSeconds); return this; } @@ -152,7 +188,15 @@ public final boolean equals(Object obj) { /** * Returns the subscription's {@code PubSub} object used to issue requests. */ + @Deprecated public PubSub pubSub() { + return getPubsub(); + } + + /** + * Returns the subscription's {@code PubSub} object used to issue requests. + */ + public PubSub getPubsub() { return pubsub; } @@ -173,7 +217,7 @@ public PubSub pubSub() { * @throws PubSubException upon failure */ public boolean delete() { - return pubsub.deleteSubscription(name()); + return pubsub.deleteSubscription(getName()); } /** @@ -195,7 +239,7 @@ public boolean delete() { * */ public Future deleteAsync() { - return pubsub.deleteSubscriptionAsync(name()); + return pubsub.deleteSubscriptionAsync(getName()); } /** @@ -214,7 +258,7 @@ public Future deleteAsync() { * @throws PubSubException upon failure */ public Subscription reload() { - return pubsub.getSubscription(name()); + return pubsub.getSubscription(getName()); } /** @@ -236,7 +280,7 @@ public Subscription reload() { * @throws PubSubException upon failure */ public Future reloadAsync() { - return pubsub.getSubscriptionAsync(name()); + return pubsub.getSubscriptionAsync(getName()); } /** @@ -263,7 +307,7 @@ public Future reloadAsync() { * @throws PubSubException upon failure, or if the subscription does not exist */ public void replacePushConfig(PushConfig pushConfig) { - pubsub.replacePushConfig(name(), pushConfig); + pubsub.replacePushConfig(getName(), pushConfig); } /** @@ -296,7 +340,7 @@ public void replacePushConfig(PushConfig pushConfig) { * @return a {@code Future} to wait for the replace operation to be completed. */ public Future replacePushConfigAsync(PushConfig pushConfig) { - return pubsub.replacePushConfigAsync(name(), pushConfig); + return pubsub.replacePushConfigAsync(getName(), pushConfig); } /** @@ -322,7 +366,7 @@ public Future replacePushConfigAsync(PushConfig pushConfig) { * @throws PubSubException upon failure */ public Iterator pull(int maxMessages) { - return pubsub.pull(name(), maxMessages); + return pubsub.pull(getName(), maxMessages); } /** @@ -350,7 +394,7 @@ public Iterator pull(int maxMessages) { * @throws PubSubException upon failure */ public Future> pullAsync(int maxMessages) { - return pubsub.pullAsync(name(), maxMessages); + return pubsub.pullAsync(getName(), maxMessages); } /** @@ -388,7 +432,7 @@ public Future> pullAsync(int maxMessages) { * @return a message consumer for the provided subscription and options */ public MessageConsumer pullAsync(MessageProcessor callback, PullOption... options) { - return pubsub.pullAsync(name(), callback, options); + return pubsub.pullAsync(getName(), callback, options); } /** @@ -406,7 +450,7 @@ public MessageConsumer pullAsync(MessageProcessor callback, PullOption... option * @throws PubSubException upon failure */ public Policy getPolicy() { - return pubsub.getSubscriptionPolicy(this.name()); + return pubsub.getSubscriptionPolicy(this.getName()); } /** @@ -427,7 +471,7 @@ public Policy getPolicy() { * @throws PubSubException upon failure */ public Future getPolicyAsync() { - return pubsub.getSubscriptionPolicyAsync(this.name()); + return pubsub.getSubscriptionPolicyAsync(this.getName()); } /** @@ -456,7 +500,7 @@ public Future getPolicyAsync() { * @throws PubSubException upon failure */ public Policy replacePolicy(Policy newPolicy) { - return pubsub.replaceSubscriptionPolicy(this.name(), newPolicy); + return pubsub.replaceSubscriptionPolicy(this.getName(), newPolicy); } /** @@ -489,7 +533,7 @@ public Policy replacePolicy(Policy newPolicy) { * @throws PubSubException upon failure */ public Future replacePolicyAsync(Policy newPolicy) { - return pubsub.replaceSubscriptionPolicyAsync(this.name(), newPolicy); + return pubsub.replaceSubscriptionPolicyAsync(this.getName(), newPolicy); } /** @@ -513,7 +557,7 @@ public Future replacePolicyAsync(Policy newPolicy) { * Permissions and Roles */ public List testPermissions(List permissions) { - return pubsub.testSubscriptionPermissions(this.name(), permissions); + return pubsub.testSubscriptionPermissions(this.getName(), permissions); } /** @@ -542,7 +586,7 @@ public List testPermissions(List permissions) { * Permissions and Roles */ public Future> testPermissionsAsync(List permissions) { - return pubsub.testSubscriptionPermissionsAsync(this.name(), permissions); + return pubsub.testSubscriptionPermissionsAsync(this.getName(), permissions); } private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/SubscriptionId.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/SubscriptionId.java index d083ecd04f26..d73667c79658 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/SubscriptionId.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/SubscriptionId.java @@ -46,14 +46,30 @@ public class SubscriptionId implements Serializable { /** * Returns the name of the project where the subscription resides. */ + @Deprecated public String project() { + return getProject(); + } + + /** + * Returns the name of the project where the subscription resides. + */ + public String getProject() { return project; } /** * Returns the name of the subscription. */ + @Deprecated public String subscription() { + return getSubscription(); + } + + /** + * Returns the name of the subscription. + */ + public String getSubscription() { return subscription; } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/SubscriptionInfo.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/SubscriptionInfo.java index e85a20b53334..6c62b85772c0 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/SubscriptionInfo.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/SubscriptionInfo.java @@ -69,33 +69,72 @@ public abstract static class Builder { * ({@code %}). It must be between 3 and 255 characters in length and cannot begin with the * string {@code goog}. */ + @Deprecated public abstract Builder name(String name); + /** + * Sets the name of the subscription. The name must start with a letter, and contain only + * letters ({@code [A-Za-z]}), numbers ({@code [0-9]}), dashes ({@code -}), underscores + * ({@code _}), periods ({@code .}), tildes ({@code ~}), plus ({@code +}) or percent signs + * ({@code %}). It must be between 3 and 255 characters in length and cannot begin with the + * string {@code goog}. + */ + public abstract Builder setName(String name); + /** * Sets the topic the subscription refers to, given the topic name. The topic is assumed to * reside in the {@link PubSubOptions#projectId()} project. */ + @Deprecated public abstract Builder topic(String topic); + /** + * Sets the topic the subscription refers to, given the topic name. The topic is assumed to + * reside in the {@link PubSubOptions#projectId()} project. + */ + public abstract Builder setTopic(String topic); + /** * Sets the topic the subscription refers to, given the project and topic names. */ + @Deprecated public abstract Builder topic(String project, String topic); + /** + * Sets the topic the subscription refers to, given the project and topic names. + */ + public abstract Builder setTopic(String project, String topic); + /** * Sets the topic the subscription refers to, given the topic identity. If * {@code topic.project()} is {@code null} the topic is assumed to reside in the * {@link PubSubOptions#projectId()} project. */ + @Deprecated public abstract Builder topic(TopicId topic); + /** + * Sets the topic the subscription refers to, given the topic identity. If + * {@code topic.project()} is {@code null} the topic is assumed to reside in the + * {@link PubSubOptions#projectId()} project. + */ + public abstract Builder setTopic(TopicId topic); + /** * Sets the push configuration for the subscription. If set, the subscription will be in * push mode and the {@code pushConfig} parameter provides the push endpoint. If not set, the * subscription will be in pull mode. */ + @Deprecated public abstract Builder pushConfig(PushConfig pushConfig); + /** + * Sets the push configuration for the subscription. If set, the subscription will be in + * push mode and the {@code pushConfig} parameter provides the push endpoint. If not set, the + * subscription will be in pull mode. + */ + public abstract Builder setPushConfig(PushConfig pushConfig); + /** * Sets the maximum time after a subscriber receives a message before the subscriber should * acknowledge the message. After message delivery but before the ack deadline expires and @@ -106,8 +145,21 @@ public abstract static class Builder { * delivery, this value is used to set the request timeout for the call to the push endpoint. * This value must be between 10 and 600 seconds, if not specified, 10 seconds is used. */ + @Deprecated public abstract Builder ackDeadLineSeconds(int ackDeadLineSeconds); + /** + * Sets the maximum time after a subscriber receives a message before the subscriber should + * acknowledge the message. After message delivery but before the ack deadline expires and + * before the message is acknowledged, it is an outstanding message and will not be delivered + * again during that time (on a best-effort basis). For pull subscriptions, this value is used + * as the initial value for the ack deadline. To override the ack deadline value for a given + * message, use {@link PubSub#modifyAckDeadline(String, int, TimeUnit, Iterable)}. For push + * delivery, this value is used to set the request timeout for the call to the push endpoint. + * This value must be between 10 and 600 seconds, if not specified, 10 seconds is used. + */ + public abstract Builder setAckDeadLineSeconds(int ackDeadLineSeconds); + /** * Creates a subscription object. */ @@ -134,35 +186,71 @@ private BuilderImpl(TopicId topic, String name) { } @Override + @Deprecated public Builder name(String name) { + return setName(name); + } + + @Override + public Builder setName(String name) { this.name = checkNotNull(name); return this; } @Override + @Deprecated public Builder topic(String project, String topic) { - return topic(TopicId.of(checkNotNull(project), topic)); + return setTopic(project, topic); + } + + @Override + public Builder setTopic(String project, String topic) { + return setTopic(TopicId.of(checkNotNull(project), topic)); } @Override + @Deprecated public Builder topic(String topic) { - return topic(TopicId.of(topic)); + return setTopic(topic); } @Override + public Builder setTopic(String topic) { + return setTopic(TopicId.of(topic)); + } + + @Override + @Deprecated public Builder topic(TopicId topic) { + return setTopic(topic); + } + + @Override + public Builder setTopic(TopicId topic) { this.topic = checkNotNull(topic); return this; } @Override + @Deprecated public Builder pushConfig(PushConfig pushConfig) { + return setPushConfig(pushConfig); + } + + @Override + public Builder setPushConfig(PushConfig pushConfig) { this.pushConfig = pushConfig; return this; } @Override + @Deprecated public Builder ackDeadLineSeconds(int ackDeadlineSeconds) { + return setAckDeadLineSeconds(ackDeadlineSeconds); + } + + @Override + public Builder setAckDeadLineSeconds(int ackDeadlineSeconds) { this.ackDeadlineSeconds = ackDeadlineSeconds; return this; } @@ -186,7 +274,18 @@ public SubscriptionInfo build() { * After a topic is deleted, existing subscriptions to that topic are not deleted, but their topic * field is set to {@link TopicId#deletedTopic()}. */ + @Deprecated public TopicId topic() { + return getTopic(); + } + + /** + * Returns the identity of the topic this subscription refers to. If {@link TopicId#project()} is + * {@code null} the topic is assumed to reside in the {@link PubSubOptions#projectId()} project. + * After a topic is deleted, existing subscriptions to that topic are not deleted, but their topic + * field is set to {@link TopicId#deletedTopic()}. + */ + public TopicId getTopic() { return topic; } @@ -197,7 +296,19 @@ public TopicId topic() { * ({@code %}). It must be between 3 and 255 characters in length and cannot begin with the * string {@code goog}. */ + @Deprecated public String name() { + return getName(); + } + + /** + * Returns the name of the subscription. The name must start with a letter, and contain only + * letters ({@code [A-Za-z]}), numbers ({@code [0-9]}), dashes ({@code -}), underscores + * ({@code _}), periods ({@code .}), tildes ({@code ~}), plus ({@code +}) or percent signs + * ({@code %}). It must be between 3 and 255 characters in length and cannot begin with the + * string {@code goog}. + */ + public String getName() { return name; } @@ -206,7 +317,17 @@ public String name() { * and the returned value defines the push endpoint. If {@code null}, the subscription is in pull * mode. */ + @Deprecated public PushConfig pushConfig() { + return getPushConfig(); + } + + /** + * Returns the push configuration for the subscription. If set, the subscription is in push mode + * and the returned value defines the push endpoint. If {@code null}, the subscription is in pull + * mode. + */ + public PushConfig getPushConfig() { return pushConfig; } @@ -220,7 +341,22 @@ public PushConfig pushConfig() { * delivery, this value is used to set the request timeout for the call to the push endpoint. This * value must be between 10 and 600 seconds, if not specified, 10 seconds is used. */ + @Deprecated public long ackDeadlineSeconds() { + return getAckDeadlineSeconds(); + } + + /** + * Returns the maximum time after a subscriber receives a message before the subscriber should + * acknowledge the message. After message delivery but before the ack deadline expires and + * before the message is acknowledged, it is an outstanding message and will not be delivered + * again during that time (on a best-effort basis). For pull subscriptions, this value is used + * as the initial value for the ack deadline. To override the ack deadline value for a given + * message, use {@link PubSub#modifyAckDeadline(String, int, TimeUnit, Iterable)}. For push + * delivery, this value is used to set the request timeout for the call to the push endpoint. This + * value must be between 10 and 600 seconds, if not specified, 10 seconds is used. + */ + public long getAckDeadlineSeconds() { return ackDeadlineSeconds; } @@ -267,13 +403,13 @@ com.google.pubsub.v1.Subscription toPb(String projectId) { } static SubscriptionInfo fromPb(com.google.pubsub.v1.Subscription subscription) { - Builder builder = builder(TopicId.fromPb(subscription.getTopic()), + Builder builder = newBuilder(TopicId.fromPb(subscription.getTopic()), SubscriberApi.parseSubscriptionFromSubscriptionName(subscription.getName())); - builder.ackDeadLineSeconds(subscription.getAckDeadlineSeconds()); + builder.setAckDeadLineSeconds(subscription.getAckDeadlineSeconds()); // A subscription with an "empty" push config is a pull subscription if (subscription.hasPushConfig() && !subscription.getPushConfig().getPushEndpoint().equals("")) { - builder.pushConfig(PushConfig.fromPb(subscription.getPushConfig())); + builder.setPushConfig(PushConfig.fromPb(subscription.getPushConfig())); } return builder.build(); } @@ -297,7 +433,7 @@ public Builder toBuilder() { * string {@code goog}. */ public static SubscriptionInfo of(String topic, String name) { - return builder(topic, name).build(); + return newBuilder(topic, name).build(); } /** @@ -313,7 +449,7 @@ public static SubscriptionInfo of(String topic, String name) { * string {@code goog}. */ public static SubscriptionInfo of(TopicId topic, String name) { - return builder(topic, name).build(); + return newBuilder(topic, name).build(); } /** @@ -331,7 +467,7 @@ public static SubscriptionInfo of(TopicId topic, String name) { * an endpoint might use {@code https://example.com/push}. */ public static SubscriptionInfo of(String topic, String name, String endpoint) { - return builder(topic, name).pushConfig(PushConfig.of(endpoint)).build(); + return newBuilder(topic, name).setPushConfig(PushConfig.of(endpoint)).build(); } /** @@ -349,7 +485,7 @@ public static SubscriptionInfo of(String topic, String name, String endpoint) { * an endpoint might use {@code https://example.com/push}. */ public static SubscriptionInfo of(TopicId topic, String name, String endpoint) { - return builder(topic, name).pushConfig(PushConfig.of(endpoint)).build(); + return newBuilder(topic, name).setPushConfig(PushConfig.of(endpoint)).build(); } /** @@ -364,8 +500,25 @@ public static SubscriptionInfo of(TopicId topic, String name, String endpoint) { * ({@code %}). It must be between 3 and 255 characters in length and cannot begin with the * string {@code goog}. */ + @Deprecated public static Builder builder(String topic, String name) { - return builder(TopicId.of(topic), name); + return newBuilder(topic, name); + } + + /** + * Creates a builder for {@code SubscriptionInfo} objects given the name of the topic and the name + * of the subscription. The topic is assumed to reside in the {@link PubSubOptions#projectId()} + * project. + * + * @param topic the name of the topic the subscription refers to + * @param name the name of the subscription. The name must start with a letter, and contain only + * letters ({@code [A-Za-z]}), numbers ({@code [0-9]}), dashes ({@code -}), underscores + * ({@code _}), periods ({@code .}), tildes ({@code ~}), plus ({@code +}) or percent signs + * ({@code %}). It must be between 3 and 255 characters in length and cannot begin with the + * string {@code goog}. + */ + public static Builder newBuilder(String topic, String name) { + return newBuilder(TopicId.of(topic), name); } /** @@ -380,7 +533,24 @@ public static Builder builder(String topic, String name) { * ({@code %}). It must be between 3 and 255 characters in length and cannot begin with the * string {@code goog}. */ + @Deprecated public static Builder builder(TopicId topic, String name) { + return newBuilder(topic, name); + } + + /** + * Creates a builder for {@code SubscriptionInfo} objects given the identity of the topic and the + * name of the subscription. If {@code topic.project()} is {@code null} the topic is assumed to + * reside in the {@link PubSubOptions#projectId()} project. + * + * @param topic the identity of the topic the subscription refers to + * @param name the name of the subscription. The name must start with a letter, and contain only + * letters ({@code [A-Za-z]}), numbers ({@code [0-9]}), dashes ({@code -}), underscores + * ({@code _}), periods ({@code .}), tildes ({@code ~}), plus ({@code +}) or percent signs + * ({@code %}). It must be between 3 and 255 characters in length and cannot begin with the + * string {@code goog}. + */ + public static Builder newBuilder(TopicId topic, String name) { return new BuilderImpl(topic, name); } } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Topic.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Topic.java index d4b9e9069636..fad88501059e 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Topic.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Topic.java @@ -60,8 +60,14 @@ private Builder(Topic topic) { } @Override + @Deprecated public Builder name(String name) { - delegate.name(name); + return setName(name); + } + + @Override + public Builder setName(String name) { + delegate.setName(name); return this; } @@ -102,7 +108,15 @@ public final boolean equals(Object obj) { /** * Returns the topic's {@code PubSub} object used to issue requests. */ + @Deprecated public PubSub pubSub() { + return getPubsub(); + } + + /** + * Returns the topic's {@code PubSub} object used to issue requests. + */ + public PubSub getPubsub() { return pubsub; } @@ -123,7 +137,7 @@ public PubSub pubSub() { * @throws PubSubException upon failure */ public boolean delete() { - return pubsub.deleteTopic(name()); + return pubsub.deleteTopic(getName()); } /** @@ -146,7 +160,7 @@ public boolean delete() { * @throws PubSubException upon failure */ public Future deleteAsync() { - return pubsub.deleteTopicAsync(name()); + return pubsub.deleteTopicAsync(getName()); } /** @@ -164,7 +178,7 @@ public Future deleteAsync() { * @throws PubSubException upon failure */ public Topic reload() { - return pubsub.getTopic(name()); + return pubsub.getTopic(getName()); } /** @@ -185,7 +199,7 @@ public Topic reload() { * @throws PubSubException upon failure */ public Future reloadAsync() { - return pubsub.getTopicAsync(name()); + return pubsub.getTopicAsync(getName()); } /** @@ -204,7 +218,7 @@ public Future reloadAsync() { * payload and no attributes */ public String publish(Message message) { - return pubsub.publish(name(), message); + return pubsub.publish(getName(), message); } /** @@ -225,7 +239,7 @@ public String publish(Message message) { * @return a {@code Future} for the unique service-generated id for the message */ public Future publishAsync(Message message) { - return pubsub.publishAsync(name(), message); + return pubsub.publishAsync(getName(), message); } /** @@ -247,7 +261,7 @@ public Future publishAsync(Message message) { * empty payload and no attributes */ public List publish(Message message, Message... messages) { - return pubsub.publish(name(), message, messages); + return pubsub.publish(getName(), message, messages); } /** @@ -271,7 +285,7 @@ public List publish(Message message, Message... messages) { * the messages. */ public Future> publishAsync(Message message, Message... messages) { - return pubsub.publishAsync(name(), message, messages); + return pubsub.publishAsync(getName(), message, messages); } /** @@ -293,7 +307,7 @@ public Future> publishAsync(Message message, Message... messages) { * empty payload and no attributes */ public List publish(Iterable messages) { - return pubsub.publish(name(), messages); + return pubsub.publish(getName(), messages); } /** @@ -317,7 +331,7 @@ public List publish(Iterable messages) { * the messages. */ public Future> publishAsync(Iterable messages) { - return pubsub.publishAsync(name(), messages); + return pubsub.publishAsync(getName(), messages); } /** @@ -338,7 +352,7 @@ public Future> publishAsync(Iterable messages) { * @throws PubSubException upon failure */ public Page listSubscriptions(ListOption... options) { - return pubsub.listSubscriptions(name(), options); + return pubsub.listSubscriptions(getName(), options); } /** @@ -363,7 +377,7 @@ public Page listSubscriptions(ListOption... options) { * */ public Future> listSubscriptionsAsync(ListOption... options) { - return pubsub.listSubscriptionsAsync(name(), options); + return pubsub.listSubscriptionsAsync(getName(), options); } /** @@ -381,7 +395,7 @@ public Future> listSubscriptionsAsync(ListOption... op * @throws PubSubException upon failure */ public Policy getPolicy() { - return pubsub.getTopicPolicy(this.name()); + return pubsub.getTopicPolicy(this.getName()); } /** @@ -402,7 +416,7 @@ public Policy getPolicy() { * @throws PubSubException upon failure */ public Future getPolicyAsync() { - return pubsub.getTopicPolicyAsync(this.name()); + return pubsub.getTopicPolicyAsync(this.getName()); } /** @@ -431,7 +445,7 @@ public Future getPolicyAsync() { * @throws PubSubException upon failure */ public Policy replacePolicy(Policy newPolicy) { - return pubsub.replaceTopicPolicy(this.name(), newPolicy); + return pubsub.replaceTopicPolicy(this.getName(), newPolicy); } /** @@ -464,7 +478,7 @@ public Policy replacePolicy(Policy newPolicy) { * @throws PubSubException upon failure */ public Future replacePolicyAsync(Policy newPolicy) { - return pubsub.replaceTopicPolicyAsync(this.name(), newPolicy); + return pubsub.replaceTopicPolicyAsync(this.getName(), newPolicy); } /** @@ -489,7 +503,7 @@ public Future replacePolicyAsync(Policy newPolicy) { * Permissions and Roles */ public List testPermissions(List permissions) { - return pubsub.testTopicPermissions(this.name(), permissions); + return pubsub.testTopicPermissions(this.getName(), permissions); } /** @@ -518,7 +532,7 @@ public List testPermissions(List permissions) { * Permissions and Roles */ public Future> testPermissionsAsync(List permissions) { - return pubsub.testTopicPermissionsAsync(this.name(), permissions); + return pubsub.testTopicPermissionsAsync(this.getName(), permissions); } private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/TopicId.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/TopicId.java index 458df8372dd4..f21810fe3dbc 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/TopicId.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/TopicId.java @@ -54,14 +54,31 @@ private TopicId(String project, String topic) { * Returns the name of the project where the topic resides. If {@code null} the topic is assumed * to reside in the {@link PubSubOptions#projectId()} project. */ + @Deprecated public String project() { + return getProject(); + } + + /** + * Returns the name of the project where the topic resides. If {@code null} the topic is assumed + * to reside in the {@link PubSubOptions#projectId()} project. + */ + public String getProject() { return project; } /** * Returns the name of the topic. */ + @Deprecated public String topic() { + return getTopic(); + } + + /** + * Returns the name of the topic. + */ + public String getTopic() { return topic; } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/TopicInfo.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/TopicInfo.java index e1b2dc6275a0..ef03accfcedd 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/TopicInfo.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/TopicInfo.java @@ -47,8 +47,17 @@ public abstract static class Builder { * periods ({@code .}), tildes ({@code ~}), plus ({@code +}) or percent signs ({@code %}). It * must be between 3 and 255 characters in length and cannot begin with the string {@code goog}. */ + @Deprecated public abstract Builder name(String name); + /** + * Sets the name of the topic. The name must start with a letter, and contain only letters + * ({@code [A-Za-z]}), numbers ({@code [0-9]}), dashes ({@code -}), underscores ({@code _}), + * periods ({@code .}), tildes ({@code ~}), plus ({@code +}) or percent signs ({@code %}). It + * must be between 3 and 255 characters in length and cannot begin with the string {@code goog}. + */ + public abstract Builder setName(String name); + /** * Creates a topic object. */ @@ -68,7 +77,13 @@ static final class BuilderImpl extends Builder { } @Override + @Deprecated public Builder name(String name) { + return setName(name); + } + + @Override + public Builder setName(String name) { this.name = checkNotNull(name); return this; } @@ -89,7 +104,18 @@ public TopicInfo build() { * periods ({@code .}), tildes ({@code ~}), plus ({@code +}) or percent signs ({@code %}). It * must be between 3 and 255 characters in length and cannot begin with the string {@code goog}. */ + @Deprecated public String name() { + return getName(); + } + + /** + * Returns the name of the topic. The name must start with a letter, and contain only letters + * ({@code [A-Za-z]}), numbers ({@code [0-9]}), dashes ({@code -}), underscores ({@code _}), + * periods ({@code .}), tildes ({@code ~}), plus ({@code +}) or percent signs ({@code %}). It + * must be between 3 and 255 characters in length and cannot begin with the string {@code goog}. + */ + public String getName() { return name; } @@ -124,7 +150,7 @@ com.google.pubsub.v1.Topic toPb(String projectId) { } static TopicInfo fromPb(com.google.pubsub.v1.Topic topicPb) { - return builder(PublisherApi.parseTopicFromTopicName(topicPb.getName())).build(); + return newBuilder(PublisherApi.parseTopicFromTopicName(topicPb.getName())).build(); } /** @@ -144,7 +170,7 @@ public Builder toBuilder() { * {@code goog}. */ public static TopicInfo of(String name) { - return builder(name).build(); + return newBuilder(name).build(); } /** @@ -156,7 +182,21 @@ public static TopicInfo of(String name) { * It must be between 3 and 255 characters in length and cannot begin with the string * {@code goog}. */ + @Deprecated public static Builder builder(String name) { + return newBuilder(name); + } + + /** + * Creates a builder for {@code TopicInfo} objects given the name of the topic. + * + * @param name the name of the topic. The name must start with a letter, and contain only letters + * ({@code [A-Za-z]}), numbers ({@code [0-9]}), dashes ({@code -}), underscores ({@code _}), + * periods ({@code .}), tildes ({@code ~}), plus ({@code +}) or percent signs ({@code %}). + * It must be between 3 and 255 characters in length and cannot begin with the string + * {@code goog}. + */ + public static Builder newBuilder(String name) { return new BuilderImpl(name); } } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java index 5a7b21b80bec..a7978d9b4ee7 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java @@ -145,7 +145,16 @@ public ManagedChannel createChannel() { * Returns a {@link PubSubOptions} instance that sets the host to use the PubSub emulator on * localhost. */ + @Deprecated public PubSubOptions options() { + return getOptions(); + } + + /** + * Returns a {@link PubSubOptions} instance that sets the host to use the PubSub emulator on + * localhost. + */ + public PubSubOptions getOptions() { return PubSubOptions.builder() .projectId(projectId) .host("localhost:" + port) diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/package-info.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/package-info.java index 0d564e7e84f1..63148437be2b 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/package-info.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/package-info.java @@ -22,7 +22,7 @@ *

 {@code
  * LocalPubSubHelper helper = LocalPubSubHelper.create();
  * helper.start();
- * PubSub localPubsub = helper.options().service();
+ * PubSub localPubsub = helper.getOptions().service();
  * } 
* *

After the test: diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/BaseSystemTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/BaseSystemTest.java index 98fda1550ee3..99fa0a902449 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/BaseSystemTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/BaseSystemTest.java @@ -73,7 +73,7 @@ public abstract class BaseSystemTest { public void testCreateGetAndDeleteTopic() { String name = formatForTest("test-create-get-delete-topic"); Topic topic = pubsub().create(TopicInfo.of(name)); - assertEquals(name, topic.name()); + assertEquals(name, topic.getName()); Topic remoteTopic = pubsub().getTopic(name); assertEquals(topic, remoteTopic); assertTrue(topic.delete()); @@ -95,7 +95,7 @@ public void testCreateGetAndDeleteTopicAsync() throws ExecutionException, Interr String name = formatForTest("test-create-get-delete-async-topic"); Future topicFuture = pubsub().createAsync(TopicInfo.of(name)); Topic createdTopic = topicFuture.get(); - assertEquals(name, createdTopic.name()); + assertEquals(name, createdTopic.getName()); topicFuture = pubsub().getTopicAsync(name); assertEquals(createdTopic, topicFuture.get()); assertTrue(createdTopic.deleteAsync().get()); @@ -111,11 +111,11 @@ public void testListTopics() { Page topics = pubsub().listTopics(PubSub.ListOption.pageSize(1)); Iterator iterator = topics.iterateAll(); while (iterator.hasNext()) { - topicNames.add(iterator.next().name()); + topicNames.add(iterator.next().getName()); } - assertTrue(topicNames.contains(topic1.name())); - assertTrue(topicNames.contains(topic2.name())); - assertTrue(topicNames.contains(topic3.name())); + assertTrue(topicNames.contains(topic1.getName())); + assertTrue(topicNames.contains(topic2.getName())); + assertTrue(topicNames.contains(topic3.getName())); assertTrue(topic1.delete()); assertTrue(topic2.delete()); assertTrue(topic3.delete()); @@ -130,11 +130,11 @@ public void testListTopicsAsync() throws ExecutionException, InterruptedExceptio Future> pageFuture = pubsub().listTopicsAsync(PubSub.ListOption.pageSize(1)); Iterator iterator = pageFuture.get().iterateAll(); while (iterator.hasNext()) { - topicNames.add(iterator.next().name()); + topicNames.add(iterator.next().getName()); } - assertTrue(topicNames.contains(topic1.name())); - assertTrue(topicNames.contains(topic2.name())); - assertTrue(topicNames.contains(topic3.name())); + assertTrue(topicNames.contains(topic1.getName())); + assertTrue(topicNames.contains(topic2.getName())); + assertTrue(topicNames.contains(topic3.getName())); assertTrue(topic1.delete()); assertTrue(topic2.delete()); assertTrue(topic3.delete()); @@ -218,9 +218,9 @@ public void testCreateGetAndDeleteSubscription() { pubsub().create(TopicInfo.of(topic)); String name = formatForTest("test-create-get-delete-subscription"); Subscription subscription = pubsub().create(SubscriptionInfo.of(topic, name)); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.topic()); - assertEquals(name, subscription.name()); - assertNull(subscription.pushConfig()); + assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.getTopic()); + assertEquals(name, subscription.getName()); + assertNull(subscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 // assertEquals(10, subscription.ackDeadlineSeconds()); Subscription remoteSubscription = pubsub().getSubscription(name); @@ -248,12 +248,12 @@ public void testCreateGetAndDeleteSubscriptionAsync() String name = formatForTest("test-create-get-delete-async-subscription"); String endpoint = "https://" + pubsub().options().projectId() + ".appspot.com/push"; PushConfig pushConfig = PushConfig.of(endpoint); - Future subscriptionFuture = - pubsub().createAsync(SubscriptionInfo.builder(topic, name).pushConfig(pushConfig).build()); + Future subscriptionFuture = pubsub().createAsync( + SubscriptionInfo.newBuilder(topic, name).setPushConfig(pushConfig).build()); Subscription subscription = subscriptionFuture.get(); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.topic()); - assertEquals(name, subscription.name()); - assertEquals(pushConfig, subscription.pushConfig()); + assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.getTopic()); + assertEquals(name, subscription.getName()); + assertEquals(pushConfig, subscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 // assertEquals(10, subscription.ackDeadlineSeconds()); subscriptionFuture = pubsub().getSubscriptionAsync(name); @@ -270,17 +270,17 @@ public void testGetSubscriptionDeletedTopic() { pubsub().create(TopicInfo.of(topic)); String name = formatForTest("test-get-deleted-topic-subscription"); Subscription subscription = pubsub().create(SubscriptionInfo.of(topic, name)); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.topic()); - assertEquals(name, subscription.name()); - assertNull(subscription.pushConfig()); + assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.getTopic()); + assertEquals(name, subscription.getName()); + assertNull(subscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 // assertEquals(10, subscription.ackDeadlineSeconds()); assertTrue(pubsub().deleteTopic(topic)); assertNull(pubsub().getTopic(topic)); Subscription remoteSubscription = pubsub().getSubscription(name); - assertEquals(TopicId.of("_deleted-topic_"), remoteSubscription.topic()); - assertEquals(name, remoteSubscription.name()); - assertNull(remoteSubscription.pushConfig()); + assertEquals(TopicId.of("_deleted-topic_"), remoteSubscription.getTopic()); + assertEquals(name, remoteSubscription.getName()); + assertNull(remoteSubscription.getPushConfig()); assertTrue(subscription.delete()); } @@ -292,17 +292,17 @@ public void testReplaceSubscriptionPushConfig() { String endpoint = "https://" + pubsub().options().projectId() + ".appspot.com/push"; PushConfig pushConfig = PushConfig.of(endpoint); Subscription subscription = - pubsub().create(SubscriptionInfo.builder(topic, name).pushConfig(pushConfig).build()); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.topic()); - assertEquals(name, subscription.name()); - assertEquals(pushConfig, subscription.pushConfig()); + pubsub().create(SubscriptionInfo.newBuilder(topic, name).setPushConfig(pushConfig).build()); + assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.getTopic()); + assertEquals(name, subscription.getName()); + assertEquals(pushConfig, subscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 // assertEquals(10, subscription.ackDeadlineSeconds()); pubsub().replacePushConfig(name, null); Subscription remoteSubscription = pubsub().getSubscription(name); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), remoteSubscription.topic()); - assertEquals(name, remoteSubscription.name()); - assertNull(remoteSubscription.pushConfig()); + assertEquals(TopicId.of(pubsub().options().projectId(), topic), remoteSubscription.getTopic()); + assertEquals(name, remoteSubscription.getName()); + assertNull(remoteSubscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 // assertEquals(10, remoteSubscription.ackDeadlineSeconds()); assertTrue(subscription.delete()); @@ -325,18 +325,18 @@ public void testReplaceSubscriptionPushConfigAsync() Future subscriptionFuture = pubsub().createAsync(SubscriptionInfo.of(topic, name)); Subscription subscription = subscriptionFuture.get(); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.topic()); - assertEquals(name, subscription.name()); - assertNull(subscription.pushConfig()); + assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.getTopic()); + assertEquals(name, subscription.getName()); + assertNull(subscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 // assertEquals(10, subscription.ackDeadlineSeconds()); String endpoint = "https://" + pubsub().options().projectId() + ".appspot.com/push"; PushConfig pushConfig = PushConfig.of(endpoint); pubsub().replacePushConfigAsync(name, pushConfig).get(); Subscription remoteSubscription = pubsub().getSubscriptionAsync(name).get(); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), remoteSubscription.topic()); - assertEquals(name, remoteSubscription.name()); - assertEquals(pushConfig, remoteSubscription.pushConfig()); + assertEquals(TopicId.of(pubsub().options().projectId(), topic), remoteSubscription.getTopic()); + assertEquals(name, remoteSubscription.getName()); + assertEquals(pushConfig, remoteSubscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 // assertEquals(10, remoteSubscription.ackDeadlineSeconds()); assertTrue(subscription.deleteAsync().get()); @@ -363,7 +363,7 @@ public void testListSubscriptions() { Page subscriptions = pubsub().listSubscriptions(PubSub.ListOption.pageSize(1)); Iterator iterator = subscriptions.iterateAll(); while (iterator.hasNext()) { - String name = iterator.next().name(); + String name = iterator.next().getName(); subscriptionNames.add(name); } assertTrue(subscriptionNames.contains(subscriptionName1)); @@ -373,12 +373,12 @@ public void testListSubscriptions() { Page topic1Subscriptions = topic1.listSubscriptions(PubSub.ListOption.pageSize(1)); Iterator firstStringPageIterator = topic1Subscriptions.values().iterator(); - topicSubscriptionNames.add(firstStringPageIterator.next().subscription()); + topicSubscriptionNames.add(firstStringPageIterator.next().getSubscription()); assertFalse(firstStringPageIterator.hasNext()); Iterator topicSubscriptionsIterator = topic1Subscriptions.nextPage().iterateAll(); while (topicSubscriptionsIterator.hasNext()) { - topicSubscriptionNames.add(topicSubscriptionsIterator.next().subscription()); + topicSubscriptionNames.add(topicSubscriptionsIterator.next().getSubscription()); } assertEquals(2, topicSubscriptionNames.size()); assertTrue(topicSubscriptionNames.contains(subscriptionName1)); @@ -411,7 +411,7 @@ public void testListSubscriptionsAsync() throws ExecutionException, InterruptedE pubsub().listSubscriptionsAsync(PubSub.ListOption.pageSize(1)); Iterator iterator = pageFuture.get().iterateAll(); while (iterator.hasNext()) { - subscriptionNames.add(iterator.next().name()); + subscriptionNames.add(iterator.next().getName()); } assertTrue(subscriptionNames.contains(subscriptionName1)); assertTrue(subscriptionNames.contains(subscriptionName2)); @@ -420,12 +420,12 @@ public void testListSubscriptionsAsync() throws ExecutionException, InterruptedE AsyncPage topic1Subscriptions = topic1.listSubscriptionsAsync(PubSub.ListOption.pageSize(1)).get(); Iterator firstStringPageIterator = topic1Subscriptions.values().iterator(); - topicSubscriptionNames.add(firstStringPageIterator.next().subscription()); + topicSubscriptionNames.add(firstStringPageIterator.next().getSubscription()); assertFalse(firstStringPageIterator.hasNext()); Iterator topicSubscriptionsIterator = topic1Subscriptions.nextPageAsync().get().iterateAll(); while (topicSubscriptionsIterator.hasNext()) { - topicSubscriptionNames.add(topicSubscriptionsIterator.next().subscription()); + topicSubscriptionNames.add(topicSubscriptionsIterator.next().getSubscription()); } assertEquals(2, topicSubscriptionNames.size()); assertTrue(topicSubscriptionNames.contains(subscriptionName1)); @@ -448,8 +448,8 @@ public void testPullMessages() { List messageIds = pubsub().publish(topic, ImmutableList.of(message1, message2)); assertEquals(2, messageIds.size()); Iterator iterator = pubsub().pull(subscription, 2); - assertEquals(message1.payloadAsString(), iterator.next().payloadAsString()); - assertEquals(message2.payloadAsString(), iterator.next().payloadAsString()); + assertEquals(message1.getPayloadAsString(), iterator.next().getPayloadAsString()); + assertEquals(message2.getPayloadAsString(), iterator.next().getPayloadAsString()); assertTrue(pubsub().deleteSubscription(subscription)); assertTrue(pubsub().deleteTopic(topic)); } @@ -459,7 +459,8 @@ public void testPullMessagesAndAutoRenewDeadline() throws InterruptedException { String topic = formatForTest("test-pull-messages-and-renew-deadline-topic"); pubsub().create(TopicInfo.of(topic)); String subscription = formatForTest("test-pull-messages-and-renew-deadline-subscription"); - pubsub().create(SubscriptionInfo.builder(topic, subscription).ackDeadLineSeconds(10).build()); + pubsub().create( + SubscriptionInfo.newBuilder(topic, subscription).setAckDeadLineSeconds(10).build()); Message message1 = Message.of("payload1"); Message message2 = Message.of("payload2"); // todo(mziccard): use batch publish if #1017 gets fixed, or remove this comment @@ -483,7 +484,7 @@ public void testPullMessagesAndAutoRenewDeadline() throws InterruptedException { Iterator nextIterator = pubsub().pull(subscription, 2); assertTrue(nextIterator.hasNext()); ReceivedMessage message = nextIterator.next(); - assertEquals(consumedMessage.payloadAsString(), message.payloadAsString()); + assertEquals(consumedMessage.getPayloadAsString(), message.getPayloadAsString()); assertFalse(nextIterator.hasNext()); consumedMessage.ack(); iterator.next().ack(); @@ -498,7 +499,8 @@ public void testPullMessagesAndModifyAckDeadline() throws InterruptedException { String topic = formatForTest("test-pull-messages-and-modify-deadline-topic"); pubsub().create(TopicInfo.of(topic)); String subscription = formatForTest("test-pull-messages-and-modify-deadline-subscription"); - pubsub().create(SubscriptionInfo.builder(topic, subscription).ackDeadLineSeconds(10).build()); + pubsub().create( + SubscriptionInfo.newBuilder(topic, subscription).setAckDeadLineSeconds(10).build()); Message message1 = Message.of("payload1"); Message message2 = Message.of("payload2"); // todo(mziccard): use batch publish if #1017 gets fixed, or remove this comment @@ -516,7 +518,7 @@ public void testPullMessagesAndModifyAckDeadline() throws InterruptedException { Iterator nextIterator = pubsub().pull(subscription, 2); assertTrue(nextIterator.hasNext()); ReceivedMessage message = nextIterator.next(); - assertEquals(receivedMessages.get(1).payloadAsString(), message.payloadAsString()); + assertEquals(receivedMessages.get(1).getPayloadAsString(), message.getPayloadAsString()); assertFalse(nextIterator.hasNext()); assertTrue(pubsub().deleteSubscription(subscription)); assertTrue(pubsub().deleteTopic(topic)); @@ -539,8 +541,8 @@ public void testPullMessagesAsync() throws ExecutionException, InterruptedExcept List messageIds = pubsub().publish(topic, ImmutableList.of(message1, message2)); assertEquals(2, messageIds.size()); Iterator iterator = pubsub().pullAsync(subscription, 2).get(); - assertEquals(message1.payloadAsString(), iterator.next().payloadAsString()); - assertEquals(message2.payloadAsString(), iterator.next().payloadAsString()); + assertEquals(message1.getPayloadAsString(), iterator.next().getPayloadAsString()); + assertEquals(message2.getPayloadAsString(), iterator.next().getPayloadAsString()); assertTrue(pubsub().deleteSubscription(subscription)); assertTrue(pubsub().deleteTopic(topic)); } @@ -576,7 +578,7 @@ public void process(Message message) throws Exception { countDownLatch.await(); } for (Message message : receivedMessages) { - payloads.contains(message.payloadAsString()); + payloads.contains(message.getPayloadAsString()); } // Messages have all been acked, they should not be pulled again Iterator messages = pubsub().pull(subscription, 2); @@ -610,13 +612,13 @@ public void process(Message message) throws Exception { countDownLatch.await(); } for (Message message : receivedMessages) { - payloads.contains(message.payloadAsString()); + payloads.contains(message.getPayloadAsString()); } // Messages have all been nacked, we should be able to pull them again Thread.sleep(5000); Iterator messages = pubsub().pull(subscription, 2); while (messages.hasNext()) { - payloads.contains(messages.next().payloadAsString()); + payloads.contains(messages.next().getPayloadAsString()); } assertTrue(pubsub().deleteSubscription(subscription)); assertTrue(pubsub().deleteTopic(topic)); @@ -664,7 +666,8 @@ public void testMessageConsumerAndAutoRenewDeadline() throws Exception { pubsub().create(TopicInfo.of(topic)); final String subscription = formatForTest("test-message-consumer-and-renew-deadline-subscription"); - pubsub().create(SubscriptionInfo.builder(topic, subscription).ackDeadLineSeconds(10).build()); + pubsub().create( + SubscriptionInfo.newBuilder(topic, subscription).setAckDeadLineSeconds(10).build()); Message message1 = Message.of("payload1"); Message message2 = Message.of("payload2"); Set payloads = Sets.newHashSet("payload1", "payload2"); @@ -687,7 +690,7 @@ public void process(Message message) throws Exception { countDownLatch.await(); } for (Message message : receivedMessages) { - payloads.contains(message.payloadAsString()); + payloads.contains(message.getPayloadAsString()); } // Messages have all been acked, they should not be pulled again Iterator messages = pubsub().pull(subscription, 2); @@ -740,9 +743,11 @@ public void testAckAndNackMoreMessages() throws ExecutionException, InterruptedE Message message2 = Message.of("payload2"); assertNotNull(pubsub().publish(topic, message1, message2)); Iterator receivedMessages = pubsub().pull(subscription, 2); - pubsub().nack(subscription, receivedMessages.next().ackId(), receivedMessages.next().ackId()); + pubsub().nack(subscription, receivedMessages.next().getAckId(), + receivedMessages.next().getAckId()); receivedMessages = pubsub().pull(subscription, 2); - pubsub().ack(subscription, receivedMessages.next().ackId(), receivedMessages.next().ackId()); + pubsub().ack(subscription, receivedMessages.next().getAckId(), + receivedMessages.next().getAckId()); assertFalse(pubsub().pull(subscription, 2).hasNext()); assertTrue(pubsub().deleteSubscription(subscription)); assertTrue(pubsub().deleteTopic(topic)); @@ -758,12 +763,12 @@ public void testAckAndNackMoreMessagesAsync() throws ExecutionException, Interru Message message2 = Message.of("payload2"); assertNotNull(pubsub().publish(topic, message1, message2)); Iterator receivedMessages = pubsub().pull(subscription, 2); - pubsub() - .nackAsync(subscription, receivedMessages.next().ackId(), receivedMessages.next().ackId()) + pubsub().nackAsync(subscription, receivedMessages.next().getAckId(), + receivedMessages.next().getAckId()) .get(); receivedMessages = pubsub().pull(subscription, 2); - pubsub() - .ackAsync(subscription, receivedMessages.next().ackId(), receivedMessages.next().ackId()) + pubsub().ackAsync(subscription, receivedMessages.next().getAckId(), + receivedMessages.next().getAckId()) .get(); assertFalse(pubsub().pull(subscription, 2).hasNext()); assertTrue(pubsub().deleteSubscription(subscription)); @@ -781,10 +786,10 @@ public void testAckAndNackMessageList() throws ExecutionException, InterruptedEx assertNotNull(pubsub().publish(topic, ImmutableList.of(message1, message2))); Iterator receivedMessages = pubsub().pull(subscription, 2); pubsub().nack(subscription, - ImmutableList.of(receivedMessages.next().ackId(), receivedMessages.next().ackId())); + ImmutableList.of(receivedMessages.next().getAckId(), receivedMessages.next().getAckId())); receivedMessages = pubsub().pull(subscription, 2); pubsub().ack(subscription, - ImmutableList.of(receivedMessages.next().ackId(), receivedMessages.next().ackId())); + ImmutableList.of(receivedMessages.next().getAckId(), receivedMessages.next().getAckId())); assertFalse(pubsub().pull(subscription, 2).hasNext()); assertTrue(pubsub().deleteSubscription(subscription)); assertTrue(pubsub().deleteTopic(topic)); @@ -800,11 +805,11 @@ public void testAckAndNackMessageListAsync() throws ExecutionException, Interrup Message message2 = Message.of("payload2"); assertNotNull(pubsub().publish(topic, ImmutableList.of(message1, message2))); Iterator receivedMessages = pubsub().pull(subscription, 2); - pubsub().nackAsync(subscription, - ImmutableList.of(receivedMessages.next().ackId(), receivedMessages.next().ackId())).get(); + pubsub().nackAsync(subscription, ImmutableList.of(receivedMessages.next().getAckId(), + receivedMessages.next().getAckId())).get(); receivedMessages = pubsub().pull(subscription, 2); - pubsub().ackAsync(subscription, - ImmutableList.of(receivedMessages.next().ackId(), receivedMessages.next().ackId())).get(); + pubsub().ackAsync(subscription, ImmutableList.of(receivedMessages.next().getAckId(), + receivedMessages.next().getAckId())).get(); assertFalse(pubsub().pull(subscription, 2).hasNext()); assertTrue(pubsub().deleteSubscription(subscription)); assertTrue(pubsub().deleteTopic(topic)); diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/LocalSystemTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/LocalSystemTest.java index 6e596e314c7d..60fd17342b56 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/LocalSystemTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/LocalSystemTest.java @@ -42,7 +42,7 @@ protected String formatForTest(String resourceName) { public static void startServer() throws IOException, InterruptedException { pubsubHelper = LocalPubsubHelper.create(); pubsubHelper.start(); - pubsub = pubsubHelper.options().service(); + pubsub = pubsubHelper.getOptions().service(); } @AfterClass diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/MessageTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/MessageTest.java index c6b177662a9b..ee4fe3055a10 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/MessageTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/MessageTest.java @@ -36,55 +36,94 @@ public class MessageTest { private static final Map ATTRIBUTES = ImmutableMap.of("key1", "value1", "key2", "value2"); private static final Long PUBLISH_TIME = 42L; - private static final Message MESSAGE_STRING = Message.builder(PAYLOAD_STRING) - .id(MESSAGE_ID) + private static final Message MESSAGE_STRING = Message.newBuilder(PAYLOAD_STRING) + .setId(MESSAGE_ID) + .setAttributes(ATTRIBUTES) + .setPublishTime(PUBLISH_TIME) + .build(); + private static final Message MESSAGE = Message.newBuilder(PAYLOAD) + .setId(MESSAGE_ID) + .setAttributes(ATTRIBUTES) + .setPublishTime(PUBLISH_TIME) + .build(); + private static final Message DEPRECATED_MESSAGE_STRING = Message.builder(PAYLOAD_STRING) + .setId(MESSAGE_ID) .attributes(ATTRIBUTES) - .publishTime(PUBLISH_TIME) + .setPublishTime(PUBLISH_TIME) .build(); - private static final Message MESSAGE = Message.builder(PAYLOAD) - .id(MESSAGE_ID) + private static final Message DEPRECATED_MESSAGE = Message.builder(PAYLOAD) + .setId(MESSAGE_ID) .attributes(ATTRIBUTES) - .publishTime(PUBLISH_TIME) + .setPublishTime(PUBLISH_TIME) .build(); @Test public void testToBuilder() { compareMessage(MESSAGE, MESSAGE.toBuilder().build()); Message message = MESSAGE.toBuilder() - .payload("newPayload") + .setPayload("newPayload") .clearAttributes() .addAttribute("key1", "value1") .build(); - assertEquals("newPayload", message.payloadAsString()); - assertEquals(ImmutableMap.of("key1", "value1"), message.attributes()); + assertEquals("newPayload", message.getPayloadAsString()); + assertEquals(ImmutableMap.of("key1", "value1"), message.getAttributes()); message = message.toBuilder() - .payload(PAYLOAD_STRING) + .setPayload(PAYLOAD_STRING) .removeAttribute("key1") - .attributes(ATTRIBUTES) + .setAttributes(ATTRIBUTES) .build(); compareMessage(MESSAGE, message); } @Test public void testBuilder() { - assertEquals(MESSAGE_ID, MESSAGE.id()); - assertEquals(PAYLOAD, MESSAGE.payload()); - assertEquals(PAYLOAD_STRING, MESSAGE.payloadAsString()); - assertEquals(ATTRIBUTES, MESSAGE.attributes()); - assertEquals(PUBLISH_TIME, MESSAGE.publishTime()); - assertEquals(MESSAGE_ID, MESSAGE_STRING.id()); - assertEquals(PAYLOAD, MESSAGE_STRING.payload()); - assertEquals(PAYLOAD_STRING, MESSAGE_STRING.payloadAsString()); - assertEquals(ATTRIBUTES, MESSAGE_STRING.attributes()); - assertEquals(PUBLISH_TIME, MESSAGE_STRING.publishTime()); + assertEquals(MESSAGE_ID, MESSAGE.getId()); + assertEquals(PAYLOAD, MESSAGE.getPayload()); + assertEquals(PAYLOAD_STRING, MESSAGE.getPayloadAsString()); + assertEquals(ATTRIBUTES, MESSAGE.getAttributes()); + assertEquals(PUBLISH_TIME, MESSAGE.getPublishTime()); + assertEquals(MESSAGE_ID, MESSAGE_STRING.getId()); + assertEquals(PAYLOAD, MESSAGE_STRING.getPayload()); + assertEquals(PAYLOAD_STRING, MESSAGE_STRING.getPayloadAsString()); + assertEquals(ATTRIBUTES, MESSAGE_STRING.getAttributes()); + assertEquals(PUBLISH_TIME, MESSAGE_STRING.getPublishTime()); compareMessage(MESSAGE, MESSAGE_STRING); + Message message = Message.newBuilder(PAYLOAD) + .setId(MESSAGE_ID) + .setAttributes(ATTRIBUTES) + .clearAttributes() + .addAttribute("key1", "value1") + .addAttribute("key2", "value2") + .setPublishTime(PUBLISH_TIME) + .build(); + assertEquals(MESSAGE_ID, message.getId()); + assertEquals(PAYLOAD, message.getPayload()); + assertEquals(PAYLOAD_STRING, message.getPayloadAsString()); + assertEquals(ATTRIBUTES, message.getAttributes()); + assertEquals(PUBLISH_TIME, message.getPublishTime()); + compareMessage(MESSAGE, message); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(MESSAGE_ID, DEPRECATED_MESSAGE.id()); + assertEquals(PAYLOAD, DEPRECATED_MESSAGE.payload()); + assertEquals(PAYLOAD_STRING, DEPRECATED_MESSAGE.payloadAsString()); + assertEquals(ATTRIBUTES, DEPRECATED_MESSAGE.attributes()); + assertEquals(PUBLISH_TIME, DEPRECATED_MESSAGE.publishTime()); + assertEquals(MESSAGE_ID, DEPRECATED_MESSAGE_STRING.id()); + assertEquals(PAYLOAD, DEPRECATED_MESSAGE_STRING.payload()); + assertEquals(PAYLOAD_STRING, DEPRECATED_MESSAGE_STRING.payloadAsString()); + assertEquals(ATTRIBUTES, DEPRECATED_MESSAGE_STRING.attributes()); + assertEquals(PUBLISH_TIME, DEPRECATED_MESSAGE_STRING.publishTime()); + compareMessage(MESSAGE, DEPRECATED_MESSAGE_STRING); Message message = Message.builder(PAYLOAD) - .id(MESSAGE_ID) + .setId(MESSAGE_ID) .attributes(ATTRIBUTES) .clearAttributes() .addAttribute("key1", "value1") .addAttribute("key2", "value2") - .publishTime(PUBLISH_TIME) + .setPublishTime(PUBLISH_TIME) .build(); assertEquals(MESSAGE_ID, message.id()); assertEquals(PAYLOAD, message.payload()); @@ -97,17 +136,17 @@ public void testBuilder() { @Test public void testOf() { Message message1 = Message.of(PAYLOAD_STRING); - assertNull(message1.id()); - assertEquals(PAYLOAD, message1.payload()); - assertEquals(PAYLOAD_STRING, message1.payloadAsString()); - assertEquals(ImmutableMap.of(), message1.attributes()); - assertNull(message1.publishTime()); + assertNull(message1.getId()); + assertEquals(PAYLOAD, message1.getPayload()); + assertEquals(PAYLOAD_STRING, message1.getPayloadAsString()); + assertEquals(ImmutableMap.of(), message1.getAttributes()); + assertNull(message1.getPublishTime()); Message message2 = Message.of(PAYLOAD); - assertNull(message2.id()); - assertEquals(PAYLOAD, message2.payload()); - assertEquals(PAYLOAD_STRING, message2.payloadAsString()); - assertEquals(ImmutableMap.of(), message2.attributes()); - assertNull(message2.publishTime()); + assertNull(message2.getId()); + assertEquals(PAYLOAD, message2.getPayload()); + assertEquals(PAYLOAD_STRING, message2.getPayloadAsString()); + assertEquals(ImmutableMap.of(), message2.getAttributes()); + assertNull(message2.getPublishTime()); compareMessage(message1 ,message2); } @@ -127,11 +166,11 @@ public void testToAndFromPbIncomplete() { private void compareMessage(Message expected, Message value) { assertEquals(expected, value); - assertEquals(expected.id(), value.id()); - assertEquals(expected.payload(), value.payload()); - assertEquals(expected.payloadAsString(), value.payloadAsString()); - assertEquals(expected.attributes(), value.attributes()); - assertEquals(expected.publishTime(), value.publishTime()); + assertEquals(expected.getId(), value.getId()); + assertEquals(expected.getPayload(), value.getPayload()); + assertEquals(expected.getPayloadAsString(), value.getPayloadAsString()); + assertEquals(expected.getAttributes(), value.getAttributes()); + assertEquals(expected.getPublishTime(), value.getPublishTime()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/OptionTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/OptionTest.java index 119e64e24c3a..8e4230198d2a 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/OptionTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/OptionTest.java @@ -55,11 +55,11 @@ public void testHashCode() { @Test public void testConstructor() { - assertEquals(OPTION_TYPE, OPTION.optionType()); - assertEquals(VALUE, OPTION.value()); + assertEquals(OPTION_TYPE, OPTION.getOptionType()); + assertEquals(VALUE, OPTION.getValue()); Option option = new Option(OPTION_TYPE, null) {}; - assertEquals(OPTION_TYPE, option.optionType()); - assertNull(option.value()); + assertEquals(OPTION_TYPE, option.getOptionType()); + assertNull(option.getValue()); thrown.expect(NullPointerException.class); new Option(null, VALUE) {}; } diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PubSubImplTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PubSubImplTest.java index b46379cc402a..dbf93c210bb0 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PubSubImplTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PubSubImplTest.java @@ -106,14 +106,14 @@ public com.google.pubsub.v1.Topic apply(TopicInfo topicInfo) { private static final String SUBSCRIPTION_NAME_PB = "projects/project/subscriptions/subscription"; private static final PushConfig PUSH_CONFIG = PushConfig.of("endpoint"); private static final SubscriptionInfo SUBSCRIPTION_INFO = - SubscriptionInfo.builder(TOPIC, SUBSCRIPTION) - .ackDeadLineSeconds(42) - .pushConfig(PUSH_CONFIG) + SubscriptionInfo.newBuilder(TOPIC, SUBSCRIPTION) + .setAckDeadLineSeconds(42) + .setPushConfig(PUSH_CONFIG) .build(); private static final SubscriptionInfo COMPLETE_SUBSCRIPTION_INFO = - SubscriptionInfo.builder(TopicId.of(PROJECT, TOPIC), SUBSCRIPTION) - .ackDeadLineSeconds(42) - .pushConfig(PUSH_CONFIG) + SubscriptionInfo.newBuilder(TopicId.of(PROJECT, TOPIC), SUBSCRIPTION) + .setAckDeadLineSeconds(42) + .setPushConfig(PUSH_CONFIG) .build(); private static final Message MESSAGE1 = Message.of("payload1"); private static final com.google.pubsub.v1.ReceivedMessage MESSAGE_PB1 = @@ -143,7 +143,8 @@ public com.google.pubsub.v1.Subscription apply(SubscriptionInfo subscriptionInfo new Function() { @Override public String apply(SubscriptionId subscriptionId) { - return formatSubscriptionName(subscriptionId.project(), subscriptionId.subscription()); + return formatSubscriptionName(subscriptionId.getProject(), + subscriptionId.getSubscription()); } }; private static final MessageProcessor DO_NOTHING = new MessageProcessor() { @@ -1285,7 +1286,7 @@ public void testPullMessages() throws ExecutionException, InterruptedException { callback.getValue().success(response); EasyMock.reset(renewerMock); for (ReceivedMessage message : messageList) { - renewerMock.remove(SUBSCRIPTION, message.ackId()); + renewerMock.remove(SUBSCRIPTION, message.getAckId()); EasyMock.expectLastCall(); } EasyMock.replay(renewerMock); @@ -1322,7 +1323,7 @@ public void testPullMessagesAsync() throws ExecutionException, InterruptedExcept callback.getValue().success(response); EasyMock.reset(renewerMock); for (ReceivedMessage message : messageList) { - renewerMock.remove(SUBSCRIPTION, message.ackId()); + renewerMock.remove(SUBSCRIPTION, message.getAckId()); EasyMock.expectLastCall(); } EasyMock.replay(renewerMock); diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PubSubTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PubSubTest.java index f99cfa2f728e..78322f4eed95 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PubSubTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PubSubTest.java @@ -36,12 +36,12 @@ public class PubSubTest { public void testListOption() { // page token ListOption listOption = ListOption.pageToken(PAGE_TOKEN); - assertEquals(PAGE_TOKEN, listOption.value()); - assertEquals(ListOption.OptionType.PAGE_TOKEN, listOption.optionType()); + assertEquals(PAGE_TOKEN, listOption.getValue()); + assertEquals(ListOption.OptionType.PAGE_TOKEN, listOption.getOptionType()); // page size listOption = ListOption.pageSize(PAGE_SIZE); - assertEquals(PAGE_SIZE, listOption.value()); - assertEquals(ListOption.OptionType.PAGE_SIZE, listOption.optionType()); + assertEquals(PAGE_SIZE, listOption.getValue()); + assertEquals(ListOption.OptionType.PAGE_SIZE, listOption.getOptionType()); } @Test @@ -49,11 +49,11 @@ public void testListOption() { public void testPullOptions() { // max queued callbacks PullOption pullOption = PullOption.maxQueuedCallbacks(MAX_QUEUED_CALLBACKS); - assertEquals(MAX_QUEUED_CALLBACKS, pullOption.value()); - assertEquals(PullOption.OptionType.MAX_QUEUED_CALLBACKS, pullOption.optionType()); + assertEquals(MAX_QUEUED_CALLBACKS, pullOption.getValue()); + assertEquals(PullOption.OptionType.MAX_QUEUED_CALLBACKS, pullOption.getOptionType()); ExecutorFactory executorFactory = EasyMock.createStrictMock(ExecutorFactory.class); pullOption = PullOption.executorFactory(executorFactory); - assertSame(executorFactory, pullOption.value()); - assertEquals(PullOption.OptionType.EXECUTOR_FACTORY, pullOption.optionType()); + assertSame(executorFactory, pullOption.getValue()); + assertEquals(PullOption.OptionType.EXECUTOR_FACTORY, pullOption.getOptionType()); } } diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PushConfigTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PushConfigTest.java index 496c10d04938..baf8ea4d3535 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PushConfigTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PushConfigTest.java @@ -29,30 +29,32 @@ public class PushConfigTest { private static final String ENDPOINT = "https://example.com/push"; private static final Map ATTRIBUTES = ImmutableMap.of("key1", "value1", "key2", "value2"); - private static final PushConfig PUSH_CONFIG = PushConfig.builder(ENDPOINT, ATTRIBUTES).build(); + private static final PushConfig PUSH_CONFIG = PushConfig.newBuilder(ENDPOINT, ATTRIBUTES).build(); + private static final PushConfig DEPRECATED_PUSH_CONFIG = + PushConfig.builder(ENDPOINT, ATTRIBUTES).build(); @Test public void testToBuilder() { comparePushConfig(PUSH_CONFIG, PUSH_CONFIG.toBuilder().build()); PushConfig pushConfig = PUSH_CONFIG.toBuilder() - .endpoint("https://example2.com/push") + .setEndpoint("https://example2.com/push") .clearAttributes() .addAttribute("key1", "value1") .build(); - assertEquals("https://example2.com/push", pushConfig.endpoint()); - assertEquals(ImmutableMap.of("key1", "value1"), pushConfig.attributes()); + assertEquals("https://example2.com/push", pushConfig.getEndpoint()); + assertEquals(ImmutableMap.of("key1", "value1"), pushConfig.getAttributes()); pushConfig = pushConfig.toBuilder() - .endpoint(ENDPOINT) + .setEndpoint(ENDPOINT) .removeAttribute("key1") - .attributes(ATTRIBUTES) + .setAttributes(ATTRIBUTES) .build(); comparePushConfig(PUSH_CONFIG, pushConfig); } @Test public void testBuilder() { - assertEquals(ENDPOINT, PUSH_CONFIG.endpoint()); - assertEquals(ATTRIBUTES, PUSH_CONFIG.attributes()); + assertEquals(ENDPOINT, DEPRECATED_PUSH_CONFIG.endpoint()); + assertEquals(ATTRIBUTES, DEPRECATED_PUSH_CONFIG.attributes()); PushConfig pushConfig = PushConfig.builder("https://example2.com/push") .endpoint(ENDPOINT) .attributes(ATTRIBUTES) @@ -65,14 +67,30 @@ public void testBuilder() { comparePushConfig(PUSH_CONFIG, pushConfig); } + @Test + public void testBuilderDeprecated() { + assertEquals(ENDPOINT, PUSH_CONFIG.getEndpoint()); + assertEquals(ATTRIBUTES, PUSH_CONFIG.getAttributes()); + PushConfig pushConfig = PushConfig.newBuilder("https://example2.com/push") + .setEndpoint(ENDPOINT) + .setAttributes(ATTRIBUTES) + .clearAttributes() + .addAttribute("key1", "value1") + .addAttribute("key2", "value2") + .build(); + assertEquals(ENDPOINT, pushConfig.getEndpoint()); + assertEquals(ATTRIBUTES, pushConfig.getAttributes()); + comparePushConfig(PUSH_CONFIG, pushConfig); + } + @Test public void testOf() { PushConfig pushConfig = PushConfig.of(ENDPOINT); - assertEquals(ENDPOINT, pushConfig.endpoint()); - assertEquals(ImmutableMap.of(), pushConfig.attributes()); + assertEquals(ENDPOINT, pushConfig.getEndpoint()); + assertEquals(ImmutableMap.of(), pushConfig.getAttributes()); pushConfig = PushConfig.of(ENDPOINT, ATTRIBUTES); - assertEquals(ENDPOINT, pushConfig.endpoint()); - assertEquals(ATTRIBUTES, pushConfig.attributes()); + assertEquals(ENDPOINT, pushConfig.getEndpoint()); + assertEquals(ATTRIBUTES, pushConfig.getAttributes()); comparePushConfig(PUSH_CONFIG, pushConfig); } @@ -89,8 +107,8 @@ public void testToAndFromPbIncomplete() { private void comparePushConfig(PushConfig expected, PushConfig value) { assertEquals(expected, value); - assertEquals(expected.endpoint(), value.endpoint()); - assertEquals(expected.attributes(), value.attributes()); + assertEquals(expected.getEndpoint(), value.getEndpoint()); + assertEquals(expected.getAttributes(), value.getAttributes()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/ReceivedMessageTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/ReceivedMessageTest.java index f21fbd106674..dd2bd636d088 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/ReceivedMessageTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/ReceivedMessageTest.java @@ -51,10 +51,10 @@ public class ReceivedMessageTest { private static final Map ATTRIBUTES = ImmutableMap.of("key1", "value1", "key2", "value2"); private static final Long PUBLISH_TIME = 42L; - private static final Message MESSAGE = Message.builder(PAYLOAD) - .id(MESSAGE_ID) - .attributes(ATTRIBUTES) - .publishTime(PUBLISH_TIME) + private static final Message MESSAGE = Message.newBuilder(PAYLOAD) + .setId(MESSAGE_ID) + .setAttributes(ATTRIBUTES) + .setPublishTime(PUBLISH_TIME) .build(); private static final com.google.pubsub.v1.ReceivedMessage RECEIVED_MESSAGE_PB = com.google.pubsub.v1.ReceivedMessage.newBuilder() @@ -87,14 +87,50 @@ public void tearDown() throws Exception { @Test public void testBuilder() { + initializeExpectedMessage(3); + replay(pubsub); + Map attributes = ImmutableMap.of("newKey1", "newVal1"); + ReceivedMessage builtMessage = expectedMessage.toBuilder() + .setPayload("newPayload") + .setId("newMessageId") + .setAttributes(attributes) + .setPublishTime(PUBLISH_TIME + 1) + .build(); + assertSame(serviceMockReturnsOptions, builtMessage.getPubsub()); + assertEquals(SUBSCRIPTION, builtMessage.getSubscription()); + assertEquals(ACK_ID, builtMessage.getAckId()); + assertEquals("newMessageId", builtMessage.getId()); + assertArrayEquals("newPayload".getBytes(Charsets.UTF_8), builtMessage.getPayload().toByteArray()); + assertEquals("newPayload", builtMessage.getPayloadAsString()); + assertEquals(attributes, builtMessage.getAttributes()); + assertEquals(PUBLISH_TIME + 1, (long) builtMessage.getPublishTime()); + builtMessage = builtMessage.toBuilder() + .setPayload(PAYLOAD) + .setId(MESSAGE_ID) + .clearAttributes() + .addAttribute("key1", "value1") + .addAttribute("key2", "value2") + .setPublishTime(PUBLISH_TIME) + .build(); + assertSame(serviceMockReturnsOptions, builtMessage.getPubsub()); + assertEquals(MESSAGE_ID, builtMessage.getId()); + assertEquals(PAYLOAD, builtMessage.getPayload()); + assertEquals(PAYLOAD_STRING, builtMessage.getPayloadAsString()); + assertEquals(ATTRIBUTES, builtMessage.getAttributes()); + assertEquals(PUBLISH_TIME, builtMessage.getPublishTime()); + compareReceivedMessage(expectedMessage, builtMessage); + } + + @Test + public void testBuilderDeprecated() { initializeExpectedMessage(3); replay(pubsub); Map attributes = ImmutableMap.of("newKey1", "newVal1"); ReceivedMessage builtMessage = expectedMessage.toBuilder() .payload("newPayload") - .id("newMessageId") + .setId("newMessageId") .attributes(attributes) - .publishTime(PUBLISH_TIME + 1) + .setPublishTime(PUBLISH_TIME + 1) .build(); assertSame(serviceMockReturnsOptions, builtMessage.pubsub()); assertEquals(SUBSCRIPTION, builtMessage.subscription()); @@ -106,11 +142,11 @@ public void testBuilder() { assertEquals(PUBLISH_TIME + 1, (long) builtMessage.publishTime()); builtMessage = builtMessage.toBuilder() .payload(PAYLOAD) - .id(MESSAGE_ID) + .setId(MESSAGE_ID) .clearAttributes() .addAttribute("key1", "value1") .addAttribute("key2", "value2") - .publishTime(PUBLISH_TIME) + .setPublishTime(PUBLISH_TIME) .build(); assertSame(serviceMockReturnsOptions, builtMessage.pubsub()); assertEquals(MESSAGE_ID, builtMessage.id()); @@ -175,13 +211,13 @@ public void testModifyAckDeadlineAsync() throws ExecutionException, InterruptedE private void compareReceivedMessage(ReceivedMessage expected, ReceivedMessage value) { assertEquals(expected, value); - assertEquals(expected.id(), value.id()); - assertEquals(expected.payload(), value.payload()); - assertEquals(expected.payloadAsString(), value.payloadAsString()); - assertEquals(expected.attributes(), value.attributes()); - assertEquals(expected.publishTime(), value.publishTime()); - assertEquals(expected.ackId(), value.ackId()); - assertEquals(expected.subscription(), value.subscription()); + assertEquals(expected.getId(), value.getId()); + assertEquals(expected.getPayload(), value.getPayload()); + assertEquals(expected.getPayloadAsString(), value.getPayloadAsString()); + assertEquals(expected.getAttributes(), value.getAttributes()); + assertEquals(expected.getPublishTime(), value.getPublishTime()); + assertEquals(expected.getAckId(), value.getAckId()); + assertEquals(expected.getSubscription(), value.getSubscription()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionIdTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionIdTest.java index ef7e4a8cd8dd..578794663b74 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionIdTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionIdTest.java @@ -29,6 +29,12 @@ public class SubscriptionIdTest { @Test public void testConstructor() { + assertEquals(PROJECT, SUBSCRIPTION_ID.getProject()); + assertEquals(NAME, SUBSCRIPTION_ID.getSubscription()); + } + + @Test + public void testConstructorDeprecated() { assertEquals(PROJECT, SUBSCRIPTION_ID.project()); assertEquals(NAME, SUBSCRIPTION_ID.subscription()); } @@ -37,14 +43,14 @@ public void testConstructor() { public void testToAndFromPb() { SubscriptionId subscriptionId = SubscriptionId.fromPb(TOPIC_PB); compareSubscriptionId(SUBSCRIPTION_ID, subscriptionId); - assertEquals(PROJECT, subscriptionId.project()); - assertEquals(NAME, subscriptionId.subscription()); + assertEquals(PROJECT, subscriptionId.getProject()); + assertEquals(NAME, subscriptionId.getSubscription()); } private void compareSubscriptionId(SubscriptionId expected, SubscriptionId value) { assertEquals(expected, value); - assertEquals(expected.project(), value.project()); - assertEquals(expected.subscription(), value.subscription()); + assertEquals(expected.getProject(), value.getProject()); + assertEquals(expected.getSubscription(), value.getSubscription()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionInfoTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionInfoTest.java index 36846f06f26a..d17f29e78dbf 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionInfoTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionInfoTest.java @@ -28,30 +28,61 @@ public class SubscriptionInfoTest { private static final String ENDPOINT = "https://example.com/push"; private static final PushConfig PUSH_CONFIG = PushConfig.of(ENDPOINT); private static final int ACK_DEADLINE = 42; - private static final SubscriptionInfo SUBSCRIPTION_INFO = SubscriptionInfo.builder(TOPIC, NAME) - .pushConfig(PUSH_CONFIG) - .ackDeadLineSeconds(ACK_DEADLINE) + private static final SubscriptionInfo SUBSCRIPTION_INFO = SubscriptionInfo.newBuilder(TOPIC, NAME) + .setPushConfig(PUSH_CONFIG) + .setAckDeadLineSeconds(ACK_DEADLINE) .build(); + private static final SubscriptionInfo DEPRECATED_SUBSCRIPTION_INFO = + SubscriptionInfo.builder(TOPIC, NAME) + .pushConfig(PUSH_CONFIG) + .ackDeadLineSeconds(ACK_DEADLINE) + .build(); @Test public void testToBuilder() { compareSubscriptionInfo(SUBSCRIPTION_INFO, SUBSCRIPTION_INFO.toBuilder().build()); SubscriptionInfo subscriptionInfo = SUBSCRIPTION_INFO.toBuilder() - .topic("newTopic") - .name("newSubscription") + .setTopic("newTopic") + .setName("newSubscription") .build(); - assertEquals(TopicId.of("newTopic"), subscriptionInfo.topic()); - assertEquals("newSubscription", subscriptionInfo.name()); - subscriptionInfo = subscriptionInfo.toBuilder().name(NAME).topic(TOPIC).build(); + assertEquals(TopicId.of("newTopic"), subscriptionInfo.getTopic()); + assertEquals("newSubscription", subscriptionInfo.getName()); + subscriptionInfo = subscriptionInfo.toBuilder().setName(NAME).setTopic(TOPIC).build(); compareSubscriptionInfo(SUBSCRIPTION_INFO, subscriptionInfo); } @Test public void testBuilder() { - assertEquals(TOPIC, SUBSCRIPTION_INFO.topic()); - assertEquals(NAME, SUBSCRIPTION_INFO.name()); - assertEquals(PUSH_CONFIG, SUBSCRIPTION_INFO.pushConfig()); - assertEquals(ACK_DEADLINE, SUBSCRIPTION_INFO.ackDeadlineSeconds()); + assertEquals(TOPIC, SUBSCRIPTION_INFO.getTopic()); + assertEquals(NAME, SUBSCRIPTION_INFO.getName()); + assertEquals(PUSH_CONFIG, SUBSCRIPTION_INFO.getPushConfig()); + assertEquals(ACK_DEADLINE, SUBSCRIPTION_INFO.getAckDeadlineSeconds()); + SubscriptionInfo subscriptionInfo = + SubscriptionInfo.newBuilder("topic", "subscription").build(); + assertEquals(TopicId.of("topic"), subscriptionInfo.getTopic()); + assertEquals(NAME, subscriptionInfo.getName()); + assertNull(subscriptionInfo.getPushConfig()); + assertEquals(0, subscriptionInfo.getAckDeadlineSeconds()); + subscriptionInfo = SubscriptionInfo.newBuilder("topic", "subscription") + .setTopic("project", "topic").build(); + assertEquals(TOPIC, subscriptionInfo.getTopic()); + assertEquals(NAME, subscriptionInfo.getName()); + assertNull(subscriptionInfo.getPushConfig()); + assertEquals(0, subscriptionInfo.getAckDeadlineSeconds()); + subscriptionInfo = SubscriptionInfo.newBuilder("topic", "subscription") + .setTopic(TOPIC).build(); + assertEquals(TOPIC, subscriptionInfo.getTopic()); + assertEquals(NAME, subscriptionInfo.getName()); + assertNull(subscriptionInfo.getPushConfig()); + assertEquals(0, subscriptionInfo.getAckDeadlineSeconds()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(TOPIC, DEPRECATED_SUBSCRIPTION_INFO.topic()); + assertEquals(NAME, DEPRECATED_SUBSCRIPTION_INFO.name()); + assertEquals(PUSH_CONFIG, DEPRECATED_SUBSCRIPTION_INFO.pushConfig()); + assertEquals(ACK_DEADLINE, DEPRECATED_SUBSCRIPTION_INFO.ackDeadlineSeconds()); SubscriptionInfo subscriptionInfo = SubscriptionInfo.builder("topic", "subscription").build(); assertEquals(TopicId.of("topic"), subscriptionInfo.topic()); assertEquals(NAME, subscriptionInfo.name()); @@ -74,25 +105,25 @@ public void testBuilder() { @Test public void testOf() { SubscriptionInfo subscriptionInfo = SubscriptionInfo.of(TOPIC, NAME); - assertEquals(TOPIC, subscriptionInfo.topic()); - assertEquals(NAME, subscriptionInfo.name()); - assertNull(subscriptionInfo.pushConfig()); - assertEquals(0, subscriptionInfo.ackDeadlineSeconds()); + assertEquals(TOPIC, subscriptionInfo.getTopic()); + assertEquals(NAME, subscriptionInfo.getName()); + assertNull(subscriptionInfo.getPushConfig()); + assertEquals(0, subscriptionInfo.getAckDeadlineSeconds()); subscriptionInfo = SubscriptionInfo.of("topic", NAME); - assertEquals(TopicId.of("topic"), subscriptionInfo.topic()); - assertEquals(NAME, subscriptionInfo.name()); - assertNull(subscriptionInfo.pushConfig()); - assertEquals(0, subscriptionInfo.ackDeadlineSeconds()); + assertEquals(TopicId.of("topic"), subscriptionInfo.getTopic()); + assertEquals(NAME, subscriptionInfo.getName()); + assertNull(subscriptionInfo.getPushConfig()); + assertEquals(0, subscriptionInfo.getAckDeadlineSeconds()); subscriptionInfo = SubscriptionInfo.of(TOPIC, NAME, ENDPOINT); - assertEquals(TOPIC, subscriptionInfo.topic()); - assertEquals(NAME, subscriptionInfo.name()); - assertEquals(PushConfig.of(ENDPOINT), subscriptionInfo.pushConfig()); - assertEquals(0, subscriptionInfo.ackDeadlineSeconds()); + assertEquals(TOPIC, subscriptionInfo.getTopic()); + assertEquals(NAME, subscriptionInfo.getName()); + assertEquals(PushConfig.of(ENDPOINT), subscriptionInfo.getPushConfig()); + assertEquals(0, subscriptionInfo.getAckDeadlineSeconds()); subscriptionInfo = SubscriptionInfo.of("topic", NAME, ENDPOINT); - assertEquals(TopicId.of("topic"), subscriptionInfo.topic()); - assertEquals(NAME, subscriptionInfo.name()); - assertEquals(PushConfig.of(ENDPOINT), subscriptionInfo.pushConfig()); - assertEquals(0, subscriptionInfo.ackDeadlineSeconds()); + assertEquals(TopicId.of("topic"), subscriptionInfo.getTopic()); + assertEquals(NAME, subscriptionInfo.getName()); + assertEquals(PushConfig.of(ENDPOINT), subscriptionInfo.getPushConfig()); + assertEquals(0, subscriptionInfo.getAckDeadlineSeconds()); } @Test @@ -114,18 +145,18 @@ public void testToAndFromPb() { com.google.pubsub.v1.Subscription subscription = SUBSCRIPTION_INFO.toPb("project"); subscriptionInfo = SubscriptionInfo.fromPb(subscription.toBuilder().setTopic("_deleted-topic_").build()); - assertEquals(TopicId.deletedTopic(), subscriptionInfo.topic()); - assertEquals(NAME, subscriptionInfo.name()); - assertEquals(PUSH_CONFIG, subscriptionInfo.pushConfig()); - assertEquals(ACK_DEADLINE, subscriptionInfo.ackDeadlineSeconds()); + assertEquals(TopicId.deletedTopic(), subscriptionInfo.getTopic()); + assertEquals(NAME, subscriptionInfo.getName()); + assertEquals(PUSH_CONFIG, subscriptionInfo.getPushConfig()); + assertEquals(ACK_DEADLINE, subscriptionInfo.getAckDeadlineSeconds()); } private void compareSubscriptionInfo(SubscriptionInfo expected, SubscriptionInfo value) { assertEquals(expected, value); - assertEquals(expected.topic(), value.topic()); - assertEquals(expected.name(), value.name()); - assertEquals(expected.pushConfig(), value.pushConfig()); - assertEquals(expected.ackDeadlineSeconds(), value.ackDeadlineSeconds()); + assertEquals(expected.getTopic(), value.getTopic()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getPushConfig(), value.getPushConfig()); + assertEquals(expected.getAckDeadlineSeconds(), value.getAckDeadlineSeconds()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionTest.java index 7d0dbb1529c2..6baffd5826c8 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionTest.java @@ -51,10 +51,11 @@ public class SubscriptionTest { private static final String ENDPOINT = "https://example.com/push"; private static final PushConfig PUSH_CONFIG = PushConfig.of(ENDPOINT); private static final int ACK_DEADLINE = 42; - private static final SubscriptionInfo SUBSCRIPTION_INFO =SubscriptionInfo.builder(TOPIC_ID, NAME) - .pushConfig(PUSH_CONFIG) - .ackDeadLineSeconds(ACK_DEADLINE) - .build(); + private static final SubscriptionInfo SUBSCRIPTION_INFO = + SubscriptionInfo.newBuilder(TOPIC_ID, NAME) + .setPushConfig(PUSH_CONFIG) + .setAckDeadLineSeconds(ACK_DEADLINE) + .build(); private static final Message MESSAGE1 = Message.of("payload1"); private static final com.google.pubsub.v1.ReceivedMessage MESSAGE_PB1 = com.google.pubsub.v1.ReceivedMessage.newBuilder() @@ -96,12 +97,34 @@ public void tearDown() throws Exception { @Test public void testBuilder() { + initializeExpectedSubscription(2); + replay(pubsub); + assertEquals(TOPIC_ID, expectedSubscription.getTopic()); + assertEquals(NAME, expectedSubscription.getName()); + assertEquals(PUSH_CONFIG, expectedSubscription.getPushConfig()); + assertEquals(ACK_DEADLINE, expectedSubscription.getAckDeadlineSeconds()); + assertSame(serviceMockReturnsOptions, expectedSubscription.getPubsub()); + Subscription builtSubscription = expectedSubscription.toBuilder() + .setName("newSubscription") + .setTopic("newProject", "newTopic") + .setPushConfig(null) + .setAckDeadLineSeconds(10) + .build(); + assertEquals(TopicId.of("newProject", "newTopic"), builtSubscription.getTopic()); + assertEquals("newSubscription", builtSubscription.getName()); + assertEquals(null, builtSubscription.getPushConfig()); + assertEquals(10, builtSubscription.getAckDeadlineSeconds()); + } + + @Test + public void testBuilderDeprecated() { initializeExpectedSubscription(2); replay(pubsub); assertEquals(TOPIC_ID, expectedSubscription.topic()); assertEquals(NAME, expectedSubscription.name()); assertEquals(PUSH_CONFIG, expectedSubscription.pushConfig()); assertEquals(ACK_DEADLINE, expectedSubscription.ackDeadlineSeconds()); + assertSame(serviceMockReturnsOptions, expectedSubscription.pubSub()); Subscription builtSubscription = expectedSubscription.toBuilder() .name("newSubscription") .topic("newProject", "newTopic") @@ -124,7 +147,7 @@ public void testToBuilder() { @Test public void testReload() { initializeExpectedSubscription(2); - SubscriptionInfo updatedInfo = SUBSCRIPTION_INFO.toBuilder().name("newSubscription").build(); + SubscriptionInfo updatedInfo = SUBSCRIPTION_INFO.toBuilder().setName("newSubscription").build(); Subscription expectedSubscription = new Subscription(serviceMockReturnsOptions, new SubscriptionInfo.BuilderImpl(updatedInfo)); expect(pubsub.options()).andReturn(mockOptions); @@ -148,7 +171,7 @@ public void testReloadNull() { @Test public void testReloadAsync() throws ExecutionException, InterruptedException { initializeExpectedSubscription(2); - SubscriptionInfo updatedInfo = SUBSCRIPTION_INFO.toBuilder().name("newSubscription").build(); + SubscriptionInfo updatedInfo = SUBSCRIPTION_INFO.toBuilder().setName("newSubscription").build(); Subscription expectedSubscription = new Subscription(serviceMockReturnsOptions, new SubscriptionInfo.BuilderImpl(updatedInfo)); expect(pubsub.options()).andReturn(mockOptions); @@ -404,10 +427,10 @@ public void testTestPermissionsAsync() throws ExecutionException, InterruptedExc private void compareSubscription(Subscription expected, Subscription value) { assertEquals(expected, value); - assertEquals(expected.topic(), value.topic()); - assertEquals(expected.name(), value.name()); - assertEquals(expected.pushConfig(), value.pushConfig()); - assertEquals(expected.ackDeadlineSeconds(), value.ackDeadlineSeconds()); + assertEquals(expected.getTopic(), value.getTopic()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getPushConfig(), value.getPushConfig()); + assertEquals(expected.getAckDeadlineSeconds(), value.getAckDeadlineSeconds()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicIdTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicIdTest.java index c8d5da25bc89..72c9fc9c212e 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicIdTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicIdTest.java @@ -33,6 +33,17 @@ public class TopicIdTest { @Test public void testOf() { + TopicId topicId = TopicId.of(PROJECT, NAME); + assertEquals(PROJECT, topicId.getProject()); + assertEquals(NAME, topicId.getTopic()); + topicId = TopicId.of(NAME); + assertNull(topicId.getProject()); + assertEquals(NAME, topicId.getTopic()); + assertFalse(topicId.isDeleted()); + } + + @Test + public void testOfDeprecated() { TopicId topicId = TopicId.of(PROJECT, NAME); assertEquals(PROJECT, topicId.project()); assertEquals(NAME, topicId.topic()); @@ -45,8 +56,8 @@ public void testOf() { @Test public void testDeletedTopic() { TopicId deletedTopic = TopicId.deletedTopic(); - assertNull(deletedTopic.project()); - assertEquals(DELETED_TOPIC_NAME, deletedTopic.topic()); + assertNull(deletedTopic.getProject()); + assertEquals(DELETED_TOPIC_NAME, deletedTopic.getTopic()); assertTrue(deletedTopic.isDeleted()); assertSame(deletedTopic, TopicId.deletedTopic()); } @@ -66,8 +77,8 @@ public void testToAndFromPb() { private void compareTopicId(TopicId expected, TopicId value) { assertEquals(expected, value); - assertEquals(expected.project(), value.project()); - assertEquals(expected.topic(), value.topic()); + assertEquals(expected.getProject(), value.getProject()); + assertEquals(expected.getTopic(), value.getTopic()); assertEquals(expected.isDeleted(), value.isDeleted()); assertEquals(expected.toPb("project"), value.toPb("project")); assertEquals(expected.hashCode(), value.hashCode()); diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicInfoTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicInfoTest.java index 29970833cdef..f89faed499c9 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicInfoTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicInfoTest.java @@ -23,22 +23,30 @@ public class TopicInfoTest { private static final String NAME = "topic"; - private static final TopicInfo TOPIC_INFO = TopicInfo.builder("topic").build(); + private static final TopicInfo TOPIC_INFO = TopicInfo.newBuilder("topic").build(); + private static final TopicInfo DEPRECATED_TOPIC_INFO = TopicInfo.builder("topic").build(); @Test public void testToBuilder() { compareTopicInfo(TOPIC_INFO, TOPIC_INFO.toBuilder().build()); TopicInfo topicInfo = TOPIC_INFO.toBuilder() - .name("newTopic") + .setName("newTopic") .build(); - assertEquals("newTopic", topicInfo.name()); - topicInfo = topicInfo.toBuilder().name(NAME).build(); + assertEquals("newTopic", topicInfo.getName()); + topicInfo = topicInfo.toBuilder().setName(NAME).build(); compareTopicInfo(TOPIC_INFO, topicInfo); } @Test public void testBuilder() { - assertEquals(NAME, TOPIC_INFO.name()); + assertEquals(NAME, TOPIC_INFO.getName()); + TopicInfo topicInfo = TopicInfo.newBuilder("wrongName").setName(NAME).build(); + compareTopicInfo(TOPIC_INFO, topicInfo); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(NAME, DEPRECATED_TOPIC_INFO.name()); TopicInfo topicInfo = TopicInfo.builder("wrongName").name(NAME).build(); compareTopicInfo(TOPIC_INFO, topicInfo); } @@ -56,7 +64,7 @@ public void testToAndFromPb() { private void compareTopicInfo(TopicInfo expected, TopicInfo value) { assertEquals(expected, value); - assertEquals(expected.name(), value.name()); + assertEquals(expected.getName(), value.getName()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicTest.java index be9587a9f98c..0b22a2c0b98e 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicTest.java @@ -24,6 +24,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import com.google.cloud.AsyncPage; @@ -75,10 +76,20 @@ public void tearDown() throws Exception { @Test public void testBuilder() { + initializeExpectedTopic(2); + replay(pubsub); + Topic builtTopic = expectedTopic.toBuilder().setName("newTopic").build(); + assertEquals("newTopic", builtTopic.getName()); + assertSame(serviceMockReturnsOptions, expectedTopic.getPubsub()); + } + + @Test + public void testBuilderDeprecated() { initializeExpectedTopic(2); replay(pubsub); Topic builtTopic = expectedTopic.toBuilder().name("newTopic").build(); assertEquals("newTopic", builtTopic.name()); + assertSame(serviceMockReturnsOptions, expectedTopic.pubSub()); } @Test @@ -91,7 +102,7 @@ public void testToBuilder() { @Test public void testReload() { initializeExpectedTopic(2); - TopicInfo updatedInfo = TOPIC_INFO.toBuilder().name("newTopic").build(); + TopicInfo updatedInfo = TOPIC_INFO.toBuilder().setName("newTopic").build(); Topic expectedTopic = new Topic(serviceMockReturnsOptions, new TopicInfo.BuilderImpl(updatedInfo)); expect(pubsub.options()).andReturn(mockOptions); @@ -115,7 +126,7 @@ public void testReloadNull() { @Test public void testReloadAsync() throws ExecutionException, InterruptedException { initializeExpectedTopic(2); - TopicInfo updatedInfo = TOPIC_INFO.toBuilder().name("newTopic").build(); + TopicInfo updatedInfo = TOPIC_INFO.toBuilder().setName("newTopic").build(); Topic expectedTopic = new Topic(serviceMockReturnsOptions, new TopicInfo.BuilderImpl(updatedInfo)); expect(pubsub.options()).andReturn(mockOptions); @@ -399,7 +410,7 @@ public void testTestPermissionsAsync() throws ExecutionException, InterruptedExc private void compareTopic(Topic expected, Topic value) { assertEquals(expected, value); - assertEquals(expected.name(), value.name()); + assertEquals(expected.getName(), value.getName()); assertEquals(expected.hashCode(), value.hashCode()); } } From 8bf9eab077037ba5d16ab45d92aef9a5fae5c0b8 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Fri, 21 Oct 2016 12:51:16 +0200 Subject: [PATCH 15/32] Rename setters/getters/builders for Logging classes to meet proto conventions (#1313) * Rename setters/getters/builders for Logging classes to meet proto conventions * Update Logging examples, snippets and READMEs to use renamed getters/setters/builders * Make deprecated methods call renamed ones --- README.md | 6 +- TESTING.md | 2 +- .../com/google/cloud/MonitoredResource.java | 52 +++- .../cloud/MonitoredResourceDescriptor.java | 93 +++++- .../MonitoredResourceDescriptorTest.java | 63 +++- .../google/cloud/MonitoredResourceTest.java | 53 +++- .../com/google/cloud/SerializationTest.java | 8 +- .../examples/logging/LoggingExample.java | 16 +- .../snippets/CreateAndListMetrics.java | 4 +- .../logging/snippets/CreateAndListSinks.java | 4 +- .../logging/snippets/LoggingSnippets.java | 24 +- .../logging/snippets/MetricSnippets.java | 4 +- .../logging/snippets/SinkSnippets.java | 4 +- .../snippets/WriteAndListLogEntries.java | 6 +- google-cloud-logging/README.md | 10 +- .../cloud/logging/AsyncLoggingHandler.java | 2 +- .../com/google/cloud/logging/HttpRequest.java | 247 ++++++++++++++- .../com/google/cloud/logging/LogEntry.java | 202 +++++++++++- .../com/google/cloud/logging/Logging.java | 32 +- .../google/cloud/logging/LoggingHandler.java | 16 +- .../com/google/cloud/logging/LoggingImpl.java | 7 +- .../google/cloud/logging/LoggingLevel.java | 8 + .../java/com/google/cloud/logging/Metric.java | 44 ++- .../com/google/cloud/logging/MetricInfo.java | 89 +++++- .../com/google/cloud/logging/Operation.java | 74 ++++- .../java/com/google/cloud/logging/Option.java | 4 +- .../com/google/cloud/logging/Payload.java | 37 ++- .../java/com/google/cloud/logging/Sink.java | 52 +++- .../com/google/cloud/logging/SinkInfo.java | 180 ++++++++++- .../com/google/cloud/logging/Structs.java | 6 +- .../google/cloud/logging/package-info.java | 6 +- .../logging/testing/RemoteLoggingHelper.java | 12 +- .../cloud/logging/testing/package-info.java | 2 +- .../logging/AsyncLoggingHandlerTest.java | 4 +- .../google/cloud/logging/BaseSystemTest.java | 293 +++++++++--------- .../google/cloud/logging/HttpRequestTest.java | 185 ++++++----- .../google/cloud/logging/LogEntryTest.java | 269 ++++++++++------ .../cloud/logging/LoggingHandlerTest.java | 52 ++-- .../google/cloud/logging/LoggingImplTest.java | 18 +- .../cloud/logging/LoggingLevelTest.java | 6 + .../com/google/cloud/logging/LoggingTest.java | 40 +-- .../google/cloud/logging/MetricInfoTest.java | 50 ++- .../com/google/cloud/logging/MetricTest.java | 41 ++- .../google/cloud/logging/OperationTest.java | 50 ++- .../com/google/cloud/logging/OptionTest.java | 16 +- .../com/google/cloud/logging/PayloadTest.java | 19 +- .../cloud/logging/SerializationTest.java | 6 +- .../google/cloud/logging/SinkInfoTest.java | 165 +++++++--- .../com/google/cloud/logging/SinkTest.java | 44 ++- .../com/google/cloud/logging/StructsTest.java | 4 +- .../cloud/logging/it/ITLoggingTest.java | 2 +- 51 files changed, 1955 insertions(+), 678 deletions(-) diff --git a/README.md b/README.md index d85c8ab3bcf4..0230de56ae63 100644 --- a/README.md +++ b/README.md @@ -412,9 +412,9 @@ import java.util.Iterator; LoggingOptions options = LoggingOptions.defaultInstance(); try(Logging logging = options.service()) { - LogEntry firstEntry = LogEntry.builder(StringPayload.of("message")) - .logName("test-log") - .resource(MonitoredResource.builder("global") + LogEntry firstEntry = LogEntry.newBuilder(StringPayload.of("message")) + .setLogName("test-log") + .setResource(MonitoredResource.builder("global") .addLabel("project_id", options.projectId()) .build()) .build(); diff --git a/TESTING.md b/TESTING.md index 606caddda375..cc7dce9f1462 100644 --- a/TESTING.md +++ b/TESTING.md @@ -164,7 +164,7 @@ uses the `RemoteLoggingHelper` to create a metric. ```java RemoteLoggingHelper loggingHelper = RemoteLoggingHelper.create(PROJECT_ID, new FileInputStream("/path/to/my/JSON/key.json")); - Logging logging = loggingHelper.options().service(); + Logging logging = loggingHelper.getOptions().service(); // Pick a name for the resource with low probability of clashing String metricName = RemoteLoggingHelper.formatForTest("test-metric"); MetricInfo metricInfo = MetricInfo.of(name, "logName:syslog"); diff --git a/google-cloud-core/src/main/java/com/google/cloud/MonitoredResource.java b/google-cloud-core/src/main/java/com/google/cloud/MonitoredResource.java index 584bc80ced02..66cd15ce1eec 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/MonitoredResource.java +++ b/google-cloud-core/src/main/java/com/google/cloud/MonitoredResource.java @@ -66,7 +66,17 @@ public static class Builder { * {@link MonitoredResourceDescriptor#type()} of a {@code MonitoredResourceDescriptor} object. * For example, the type {@code cloudsql_database} represent databases in Google Cloud SQL. */ + @Deprecated public Builder type(String type) { + return setType(type); + } + + /** + * Sets the monitored resource type. This value must match the one of + * {@link MonitoredResourceDescriptor#type()} of a {@code MonitoredResourceDescriptor} object. + * For example, the type {@code cloudsql_database} represent databases in Google Cloud SQL. + */ + public Builder setType(String type) { this.type = type; return this; } @@ -76,7 +86,17 @@ public Builder type(String type) { * descriptor (see {@link MonitoredResourceDescriptor#labels()}. For example, Google Compute * Engine VM instances use the labels {@code instance_id} and {@code zone}. */ + @Deprecated public Builder labels(Map labels) { + return setLabels(labels); + } + + /** + * Sets the values for all the labels required by the corresponding monitored resource + * descriptor (see {@link MonitoredResourceDescriptor#labels()}. For example, Google Compute + * Engine VM instances use the labels {@code instance_id} and {@code zone}. + */ + public Builder setLabels(Map labels) { this.labels = new HashMap<>(checkNotNull(labels)); return this; } @@ -112,7 +132,17 @@ public MonitoredResource build() { * {@link MonitoredResourceDescriptor#type()} of a {@code MonitoredResourceDescriptor} object. * For example, the type {@code cloudsql_database} represent databases in Google Cloud SQL. */ + @Deprecated public String type() { + return getType(); + } + + /** + * Returns the monitored resource type. This value must match the one of + * {@link MonitoredResourceDescriptor#type()} of a {@code MonitoredResourceDescriptor} object. + * For example, the type {@code cloudsql_database} represent databases in Google Cloud SQL. + */ + public String getType() { return type; } @@ -121,7 +151,17 @@ public String type() { * descriptor (see {@link MonitoredResourceDescriptor#labels()}. For example, Google Compute * Engine VM instances use the labels {@code instance_id} and {@code zone}. */ + @Deprecated public Map labels() { + return getLabels(); + } + + /** + * Returns the values for all the labels required by the corresponding monitored resource + * descriptor (see {@link MonitoredResourceDescriptor#labels()}. For example, Google Compute + * Engine VM instances use the labels {@code instance_id} and {@code zone}. + */ + public Map getLabels() { return labels; } @@ -167,7 +207,15 @@ public Builder toBuilder() { /** * Returns a builder for {@code MonitoredResource} objects given the resource's type. */ + @Deprecated public static Builder builder(String type) { + return newBuilder(type); + } + + /** + * Returns a builder for {@code MonitoredResource} objects given the resource's type. + */ + public static Builder newBuilder(String type) { return new Builder(type); } @@ -175,10 +223,10 @@ public static Builder builder(String type) { * Creates a {@code MonitoredResource} object given the resource's type and labels. */ public static MonitoredResource of(String type, Map labels) { - return builder(type).labels(labels).build(); + return newBuilder(type).setLabels(labels).build(); } public static MonitoredResource fromPb(com.google.api.MonitoredResource descriptorPb) { - return new Builder(descriptorPb.getType()).labels(descriptorPb.getLabels()).build(); + return new Builder(descriptorPb.getType()).setLabels(descriptorPb.getLabelsMap()).build(); } } diff --git a/google-cloud-core/src/main/java/com/google/cloud/MonitoredResourceDescriptor.java b/google-cloud-core/src/main/java/com/google/cloud/MonitoredResourceDescriptor.java index cb121094ef31..ebee6544df4a 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/MonitoredResourceDescriptor.java +++ b/google-cloud-core/src/main/java/com/google/cloud/MonitoredResourceDescriptor.java @@ -120,14 +120,30 @@ static ValueType fromPb(com.google.api.LabelDescriptor.ValueType typePb) { /** * Returns the key associated to this label. */ + @Deprecated public String key() { + return getKey(); + } + + /** + * Returns the key associated to this label. + */ + public String getKey() { return key; } /** * Returns the type of data that can be assigned to this label. */ + @Deprecated public ValueType valueType() { + return getValueType(); + } + + /** + * Returns the type of data that can be assigned to this label. + */ + public ValueType getValueType() { return valueType; } @@ -135,7 +151,16 @@ public ValueType valueType() { * Returns the optional human-readable description for this label. If not set, this method * returns {@code null}. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns the optional human-readable description for this label. If not set, this method + * returns {@code null}. + */ + public String getDescription() { return description; } @@ -199,22 +224,22 @@ static class Builder { this.type = type; } - Builder name(String name) { + Builder setName(String name) { this.name = name; return this; } - Builder displayName(String displayName) { + Builder setDisplayName(String displayName) { this.displayName = displayName; return this; } - Builder description(String description) { + Builder setDescription(String description) { this.description = description; return this; } - Builder labels(List labels) { + Builder setLabels(List labels) { this.labels = labels; return this; } @@ -236,7 +261,16 @@ MonitoredResourceDescriptor build() { * Returns the monitored resource type. For example, the type {@code cloudsql_database} represents * databases in Google Cloud SQL. */ + @Deprecated public String type() { + return getType(); + } + + /** + * Returns the monitored resource type. For example, the type {@code cloudsql_database} represents + * databases in Google Cloud SQL. + */ + public String getType() { return type; } @@ -244,7 +278,16 @@ public String type() { * Returns an optional name for the monitored resource descriptor. If not set, this method returns * {@code null}. */ + @Deprecated public String name() { + return getName(); + } + + /** + * Returns an optional name for the monitored resource descriptor. If not set, this method returns + * {@code null}. + */ + public String getName() { return name; } @@ -253,7 +296,17 @@ public String name() { * in user interfaces. For example, {@code Google Cloud SQL Database}. If not set, this method * returns {@code null}. */ + @Deprecated public String displayName() { + return getDisplayName(); + } + + /** + * Returns an optional concise name for the monitored resource type. This value might be displayed + * in user interfaces. For example, {@code Google Cloud SQL Database}. If not set, this method + * returns {@code null}. + */ + public String getDisplayName() { return displayName; } @@ -261,7 +314,16 @@ public String displayName() { * Returns an optional detailed description of the monitored resource type. This value might be * used in documentation. If not set, this method returns {@code null}. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns an optional detailed description of the monitored resource type. This value might be + * used in documentation. If not set, this method returns {@code null}. + */ + public String getDescription() { return description; } @@ -270,7 +332,17 @@ public String description() { * example, an individual Google Cloud SQL database is identified by values for the labels * {@code database_id} and {@code region}. */ + @Deprecated public List labels() { + return getLabels(); + } + + /** + * Returns a list of labels used to describe instances of this monitored resource type. For + * example, an individual Google Cloud SQL database is identified by values for the labels + * {@code database_id} and {@code region}. + */ + public List getLabels() { return labels; } @@ -323,23 +395,24 @@ public com.google.api.MonitoredResourceDescriptor toPb() { return builder.build(); } - static Builder builder(String type) { + static Builder newBuilder(String type) { return new Builder(type); } public static MonitoredResourceDescriptor fromPb( com.google.api.MonitoredResourceDescriptor descriptorPb) { - Builder builder = builder(descriptorPb.getType()); + Builder builder = newBuilder(descriptorPb.getType()); if (descriptorPb.getName() != null && !descriptorPb.getName().equals("")) { - builder.name(descriptorPb.getName()); + builder.setName(descriptorPb.getName()); } if (descriptorPb.getDisplayName() != null && !descriptorPb.getDisplayName().equals("")) { - builder.displayName(descriptorPb.getDisplayName()); + builder.setDisplayName(descriptorPb.getDisplayName()); } if (descriptorPb.getDescription() != null && !descriptorPb.getDescription().equals("")) { - builder.description(descriptorPb.getDescription()); + builder.setDescription(descriptorPb.getDescription()); } - builder.labels(Lists.transform(descriptorPb.getLabelsList(), LabelDescriptor.FROM_PB_FUNCTION)); + builder.setLabels(Lists.transform(descriptorPb.getLabelsList(), + LabelDescriptor.FROM_PB_FUNCTION)); return builder.build(); } } diff --git a/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceDescriptorTest.java b/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceDescriptorTest.java index cab0438e05d8..24a8be62e760 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceDescriptorTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceDescriptorTest.java @@ -44,15 +44,31 @@ public class MonitoredResourceDescriptorTest { private static final List LABELS = ImmutableList.of(BOOLEAN_LABEL, STRING_LABEL, INT_LABEL); private static final MonitoredResourceDescriptor RESOURCE_DESCRIPTOR = - MonitoredResourceDescriptor.builder(TYPE) - .name(NAME) - .displayName(DISPLAY_NAME) - .description(DESCRIPTION) - .labels(LABELS) + MonitoredResourceDescriptor.newBuilder(TYPE) + .setName(NAME) + .setDisplayName(DISPLAY_NAME) + .setDescription(DESCRIPTION) + .setLabels(LABELS) .build(); @Test public void testLabelDescriptor() { + assertEquals("booleanKey", BOOLEAN_LABEL.getKey()); + assertEquals(ValueType.BOOL, BOOLEAN_LABEL.getValueType()); + assertEquals("Boolean label", BOOLEAN_LABEL.getDescription()); + assertEquals("stringKey", STRING_LABEL.getKey()); + assertEquals(ValueType.STRING, STRING_LABEL.getValueType()); + assertEquals("String label", STRING_LABEL.getDescription()); + assertEquals("intKey", INT_LABEL.getKey()); + assertEquals(ValueType.INT64, INT_LABEL.getValueType()); + assertEquals("Int label", INT_LABEL.getDescription()); + assertEquals("intKey", INT_LABEL_NO_DESCRIPTION.getKey()); + assertEquals(ValueType.INT64, INT_LABEL_NO_DESCRIPTION.getValueType()); + assertNull(INT_LABEL_NO_DESCRIPTION.getDescription()); + } + + @Test + public void testLabelDescriptorDeprecated() { assertEquals("booleanKey", BOOLEAN_LABEL.key()); assertEquals(ValueType.BOOL, BOOLEAN_LABEL.valueType()); assertEquals("Boolean label", BOOLEAN_LABEL.description()); @@ -69,13 +85,29 @@ public void testLabelDescriptor() { @Test public void testBuilder() { + assertEquals(TYPE, RESOURCE_DESCRIPTOR.getType()); + assertEquals(NAME, RESOURCE_DESCRIPTOR.getName()); + assertEquals(DISPLAY_NAME, RESOURCE_DESCRIPTOR.getDisplayName()); + assertEquals(DESCRIPTION, RESOURCE_DESCRIPTOR.getDescription()); + assertEquals(LABELS, RESOURCE_DESCRIPTOR.getLabels()); + MonitoredResourceDescriptor resourceDescriptor = + MonitoredResourceDescriptor.newBuilder(TYPE).build(); + assertEquals(TYPE, resourceDescriptor.getType()); + assertNull(resourceDescriptor.getName()); + assertNull(resourceDescriptor.getDisplayName()); + assertNull(resourceDescriptor.getDescription()); + assertEquals(ImmutableList.of(), resourceDescriptor.getLabels()); + } + + @Test + public void testBuilderDeprecated() { assertEquals(TYPE, RESOURCE_DESCRIPTOR.type()); assertEquals(NAME, RESOURCE_DESCRIPTOR.name()); assertEquals(DISPLAY_NAME, RESOURCE_DESCRIPTOR.displayName()); assertEquals(DESCRIPTION, RESOURCE_DESCRIPTOR.description()); assertEquals(LABELS, RESOURCE_DESCRIPTOR.labels()); MonitoredResourceDescriptor resourceDescriptor = - MonitoredResourceDescriptor.builder(TYPE).build(); + MonitoredResourceDescriptor.newBuilder(TYPE).build(); assertEquals(TYPE, resourceDescriptor.type()); assertNull(resourceDescriptor.name()); assertNull(resourceDescriptor.displayName()); @@ -83,7 +115,6 @@ public void testBuilder() { assertEquals(ImmutableList.of(), resourceDescriptor.labels()); } - @Test public void testToAndFromPbLabelDescriptor() { compareLabelDescriptor(BOOLEAN_LABEL, LabelDescriptor.fromPb(BOOLEAN_LABEL.toPb())); @@ -98,16 +129,16 @@ public void testToAndFromPb() { compareResourceDescriptor(RESOURCE_DESCRIPTOR, MonitoredResourceDescriptor.fromPb(RESOURCE_DESCRIPTOR.toPb())); MonitoredResourceDescriptor resourceDescriptor = - MonitoredResourceDescriptor.builder(TYPE).build(); + MonitoredResourceDescriptor.newBuilder(TYPE).build(); compareResourceDescriptor(resourceDescriptor, MonitoredResourceDescriptor.fromPb(resourceDescriptor.toPb())); } private void compareLabelDescriptor(LabelDescriptor expected, LabelDescriptor value) { assertEquals(expected, value); - assertEquals(expected.key(), value.key()); - assertEquals(expected.valueType(), value.valueType()); - assertEquals(expected.description(), value.description()); + assertEquals(expected.getKey(), value.getKey()); + assertEquals(expected.getValueType(), value.getValueType()); + assertEquals(expected.getDescription(), value.getDescription()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } @@ -115,11 +146,11 @@ private void compareLabelDescriptor(LabelDescriptor expected, LabelDescriptor va private void compareResourceDescriptor(MonitoredResourceDescriptor expected, MonitoredResourceDescriptor value) { assertEquals(expected, value); - assertEquals(expected.type(), value.type()); - assertEquals(expected.name(), value.name()); - assertEquals(expected.displayName(), value.displayName()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.labels(), value.labels()); + assertEquals(expected.getType(), value.getType()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getDisplayName(), value.getDisplayName()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getLabels(), value.getLabels()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } diff --git a/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceTest.java b/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceTest.java index b42dc0c0f61b..845ff035c679 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/MonitoredResourceTest.java @@ -29,21 +29,46 @@ public class MonitoredResourceTest { private static final String TYPE = "cloudsql_database"; private static final Map LABELS = ImmutableMap.of("dataset-id", "myDataset", "zone", "myZone"); - private static final MonitoredResource MONITORED_RESOURCE = MonitoredResource.builder(TYPE) - .labels(LABELS) + private static final MonitoredResource MONITORED_RESOURCE = MonitoredResource.newBuilder(TYPE) + .setLabels(LABELS) .build(); + private static final MonitoredResource DEPRECATED_MONITORED_RESOURCE = + MonitoredResource.builder(TYPE) + .labels(LABELS) + .build(); @Test public void testBuilder() { - assertEquals(TYPE, MONITORED_RESOURCE.type()); - assertEquals(LABELS, MONITORED_RESOURCE.labels()); + assertEquals(TYPE, MONITORED_RESOURCE.getType()); + assertEquals(LABELS, MONITORED_RESOURCE.getLabels()); + MonitoredResource monitoredResource = MonitoredResource.newBuilder(TYPE) + .addLabel("dataset-id", "myDataset") + .addLabel("zone", "myZone") + .build(); + assertEquals(TYPE, monitoredResource.getType()); + assertEquals(LABELS, monitoredResource.getLabels()); + compareMonitoredResource(MONITORED_RESOURCE, monitoredResource); + monitoredResource = MonitoredResource.newBuilder(TYPE) + .setType("global") + .addLabel("dataset-id", "myDataset") + .addLabel("zone", "myZone") + .clearLabels() + .build(); + assertEquals("global", monitoredResource.getType()); + assertEquals(ImmutableMap.of(), monitoredResource.getLabels()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(TYPE, DEPRECATED_MONITORED_RESOURCE.type()); + assertEquals(LABELS, DEPRECATED_MONITORED_RESOURCE.labels()); MonitoredResource monitoredResource = MonitoredResource.builder(TYPE) .addLabel("dataset-id", "myDataset") .addLabel("zone", "myZone") .build(); assertEquals(TYPE, monitoredResource.type()); assertEquals(LABELS, monitoredResource.labels()); - compareMonitoredResource(MONITORED_RESOURCE, monitoredResource); + compareMonitoredResource(DEPRECATED_MONITORED_RESOURCE, monitoredResource); monitoredResource = MonitoredResource.builder(TYPE) .type("global") .addLabel("dataset-id", "myDataset") @@ -58,14 +83,14 @@ public void testBuilder() { public void testToBuilder() { compareMonitoredResource(MONITORED_RESOURCE, MONITORED_RESOURCE.toBuilder().build()); MonitoredResource monitoredResource = MONITORED_RESOURCE.toBuilder() - .type("global") + .setType("global") .clearLabels() .build(); - assertEquals("global", monitoredResource.type()); - assertEquals(ImmutableMap.of(), monitoredResource.labels()); + assertEquals("global", monitoredResource.getType()); + assertEquals(ImmutableMap.of(), monitoredResource.getLabels()); monitoredResource = monitoredResource.toBuilder() - .type(TYPE) - .labels(ImmutableMap.of("dataset-id", "myDataset")) + .setType(TYPE) + .setLabels(ImmutableMap.of("dataset-id", "myDataset")) .addLabel("zone", "myZone") .build(); compareMonitoredResource(MONITORED_RESOURCE, monitoredResource); @@ -74,8 +99,8 @@ public void testToBuilder() { @Test public void testOf() { MonitoredResource monitoredResource = MonitoredResource.of(TYPE, LABELS); - assertEquals(TYPE, monitoredResource.type()); - assertEquals(LABELS, monitoredResource.labels()); + assertEquals(TYPE, monitoredResource.getType()); + assertEquals(LABELS, monitoredResource.getLabels()); compareMonitoredResource(MONITORED_RESOURCE, monitoredResource); } @@ -90,8 +115,8 @@ public void testToAndFromPb() { private void compareMonitoredResource(MonitoredResource expected, MonitoredResource value) { assertEquals(expected, value); - assertEquals(expected.type(), value.type()); - assertEquals(expected.labels(), value.labels()); + assertEquals(expected.getType(), value.getType()); + assertEquals(expected.getLabels(), value.getLabels()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java b/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java index 13baed858bdb..ba3194c20371 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java @@ -46,11 +46,11 @@ public class SerializationTest extends BaseSerializationTest { private static final LabelDescriptor LABEL_DESCRIPTOR = new LabelDescriptor("project_id", ValueType.STRING, "The project id"); private static final MonitoredResourceDescriptor MONITORED_RESOURCE_DESCRIPTOR = - MonitoredResourceDescriptor.builder("global") - .labels(ImmutableList.of(LABEL_DESCRIPTOR)) + MonitoredResourceDescriptor.newBuilder("global") + .setLabels(ImmutableList.of(LABEL_DESCRIPTOR)) .build(); - private static final MonitoredResource MONITORED_RESOURCE = MonitoredResource.builder("global") - .labels(ImmutableMap.of("project_id", "project")) + private static final MonitoredResource MONITORED_RESOURCE = MonitoredResource.newBuilder("global") + .setLabels(ImmutableMap.of("project_id", "project")) .build(); private static final String JSON_KEY = "{\n" + " \"private_key_id\": \"somekeyid\",\n" diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/LoggingExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/LoggingExample.java index f41535bc8afa..3cab8c4dd3de 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/LoggingExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/LoggingExample.java @@ -353,9 +353,9 @@ SinkInfo parse(String... args) throws Exception { default: throw new IllegalArgumentException("Second argument must be bucket|dataset|topic."); } - SinkInfo.Builder builder = SinkInfo.builder(name, destination); + SinkInfo.Builder builder = SinkInfo.newBuilder(name, destination); if (args.length == 4) { - builder.filter(args[3]); + builder.setFilter(args[3]); } return builder.build(); } @@ -395,10 +395,10 @@ private static class WriteEntryAction extends LoggingAction { @Override public void run(Logging logging, LogEntry entry) { - MonitoredResource resource = MonitoredResource.builder("global") + MonitoredResource resource = MonitoredResource.newBuilder("global") .addLabel("project_id", logging.options().projectId()) .build(); - LogEntry entryWithResource = entry.toBuilder().resource(resource).build(); + LogEntry entryWithResource = entry.toBuilder().setResource(resource).build(); logging.write(Collections.singleton(entryWithResource)); System.out.printf("Written entry %s%n", entryWithResource); } @@ -416,10 +416,10 @@ LogEntry parse(String... args) throws Exception { for (int i = 3; i < args.length; i += 2) { labels.put(args[i], args[i + 1]); } - return LogEntry.builder(StringPayload.of(message)) - .logName(logName) - .severity(severity) - .labels(labels) + return LogEntry.newBuilder(StringPayload.of(message)) + .setLogName(logName) + .setSeverity(severity) + .setLabels(labels) .build(); } else { throw new IllegalArgumentException("Missing required arguments."); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListMetrics.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListMetrics.java index b32e50725db0..151b5428910b 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListMetrics.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListMetrics.java @@ -39,8 +39,8 @@ public static void main(String... args) throws Exception { try(Logging logging = LoggingOptions.defaultInstance().service()) { // Create a metric - MetricInfo metricInfo = MetricInfo.builder("test-metric", "severity >= ERROR") - .description("Log entries with severity higher or equal to ERROR") + MetricInfo metricInfo = MetricInfo.newBuilder("test-metric", "severity >= ERROR") + .setDescription("Log entries with severity higher or equal to ERROR") .build(); logging.create(metricInfo); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListSinks.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListSinks.java index 2a2f7008c480..cb5b378bd7b5 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListSinks.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListSinks.java @@ -39,8 +39,8 @@ public static void main(String... args) throws Exception { try(Logging logging = LoggingOptions.defaultInstance().service()) { // Create a sink to back log entries to a BigQuery dataset - SinkInfo sinkInfo = SinkInfo.builder("test-sink", DatasetDestination.of("test-dataset")) - .filter("severity >= ERROR") + SinkInfo sinkInfo = SinkInfo.newBuilder("test-sink", DatasetDestination.of("test-dataset")) + .setFilter("severity >= ERROR") .build(); logging.create(sinkInfo); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/LoggingSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/LoggingSnippets.java index 23e32bce2ca7..a4db3bb185fa 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/LoggingSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/LoggingSnippets.java @@ -97,9 +97,9 @@ public Sink createSinkAsync(String sinkName, String datasetName) // [VARIABLE "my_dataset"] public Sink updateSink(String sinkName, String datasetName) { // [START updateSink] - SinkInfo sinkInfo = SinkInfo.builder(sinkName, DatasetDestination.of(datasetName)) - .versionFormat(SinkInfo.VersionFormat.V2) - .filter("severity>=ERROR") + SinkInfo sinkInfo = SinkInfo.newBuilder(sinkName, DatasetDestination.of(datasetName)) + .setVersionFormat(SinkInfo.VersionFormat.V2) + .setFilter("severity>=ERROR") .build(); Sink sink = logging.update(sinkInfo); // [END updateSink] @@ -115,9 +115,9 @@ public Sink updateSink(String sinkName, String datasetName) { public Sink updateSinkAsync(String sinkName, String datasetName) throws ExecutionException, InterruptedException { // [START updateSinkAsync] - SinkInfo sinkInfo = SinkInfo.builder(sinkName, DatasetDestination.of(datasetName)) - .versionFormat(SinkInfo.VersionFormat.V2) - .filter("severity>=ERROR") + SinkInfo sinkInfo = SinkInfo.newBuilder(sinkName, DatasetDestination.of(datasetName)) + .setVersionFormat(SinkInfo.VersionFormat.V2) + .setFilter("severity>=ERROR") .build(); Future future = logging.updateAsync(sinkInfo); // ... @@ -337,8 +337,8 @@ public Metric createMetricAsync(String metricName) // [VARIABLE "my_metric_name"] public Metric updateMetric(String metricName) { // [START updateMetric] - MetricInfo metricInfo = MetricInfo.builder(metricName, "severity>=ERROR") - .description("new description") + MetricInfo metricInfo = MetricInfo.newBuilder(metricName, "severity>=ERROR") + .setDescription("new description") .build(); Metric metric = logging.update(metricInfo); // [END updateMetric] @@ -353,8 +353,8 @@ public Metric updateMetric(String metricName) { public Metric updateMetricAsync(String metricName) throws ExecutionException, InterruptedException { // [START updateMetricAsync] - MetricInfo metricInfo = MetricInfo.builder(metricName, "severity>=ERROR") - .description("new description") + MetricInfo metricInfo = MetricInfo.newBuilder(metricName, "severity>=ERROR") + .setDescription("new description") .build(); Future future = logging.updateAsync(metricInfo); // ... @@ -480,7 +480,7 @@ public void write(String logName) { entries.add(LogEntry.of(JsonPayload.of(jsonMap))); logging.write(entries, WriteOption.logName(logName), - WriteOption.resource(MonitoredResource.builder("global").build())); + WriteOption.resource(MonitoredResource.newBuilder("global").build())); // [END write] } @@ -500,7 +500,7 @@ public Future writeAsync(String logName) { Future future = logging.writeAsync( entries, WriteOption.logName(logName), - WriteOption.resource(MonitoredResource.builder("global").build())); + WriteOption.resource(MonitoredResource.newBuilder("global").build())); // [END writeAsync] return future; } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/MetricSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/MetricSnippets.java index 48c6193c16fb..b986d5206e04 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/MetricSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/MetricSnippets.java @@ -75,7 +75,7 @@ public Metric reloadAsync() throws ExecutionException, InterruptedException { public Metric update() { // [START update] Metric updatedMetric = metric.toBuilder() - .description("A more detailed description") + .setDescription("A more detailed description") .build() .update(); // [END update] @@ -89,7 +89,7 @@ public Metric update() { public Metric updateAsync() throws ExecutionException, InterruptedException { // [START updateAsync] Future future = metric.toBuilder() - .description("A more detailed description") + .setDescription("A more detailed description") .build() .updateAsync(); // ... diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/SinkSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/SinkSnippets.java index 4383d07b4f62..d3896dd5f8f3 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/SinkSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/SinkSnippets.java @@ -75,7 +75,7 @@ public Sink reloadAsync() throws ExecutionException, InterruptedException { public Sink update() { // [START update] Sink updatedSink = sink.toBuilder() - .filter("severity<=ERROR") + .setFilter("severity<=ERROR") .build() .update(); // [END update] @@ -89,7 +89,7 @@ public Sink update() { public Sink updateAsync() throws ExecutionException, InterruptedException { // [START updateAsync] Future future = sink.toBuilder() - .filter("severity<=ERROR") + .setFilter("severity<=ERROR") .build() .updateAsync(); // ... diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/WriteAndListLogEntries.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/WriteAndListLogEntries.java index 69785430891a..cc0b8fe175c8 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/WriteAndListLogEntries.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/WriteAndListLogEntries.java @@ -42,9 +42,9 @@ public static void main(String... args) throws Exception { try(Logging logging = options.service()) { // Create a log entry - LogEntry firstEntry = LogEntry.builder(StringPayload.of("message")) - .logName("test-log") - .resource(MonitoredResource.builder("global") + LogEntry firstEntry = LogEntry.newBuilder(StringPayload.of("message")) + .setLogName("test-log") + .setResource(MonitoredResource.newBuilder("global") .addLabel("project_id", options.projectId()) .build()) .build(); diff --git a/google-cloud-logging/README.md b/google-cloud-logging/README.md index adb28e74160a..90e302dc5157 100644 --- a/google-cloud-logging/README.md +++ b/google-cloud-logging/README.md @@ -112,8 +112,8 @@ import com.google.cloud.logging.MetricInfo; Then, to create the metric, use the following code: ```java -MetricInfo metricInfo = MetricInfo.builder("test-metric", "severity >= ERROR") - .description("Log entries with severity higher or equal to ERROR") +MetricInfo metricInfo = MetricInfo.newBuilder("test-metric", "severity >= ERROR") + .setDescription("Log entries with severity higher or equal to ERROR") .build(); logging.create(metricInfo); ``` @@ -131,9 +131,9 @@ import java.util.Collections; ``` Then, to write the log entries, use the following code: ```java -LogEntry firstEntry = LogEntry.builder(StringPayload.of("message")) - .logName("test-log") - .resource(MonitoredResource.builder("global") +LogEntry firstEntry = LogEntry.newBuilder(StringPayload.of("message")) + .setLogName("test-log") + .setResource(MonitoredResource.builder("global") .addLabel("project_id", options.projectId()) .build()) .build(); diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/AsyncLoggingHandler.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/AsyncLoggingHandler.java index 80dd58872e0e..27ff47b1bd69 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/AsyncLoggingHandler.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/AsyncLoggingHandler.java @@ -96,6 +96,6 @@ public AsyncLoggingHandler(String logName, LoggingOptions options, MonitoredReso @Override void write(List entries, WriteOption... options) { - logging().writeAsync(entries, options); + getLogging().writeAsync(entries, options); } } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/HttpRequest.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/HttpRequest.java index ebe14032933d..efac2760d895 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/HttpRequest.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/HttpRequest.java @@ -97,7 +97,15 @@ public static final class Builder { /** * Sets the HTTP request method. */ + @Deprecated public Builder requestMethod(RequestMethod requestMethod) { + return setRequestMethod(requestMethod); + } + + /** + * Sets the HTTP request method. + */ + public Builder setRequestMethod(RequestMethod requestMethod) { this.requestMethod = requestMethod; return this; } @@ -107,7 +115,17 @@ public Builder requestMethod(RequestMethod requestMethod) { * host name, the path and the query portion of the URL that was requested. Example: * {@code http://example.com/some/info?color=red}. */ + @Deprecated public Builder requestUrl(String requestUrl) { + return setRequestUrl(requestUrl); + } + + /** + * Sets the requested URL. Request URL contains the scheme ({@code http}, {@code https}), the + * host name, the path and the query portion of the URL that was requested. Example: + * {@code http://example.com/some/info?color=red}. + */ + public Builder setRequestUrl(String requestUrl) { this.requestUrl = requestUrl; return this; } @@ -116,7 +134,16 @@ public Builder requestUrl(String requestUrl) { * Sets the size of the HTTP request message in bytes, including the request headers and the * request body. */ + @Deprecated public Builder requestSize(long requestSize) { + return setRequestSize(requestSize); + } + + /** + * Sets the size of the HTTP request message in bytes, including the request headers and the + * request body. + */ + public Builder setRequestSize(long requestSize) { this.requestSize = requestSize; return this; } @@ -124,7 +151,15 @@ public Builder requestSize(long requestSize) { /** * Sets the response code indicating the status of response. */ + @Deprecated public Builder status(int status) { + return setStatus(status); + } + + /** + * Sets the response code indicating the status of response. + */ + public Builder setStatus(int status) { this.status = status; return this; } @@ -133,7 +168,16 @@ public Builder status(int status) { * Sets the size of the HTTP response message sent back to the client, in bytes, including the * response headers and the response body. */ + @Deprecated public Builder responseSize(long responseSize) { + return setResponseSize(responseSize); + } + + /** + * Sets the size of the HTTP response message sent back to the client, in bytes, including the + * response headers and the response body. + */ + public Builder setResponseSize(long responseSize) { this.responseSize = responseSize; return this; } @@ -142,7 +186,16 @@ public Builder responseSize(long responseSize) { * Sets the user agent sent by the client. Example: * {@code Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)}. */ + @Deprecated public Builder userAgent(String userAgent) { + return setUserAgent(userAgent); + } + + /** + * Sets the user agent sent by the client. Example: + * {@code Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)}. + */ + public Builder setUserAgent(String userAgent) { this.userAgent = userAgent; return this; } @@ -151,7 +204,16 @@ public Builder userAgent(String userAgent) { * Sets the IP address (IPv4 or IPv6) of the client that issued the HTTP request. Examples: * {@code 192.168.1.1}, {@code FE80::0202:B3FF:FE1E:8329}. */ + @Deprecated public Builder remoteIp(String remoteIp) { + return setRemoteIp(remoteIp); + } + + /** + * Sets the IP address (IPv4 or IPv6) of the client that issued the HTTP request. Examples: + * {@code 192.168.1.1}, {@code FE80::0202:B3FF:FE1E:8329}. + */ + public Builder setRemoteIp(String remoteIp) { this.remoteIp = remoteIp; return this; } @@ -160,7 +222,16 @@ public Builder remoteIp(String remoteIp) { * Sets the IP address (IPv4 or IPv6) of the origin server that the request was sent to. * Examples: {@code 192.168.1.1}, {@code FE80::0202:B3FF:FE1E:8329}. */ + @Deprecated public Builder serverIp(String serverIp) { + return setServerIp(serverIp); + } + + /** + * Sets the IP address (IPv4 or IPv6) of the origin server that the request was sent to. + * Examples: {@code 192.168.1.1}, {@code FE80::0202:B3FF:FE1E:8329}. + */ + public Builder setServerIp(String serverIp) { this.serverIp = serverIp; return this; } @@ -171,7 +242,18 @@ public Builder serverIp(String serverIp) { * @see HTTP/1.1 Header Field * Definitions */ + @Deprecated public Builder referer(String referer) { + return setReferer(referer); + } + + /** + * Sets the referer URL of the request, as defined in HTTP/1.1 Header Field Definitions. + * + * @see HTTP/1.1 Header Field + * Definitions + */ + public Builder setReferer(String referer) { this.referer = referer; return this; } @@ -179,7 +261,15 @@ public Builder referer(String referer) { /** * Sets whether or not a cache lookup was attempted. If not set, {@code false} is used. */ + @Deprecated public Builder cacheLookup(boolean cacheLookup) { + return setCacheLookup(cacheLookup); + } + + /** + * Sets whether or not a cache lookup was attempted. If not set, {@code false} is used. + */ + public Builder setCacheLookup(boolean cacheLookup) { this.cacheLookup = cacheLookup; return this; } @@ -188,7 +278,16 @@ public Builder cacheLookup(boolean cacheLookup) { * Sets whether or not an entity was served from cache (with or without validation). If not set, * {@code false} is used. */ + @Deprecated public Builder cacheHit(boolean cacheHit) { + return setCacheHit(cacheHit); + } + + /** + * Sets whether or not an entity was served from cache (with or without validation). If not set, + * {@code false} is used. + */ + public Builder setCacheHit(boolean cacheHit) { this.cacheHit = cacheHit; return this; } @@ -198,7 +297,17 @@ public Builder cacheHit(boolean cacheHit) { * from cache. This field is only meaningful if {@link #cacheHit(boolean)} is set to * {@code true}. If not set, {@code false} is used. */ + @Deprecated public Builder cacheValidatedWithOriginServer(boolean cacheValidatedWithOriginServer) { + return setCacheValidatedWithOriginServer(cacheValidatedWithOriginServer); + } + + /** + * Sets whether or not the response was validated with the origin server before being served + * from cache. This field is only meaningful if {@link #cacheHit(boolean)} is set to + * {@code true}. If not set, {@code false} is used. + */ + public Builder setCacheValidatedWithOriginServer(boolean cacheValidatedWithOriginServer) { this.cacheValidatedWithOriginServer = cacheValidatedWithOriginServer; return this; } @@ -207,7 +316,16 @@ public Builder cacheValidatedWithOriginServer(boolean cacheValidatedWithOriginSe * Sets the number of HTTP response bytes inserted into cache. Set only when a cache fill was * attempted. */ + @Deprecated public Builder cacheFillBytes(long cacheFillBytes) { + return setCacheFillBytes(cacheFillBytes); + } + + /** + * Sets the number of HTTP response bytes inserted into cache. Set only when a cache fill was + * attempted. + */ + public Builder setCacheFillBytes(long cacheFillBytes) { this.cacheFillBytes = cacheFillBytes; return this; } @@ -239,7 +357,15 @@ public HttpRequest build() { /** * Returns the HTTP request method. */ + @Deprecated public RequestMethod requestMethod() { + return getRequestMethod(); + } + + /** + * Returns the HTTP request method. + */ + public RequestMethod getRequestMethod() { return requestMethod; } @@ -248,7 +374,17 @@ public RequestMethod requestMethod() { * host name, the path and the query portion of the URL that was requested. Example: * {@code http://example.com/some/info?color=red}. */ + @Deprecated public String requestUrl() { + return getRequestUrl(); + } + + /** + * Returns the requested URL. Request URL contains the scheme ({@code http}, {@code https}), the + * host name, the path and the query portion of the URL that was requested. Example: + * {@code http://example.com/some/info?color=red}. + */ + public String getRequestUrl() { return requestUrl; } @@ -256,14 +392,31 @@ public String requestUrl() { * Returns the size of the HTTP request message in bytes, including the request headers and the * request body. */ + @Deprecated public Long requestSize() { + return getRequestSize(); + } + + /** + * Returns the size of the HTTP request message in bytes, including the request headers and the + * request body. + */ + public Long getRequestSize() { return requestSize; } /** * Returns the response code indicating the status of response. */ + @Deprecated public Integer status() { + return getStatus(); + } + + /** + * Returns the response code indicating the status of response. + */ + public Integer getStatus() { return status; } @@ -271,7 +424,16 @@ public Integer status() { * Returns the size of the HTTP response message sent back to the client, in bytes, including the * response headers and the response body. */ + @Deprecated public Long responseSize() { + return getResponseSize(); + } + + /** + * Returns the size of the HTTP response message sent back to the client, in bytes, including the + * response headers and the response body. + */ + public Long getResponseSize() { return responseSize; } @@ -279,7 +441,16 @@ public Long responseSize() { * Returns the user agent sent by the client. Example: * {@code Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)}. */ + @Deprecated public String userAgent() { + return getUserAgent(); + } + + /** + * Returns the user agent sent by the client. Example: + * {@code Mozilla/4.0 (compatible; MSIE 6.0; Windows 98; Q312461; .NET CLR 1.0.3705)}. + */ + public String getUserAgent() { return userAgent; } @@ -287,7 +458,16 @@ public String userAgent() { * Returns the IP address (IPv4 or IPv6) of the client that issued the HTTP request. Examples: * {@code 192.168.1.1}, {@code FE80::0202:B3FF:FE1E:8329}. */ + @Deprecated public String remoteIp() { + return getRemoteIp(); + } + + /** + * Returns the IP address (IPv4 or IPv6) of the client that issued the HTTP request. Examples: + * {@code 192.168.1.1}, {@code FE80::0202:B3FF:FE1E:8329}. + */ + public String getRemoteIp() { return remoteIp; } @@ -295,7 +475,16 @@ public String remoteIp() { * Returns the IP address (IPv4 or IPv6) of the origin server that the request was sent to. * Examples: {@code 192.168.1.1}, {@code FE80::0202:B3FF:FE1E:8329}. */ + @Deprecated public String serverIp() { + return getServerIp(); + } + + /** + * Returns the IP address (IPv4 or IPv6) of the origin server that the request was sent to. + * Examples: {@code 192.168.1.1}, {@code FE80::0202:B3FF:FE1E:8329}. + */ + public String getServerIp() { return serverIp; } @@ -305,7 +494,18 @@ public String serverIp() { * @see HTTP/1.1 Header Field * Definitions */ + @Deprecated public String referer() { + return getReferer(); + } + + /** + * Returns the referer URL of the request, as defined in HTTP/1.1 Header Field Definitions. + * + * @see HTTP/1.1 Header Field + * Definitions + */ + public String getReferer() { return referer; } @@ -338,7 +538,16 @@ public boolean cacheValidatedWithOriginServer() { * Returns the number of HTTP response bytes inserted into cache. Set only when a cache fill was * attempted. */ + @Deprecated public Long cacheFillBytes() { + return getCacheFillBytes(); + } + + /** + * Returns the number of HTTP response bytes inserted into cache. Set only when a cache fill was + * attempted. + */ + public Long getCacheFillBytes() { return cacheFillBytes; } @@ -423,7 +632,7 @@ com.google.logging.type.HttpRequest toPb() { if (remoteIp != null) { builder.setRemoteIp(remoteIp); } - if (serverIp != null) { + if (serverIp != null) { builder.setServerIp(serverIp); } if (referer != null) { @@ -441,44 +650,52 @@ com.google.logging.type.HttpRequest toPb() { /** * Returns a builder for {@code HttpRequest} objects. */ + @Deprecated public static Builder builder() { + return newBuilder(); + } + + /** + * Returns a builder for {@code HttpRequest} objects. + */ + public static Builder newBuilder() { return new Builder(); } static HttpRequest fromPb(com.google.logging.type.HttpRequest requestPb) { - Builder builder = builder(); + Builder builder = newBuilder(); if (requestPb.getRequestMethod() != null && !requestPb.getRequestMethod().equals("")) { - builder.requestMethod(RequestMethod.valueOf(requestPb.getRequestMethod())); + builder.setRequestMethod(RequestMethod.valueOf(requestPb.getRequestMethod())); } if (requestPb.getRequestUrl() != null && !requestPb.getRequestUrl().equals("")) { - builder.requestUrl(requestPb.getRequestUrl()); + builder.setRequestUrl(requestPb.getRequestUrl()); } if (requestPb.getRequestSize() != 0L) { - builder.requestSize(requestPb.getRequestSize()); + builder.setRequestSize(requestPb.getRequestSize()); } if (requestPb.getStatus() != 0L) { - builder.status(requestPb.getStatus()); + builder.setStatus(requestPb.getStatus()); } if (requestPb.getResponseSize() != 0L) { - builder.responseSize(requestPb.getResponseSize()); + builder.setResponseSize(requestPb.getResponseSize()); } if (requestPb.getUserAgent() != null && !requestPb.getRequestUrl().equals("")) { - builder.userAgent(requestPb.getUserAgent()); + builder.setUserAgent(requestPb.getUserAgent()); } if (requestPb.getServerIp() != null && !requestPb.getServerIp().equals("")) { - builder.serverIp(requestPb.getServerIp()); + builder.setServerIp(requestPb.getServerIp()); } if (requestPb.getRemoteIp() != null && !requestPb.getRemoteIp().equals("")) { - builder.remoteIp(requestPb.getRemoteIp()); + builder.setRemoteIp(requestPb.getRemoteIp()); } if (requestPb.getReferer() != null && !requestPb.getReferer().equals("")) { - builder.referer(requestPb.getReferer()); + builder.setReferer(requestPb.getReferer()); } - builder.cacheLookup(requestPb.getCacheLookup()); - builder.cacheHit(requestPb.getCacheHit()); - builder.cacheValidatedWithOriginServer(requestPb.getCacheValidatedWithOriginServer()); + builder.setCacheLookup(requestPb.getCacheLookup()); + builder.setCacheHit(requestPb.getCacheHit()); + builder.setCacheValidatedWithOriginServer(requestPb.getCacheValidatedWithOriginServer()); if (requestPb.getCacheFillBytes() != 0L) { - builder.cacheFillBytes(requestPb.getCacheFillBytes()); + builder.setCacheFillBytes(requestPb.getCacheFillBytes()); } return builder.build(); } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntry.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntry.java index ab87a9cb710a..821c6e9b76af 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntry.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LogEntry.java @@ -102,7 +102,19 @@ public static class Builder { * forward-slash ({@code /}) characters in the log name must be URL-encoded. Examples: * {@code syslog}, {@code library.googleapis.com%2Fbook_log}. */ + @Deprecated public Builder logName(String logName) { + return setLogName(logName); + } + + /** + * Sets the name of the log to which this log entry belongs. The log name must be less than 512 + * characters long and can only include the following characters: upper and lower case + * alphanumeric characters: {@code [A-Za-z0-9]}; and punctuation characters: {@code _-./}. The + * forward-slash ({@code /}) characters in the log name must be URL-encoded. Examples: + * {@code syslog}, {@code library.googleapis.com%2Fbook_log}. + */ + public Builder setLogName(String logName) { this.logName = logName; return this; } @@ -112,7 +124,17 @@ public Builder logName(String logName) { * a database error would be associated with the monitored resource designating the particular * database that reported the error. */ + @Deprecated public Builder resource(MonitoredResource resource) { + return setResource(resource); + } + + /** + * Sets the monitored resource associated with this log entry. Example: a log entry that reports + * a database error would be associated with the monitored resource designating the particular + * database that reported the error. + */ + public Builder setResource(MonitoredResource resource) { this.resource = resource; return this; } @@ -121,7 +143,16 @@ public Builder resource(MonitoredResource resource) { * Sets the time at which the event described by the log entry occurred, in milliseconds. If * omitted, the Logging service will use the time at which the log entry is received. */ + @Deprecated public Builder timestamp(long timestamp) { + return setTimestamp(timestamp); + } + + /** + * Sets the time at which the event described by the log entry occurred, in milliseconds. If + * omitted, the Logging service will use the time at which the log entry is received. + */ + public Builder setTimestamp(long timestamp) { this.timestamp = timestamp; return this; } @@ -129,7 +160,15 @@ public Builder timestamp(long timestamp) { /** * Sets the severity of the log entry. If not set, {@link Severity#DEFAULT} is used. */ + @Deprecated public Builder severity(Severity severity) { + return setSeverity(severity); + } + + /** + * Sets the severity of the log entry. If not set, {@link Severity#DEFAULT} is used. + */ + public Builder setSeverity(Severity severity) { this.severity = severity; return this; } @@ -139,7 +178,17 @@ public Builder severity(Severity severity) { * other log entries in the same log with the same ID as duplicates which can be removed. If * omitted, the Logging service will generate a unique ID for this log entry. */ + @Deprecated public Builder insertId(String insertId) { + return setInsertId(insertId); + } + + /** + * Sets a unique ID for the log entry. If you provide this field, the Logging service considers + * other log entries in the same log with the same ID as duplicates which can be removed. If + * omitted, the Logging service will generate a unique ID for this log entry. + */ + public Builder setInsertId(String insertId) { this.insertId = insertId; return this; } @@ -147,7 +196,15 @@ public Builder insertId(String insertId) { /** * Sets information about the HTTP request associated with this log entry, if applicable. */ + @Deprecated public Builder httpRequest(HttpRequest httpRequest) { + return setHttpRequest(httpRequest); + } + + /** + * Sets information about the HTTP request associated with this log entry, if applicable. + */ + public Builder setHttpRequest(HttpRequest httpRequest) { this.httpRequest = httpRequest; return this; } @@ -156,7 +213,16 @@ public Builder httpRequest(HttpRequest httpRequest) { * Sets an optional set of user-defined (key, value) data that provides additional information * about the log entry. */ + @Deprecated public Builder labels(Map labels) { + return setLabels(labels); + } + + /** + * Sets an optional set of user-defined (key, value) data that provides additional information + * about the log entry. + */ + public Builder setLabels(Map labels) { this.labels = new HashMap<>(checkNotNull(labels)); return this; } @@ -182,7 +248,15 @@ public Builder clearLabels() { /** * Sets information about an operation associated with the log entry, if applicable. */ + @Deprecated public Builder operation(Operation operation) { + return setOperation(operation); + } + + /** + * Sets information about an operation associated with the log entry, if applicable. + */ + public Builder setOperation(Operation operation) { this.operation = operation; return this; } @@ -194,7 +268,19 @@ public Builder operation(Operation operation) { * * @see Log Entries and Logs */ + @Deprecated public Builder payload(Payload payload) { + return setPayload(payload); + } + + /** + * Sets the payload for this log entry. The log entry payload can be provided as an UTF-8 string + * (see {@link Payload.StringPayload}), a JSON object (see {@link Payload.JsonPayload}, or + * a protobuf object (see {@link Payload.ProtoPayload}). + * + * @see Log Entries and Logs + */ + public Builder setPayload(Payload payload) { this.payload = payload; return this; } @@ -226,7 +312,19 @@ public LogEntry build() { * forward-slash ({@code /}) characters in the log name must be URL-encoded. Examples: * {@code syslog}, {@code library.googleapis.com%2Fbook_log}. */ + @Deprecated public String logName() { + return getLogName(); + } + + /** + * Returns the name of the log to which this log entry belongs. The log name must be less than 512 + * characters long and can only include the following characters: upper and lower case + * alphanumeric characters: {@code [A-Za-z0-9]}; and punctuation characters: {@code _-./}. The + * forward-slash ({@code /}) characters in the log name must be URL-encoded. Examples: + * {@code syslog}, {@code library.googleapis.com%2Fbook_log}. + */ + public String getLogName() { return logName; } @@ -235,7 +333,17 @@ public String logName() { * reports a database error would be associated with the monitored resource designating the * particular database that reported the error. */ + @Deprecated public MonitoredResource resource() { + return getResource(); + } + + /** + * Returns the monitored resource associated with this log entry. Example: a log entry that + * reports a database error would be associated with the monitored resource designating the + * particular database that reported the error. + */ + public MonitoredResource getResource() { return resource; } @@ -243,14 +351,31 @@ public MonitoredResource resource() { * Returns the time at which the event described by the log entry occurred, in milliseconds. If * omitted, the Logging service will use the time at which the log entry is received. */ + @Deprecated public Long timestamp() { + return getTimestamp(); + } + + /** + * Returns the time at which the event described by the log entry occurred, in milliseconds. If + * omitted, the Logging service will use the time at which the log entry is received. + */ + public Long getTimestamp() { return timestamp; } /** * Returns the severity of the log entry. If not set, {@link Severity#DEFAULT} is used. */ + @Deprecated public Severity severity() { + return getSeverity(); + } + + /** + * Returns the severity of the log entry. If not set, {@link Severity#DEFAULT} is used. + */ + public Severity getSeverity() { return severity; } @@ -258,14 +383,31 @@ public Severity severity() { * Returns a unique ID for the log entry. The Logging service considers other log entries in the * same log with the same ID as duplicates which can be removed. */ + @Deprecated public String insertId() { + return getInsertId(); + } + + /** + * Returns a unique ID for the log entry. The Logging service considers other log entries in the + * same log with the same ID as duplicates which can be removed. + */ + public String getInsertId() { return insertId; } /** * Returns information about the HTTP request associated with this log entry, if applicable. */ + @Deprecated public HttpRequest httpRequest() { + return getHttpRequest(); + } + + /** + * Returns information about the HTTP request associated with this log entry, if applicable. + */ + public HttpRequest getHttpRequest() { return httpRequest; } @@ -273,14 +415,31 @@ public HttpRequest httpRequest() { * Returns an optional set of user-defined (key, value) data that provides additional information * about the log entry. */ + @Deprecated public Map labels() { + return getLabels(); + } + + /** + * Returns an optional set of user-defined (key, value) data that provides additional information + * about the log entry. + */ + public Map getLabels() { return labels; } /** * Returns information about an operation associated with the log entry, if applicable. */ + @Deprecated public Operation operation() { + return getOperation(); + } + + /** + * Returns information about an operation associated with the log entry, if applicable. + */ + public Operation getOperation() { return operation; } @@ -292,7 +451,20 @@ public Operation operation() { * @see Log Entries and Logs */ @SuppressWarnings("unchecked") + @Deprecated public T payload() { + return getPayload(); + } + + /** + * Returns the payload for this log entry. The log entry payload can be an UTF-8 string (see + * {@link Payload.StringPayload}), a JSON object (see {@link Payload.JsonPayload}, or a protobuf + * object (see {@link Payload.ProtoPayload}). + * + * @see Log Entries and Logs + */ + @SuppressWarnings("unchecked") + public T getPayload() { return (T) payload; } @@ -377,7 +549,15 @@ com.google.logging.v2.LogEntry toPb(String projectId) { /** * Returns a builder for {@code LogEntry} objects given the entry payload. */ + @Deprecated public static Builder builder(Payload payload) { + return newBuilder(payload); + } + + /** + * Returns a builder for {@code LogEntry} objects given the entry payload. + */ + public static Builder newBuilder(Payload payload) { return new Builder(payload); } @@ -385,7 +565,7 @@ public static Builder builder(Payload payload) { * Creates a {@code LogEntry} object given the entry payload. */ public static LogEntry of(Payload payload) { - return builder(payload).build(); + return newBuilder(payload).build(); } /** @@ -393,35 +573,35 @@ public static LogEntry of(Payload payload) { * payload. */ public static LogEntry of(String logName, MonitoredResource resource, Payload payload) { - return builder(payload).logName(logName).resource(resource).build(); + return newBuilder(payload).setLogName(logName).setResource(resource).build(); } static LogEntry fromPb(com.google.logging.v2.LogEntry entryPb) { - Builder builder = builder(Payload.fromPb(entryPb)); - builder.labels(entryPb.getLabels()); - builder.severity(Severity.fromPb(entryPb.getSeverity())); + Builder builder = newBuilder(Payload.fromPb(entryPb)); + builder.setLabels(entryPb.getLabelsMap()); + builder.setSeverity(Severity.fromPb(entryPb.getSeverity())); if (!entryPb.getLogName().equals("")) { - builder.logName(LoggingServiceV2Api.parseLogFromLogName(entryPb.getLogName())); + builder.setLogName(LoggingServiceV2Api.parseLogFromLogName(entryPb.getLogName())); } if (!entryPb.getResource().equals(com.google.api.MonitoredResource.getDefaultInstance())) { - builder.resource(MonitoredResource.fromPb(entryPb.getResource())); + builder.setResource(MonitoredResource.fromPb(entryPb.getResource())); } if (entryPb.hasTimestamp()) { Timestamp ts = entryPb.getTimestamp(); Long millis = ts.getSeconds() * MILLIS_PER_SECOND + ts.getNanos() / NANOS_PER_MILLISECOND; if (millis != 0) { - builder.timestamp(millis); + builder.setTimestamp(millis); } } if (!entryPb.getInsertId().equals("")) { - builder.insertId(entryPb.getInsertId()); + builder.setInsertId(entryPb.getInsertId()); } if (!entryPb.getHttpRequest().equals( com.google.logging.type.HttpRequest.getDefaultInstance())) { - builder.httpRequest(HttpRequest.fromPb(entryPb.getHttpRequest())); + builder.setHttpRequest(HttpRequest.fromPb(entryPb.getHttpRequest())); } if (!entryPb.getOperation().equals(LogEntryOperation.getDefaultInstance())) { - builder.operation(Operation.fromPb(entryPb.getOperation())); + builder.setOperation(Operation.fromPb(entryPb.getOperation())); } return builder.build(); } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Logging.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Logging.java index 2f4b9c0b1cb7..0db8c916d5f8 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Logging.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Logging.java @@ -234,9 +234,9 @@ public static EntryListOption filter(String filter) { *

 {@code
    * String sinkName = "my_sink_name";
    * String datasetName = "my_dataset";
-   * SinkInfo sinkInfo = SinkInfo.builder(sinkName, DatasetDestination.of(datasetName))
-   *     .versionFormat(SinkInfo.VersionFormat.V2)
-   *     .filter("severity>=ERROR")
+   * SinkInfo sinkInfo = SinkInfo.newBuilder(sinkName, DatasetDestination.of(datasetName))
+   *     .setVersionFormat(SinkInfo.VersionFormat.V2)
+   *     .setFilter("severity>=ERROR")
    *     .build();
    * Sink sink = logging.update(sinkInfo);
    * }
@@ -255,9 +255,9 @@ public static EntryListOption filter(String filter) { *
 {@code
    * String sinkName = "my_sink_name";
    * String datasetName = "my_dataset";
-   * SinkInfo sinkInfo = SinkInfo.builder(sinkName, DatasetDestination.of(datasetName))
-   *     .versionFormat(SinkInfo.VersionFormat.V2)
-   *     .filter("severity>=ERROR")
+   * SinkInfo sinkInfo = SinkInfo.newBuilder(sinkName, DatasetDestination.of(datasetName))
+   *     .setVersionFormat(SinkInfo.VersionFormat.V2)
+   *     .setFilter("severity>=ERROR")
    *     .build();
    * Future future = logging.updateAsync(sinkInfo);
    * // ...
@@ -274,7 +274,7 @@ public static EntryListOption filter(String filter) {
    * 
 {@code
    * String sinkName = "my_sink_name";
    * Sink sink = logging.getSink(sinkName);
-   * if (sink != null) {
+   * if (sink == null) {
    *   // sink was not found
    * }
    * }
@@ -293,7 +293,7 @@ public static EntryListOption filter(String filter) { * Future future = logging.getSinkAsync(sinkName); * // ... * Sink sink = future.get(); - * if (sink != null) { + * if (sink == null) { * // sink was not found * } * }
@@ -501,8 +501,8 @@ Future> listMonitoredResourceDescriptorsA *

Example of updating a metric. *

 {@code
    * String metricName = "my_metric_name";
-   * MetricInfo metricInfo = MetricInfo.builder(metricName, "severity>=ERROR")
-   *     .description("new description")
+   * MetricInfo metricInfo = MetricInfo.newBuilder(metricName, "severity>=ERROR")
+   *     .setDescription("new description")
    *     .build();
    * Metric metric = logging.update(metricInfo);
    * }
@@ -520,8 +520,8 @@ Future> listMonitoredResourceDescriptorsA *

Example of asynchronously updating a metric. *

 {@code
    * String metricName = "my_metric_name";
-   * MetricInfo metricInfo = MetricInfo.builder(metricName, "severity>=ERROR")
-   *     .description("new description")
+   * MetricInfo metricInfo = MetricInfo.newBuilder(metricName, "severity>=ERROR")
+   *     .setDescription("new description")
    *     .build();
    * Future future = logging.updateAsync(metricInfo);
    * // ...
@@ -538,7 +538,7 @@ Future> listMonitoredResourceDescriptorsA
    * 
 {@code
    * String metricName = "my_metric_name";
    * Metric metric = logging.getMetric(metricName);
-   * if (metric != null) {
+   * if (metric == null) {
    *   // metric was not found
    * }
    * }
@@ -557,7 +557,7 @@ Future> listMonitoredResourceDescriptorsA * Future future = logging.getMetricAsync(metricName); * // ... * Metric metric = future.get(); - * if (metric != null) { + * if (metric == null) { * // metric was not found * } * }
@@ -662,7 +662,7 @@ Future> listMonitoredResourceDescriptorsA * entries.add(LogEntry.of(JsonPayload.of(jsonMap))); * logging.write(entries, * WriteOption.logName(logName), - * WriteOption.resource(MonitoredResource.builder("global").build())); + * WriteOption.resource(MonitoredResource.newBuilder("global").build())); * } * */ @@ -688,7 +688,7 @@ Future> listMonitoredResourceDescriptorsA * Future future = logging.writeAsync( * entries, * WriteOption.logName(logName), - * WriteOption.resource(MonitoredResource.builder("global").build())); + * WriteOption.resource(MonitoredResource.newBuilder("global").build())); * } * */ diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java index 892dd374fc30..21eca656b972 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java @@ -147,7 +147,7 @@ public LoggingHandler(String log, LoggingOptions options, MonitoredResource moni setFilter(helper.getFilterProperty(className + ".filter", null)); setFormatter(helper.getFormatterProperty(className + ".formatter", new SimpleFormatter())); String logName = firstNonNull(log, helper.getProperty(className + ".log", "java.log")); - MonitoredResource resource = firstNonNull(monitoredResource, defaultResource()); + MonitoredResource resource = firstNonNull(monitoredResource, getDefaultResource()); writeOptions = new WriteOption[]{WriteOption.logName(logName), WriteOption.resource(resource)}; maskLoggers(); } @@ -207,7 +207,7 @@ private static boolean hasLoggingHandler(Logger logger) { return false; } - private MonitoredResource defaultResource() { + private MonitoredResource getDefaultResource() { return MonitoredResource.of("global", ImmutableMap.of("project_id", options.projectId())); } @@ -271,7 +271,7 @@ Formatter getFormatterProperty(String name, Formatter defaultValue) { /** * Returns an instance of the logging service. */ - Logging logging() { + Logging getLogging() { if (logging == null) { logging = options.service(); } @@ -306,15 +306,15 @@ private LogEntry entryFor(LogRecord record) { Map labels = ImmutableMap.of( "levelName", level.getName(), "levelValue", String.valueOf(level.intValue())); - return LogEntry.builder(Payload.StringPayload.of(payload)) - .labels(labels) - .severity(severityFor(level)) + return LogEntry.newBuilder(Payload.StringPayload.of(payload)) + .setLabels(labels) + .setSeverity(severityFor(level)) .build(); } private static Severity severityFor(Level level) { if (level instanceof LoggingLevel) { - return ((LoggingLevel) level).severity(); + return ((LoggingLevel) level).getSeverity(); } switch (level.intValue()) { // FINEST @@ -348,7 +348,7 @@ private static Severity severityFor(Level level) { * how entries should be written. */ void write(List entries, WriteOption... options) { - logging().write(entries, options); + getLogging().write(entries, options); } @Override diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingImpl.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingImpl.java index 225aba62ced2..33736bf0c1d5 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingImpl.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingImpl.java @@ -218,7 +218,7 @@ public Sink update(SinkInfo sink) { @Override public Future updateAsync(SinkInfo sink) { UpdateSinkRequest request = UpdateSinkRequest.newBuilder() - .setSinkName(ConfigServiceV2Api.formatSinkName(options().projectId(), sink.name())) + .setSinkName(ConfigServiceV2Api.formatSinkName(options().projectId(), sink.getName())) .setSink(sink.toPb(options().projectId())) .build(); return transform(rpc.update(request), Sink.fromPbFunction(this)); @@ -375,7 +375,8 @@ public Metric update(MetricInfo metric) { @Override public Future updateAsync(MetricInfo metric) { UpdateLogMetricRequest request = UpdateLogMetricRequest.newBuilder() - .setMetricName(MetricsServiceV2Api.formatMetricName(options().projectId(), metric.name())) + .setMetricName(MetricsServiceV2Api.formatMetricName(options().projectId(), + metric.getName())) .setMetric(metric.toPb()) .build(); return transform(rpc.update(request), Metric.fromPbFunction(this)); @@ -542,7 +543,7 @@ public void close() throws Exception { static Map optionMap(Option... options) { Map optionMap = Maps.newHashMap(); for (Option option : options) { - Object prev = optionMap.put(option.optionType(), option.value()); + Object prev = optionMap.put(option.getOptionType(), option.getValue()); checkArgument(prev == null, "Duplicate option %s", option); } return optionMap; diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingLevel.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingLevel.java index 5ed4ae6d84b0..53056993a6d2 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingLevel.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingLevel.java @@ -89,7 +89,15 @@ private LoggingLevel(String name, int value, Severity severity) { /** * Returns the Stackdriver Logging severity associated with this logging level. */ + @Deprecated public Severity severity() { + return getSeverity(); + } + + /** + * Returns the Stackdriver Logging severity associated with this logging level. + */ + public Severity getSeverity() { return severity; } } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Metric.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Metric.java index c5e3e6e00ff4..3be29ef1cd0d 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Metric.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Metric.java @@ -58,20 +58,38 @@ private Builder(Metric metric) { } @Override + @Deprecated public Builder name(String name) { - delegate.name(name); + return setName(name); + } + + @Override + public Builder setName(String name) { + delegate.setName(name); return this; } @Override + @Deprecated public Builder description(String description) { - delegate.description(description); + return setDescription(description); + } + + @Override + public Builder setDescription(String description) { + delegate.setDescription(description); return this; } @Override + @Deprecated public Builder filter(String filter) { - delegate.filter(filter); + return setFilter(filter); + } + + @Override + public Builder setFilter(String filter) { + delegate.setFilter(filter); return this; } @@ -112,7 +130,15 @@ public final boolean equals(Object obj) { /** * Returns the metrics's {@code Logging} object used to issue requests. */ + @Deprecated public Logging logging() { + return getLogging(); + } + + /** + * Returns the metrics's {@code Logging} object used to issue requests. + */ + public Logging getLogging() { return logging; } @@ -133,7 +159,7 @@ public Logging logging() { * @throws LoggingException upon failure */ public boolean delete() { - return logging.deleteMetric(name()); + return logging.deleteMetric(getName()); } /** @@ -156,7 +182,7 @@ public boolean delete() { * @throws LoggingException upon failure */ public Future deleteAsync() { - return logging.deleteMetricAsync(name()); + return logging.deleteMetricAsync(getName()); } /** @@ -174,7 +200,7 @@ public Future deleteAsync() { * @throws LoggingException upon failure */ public Metric reload() { - return logging.getMetric(name()); + return logging.getMetric(getName()); } /** @@ -195,7 +221,7 @@ public Metric reload() { * @throws LoggingException upon failure */ public Future reloadAsync() { - return logging.getMetricAsync(name()); + return logging.getMetricAsync(getName()); } /** @@ -204,7 +230,7 @@ public Future reloadAsync() { *

Example of updating the metric's information. *

 {@code
    * Metric updatedMetric = metric.toBuilder()
-   *     .description("A more detailed description")
+   *     .setDescription("A more detailed description")
    *     .build()
    *     .update();
    * }
@@ -224,7 +250,7 @@ public Metric update() { *

Example of asynchronously updating the metric's information. *

 {@code
    * Future future = metric.toBuilder()
-   *     .description("A more detailed description")
+   *     .setDescription("A more detailed description")
    *     .build()
    *     .updateAsync();
    * // ...
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/MetricInfo.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/MetricInfo.java
index cd0cf58f4d6b..9be96f8d2ce8 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/MetricInfo.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/MetricInfo.java
@@ -51,13 +51,29 @@ public abstract static class Builder {
      * forward-slash character ({@code /}) denotes a hierarchy of name pieces, and it cannot be the
      * first character of the name.
      */
+    @Deprecated
     public abstract Builder name(String name);
 
+    /**
+     * Sets the name of the metric. Example: {@code severe-errors}. Metric identifiers are
+     * limited to 1000 characters and can include only the following characters: {@code A-Z},
+     * {@code a-z}, {@code 0-9}, and the special characters {@code _-.,+!*',()%/\}. The
+     * forward-slash character ({@code /}) denotes a hierarchy of name pieces, and it cannot be the
+     * first character of the name.
+     */
+    public abstract Builder setName(String name);
+
     /**
      * Sets an optional description for this metric. Used for documentation purpose.
      */
+    @Deprecated
     public abstract Builder description(String description);
 
+    /**
+     * Sets an optional description for this metric. Used for documentation purpose.
+     */
+    public abstract Builder setDescription(String description);
+
     /**
      * Sets an advanced logs filter. The value of the metric is the number of log entries that match
      * this filter. Example: {@code logName=projects/my-projectid/logs/syslog AND severity>=ERROR}.
@@ -65,8 +81,18 @@ public abstract static class Builder {
      * @see Advanced Log
      *     Filters
      */
+    @Deprecated
     public abstract Builder filter(String filter);
 
+    /**
+     * Sets an advanced logs filter. The value of the metric is the number of log entries that match
+     * this filter. Example: {@code logName=projects/my-projectid/logs/syslog AND severity>=ERROR}.
+     *
+     * @see Advanced Log
+     *     Filters
+     */
+    public abstract Builder setFilter(String filter);
+
     /**
      * Creates a {@code MetricInfo} object for this builder.
      */
@@ -91,19 +117,37 @@ static final class BuilderImpl extends Builder {
     }
 
     @Override
+    @Deprecated
     public Builder name(String name) {
+      return setName(name);
+    }
+
+    @Override
+    public Builder setName(String name) {
       this.name = name;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder description(String description) {
+      return setDescription(description);
+    }
+
+    @Override
+    public Builder setDescription(String description) {
       this.description = description;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder filter(String filter) {
+      return setFilter(filter);
+    }
+
+    @Override
+    public Builder setFilter(String filter) {
       this.filter = filter;
       return this;
     }
@@ -127,14 +171,34 @@ public MetricInfo build() {
    * forward-slash character ({@code /}) denotes a hierarchy of name pieces, and it cannot be the
    * first character of the name.
    */
+  @Deprecated
   public String name() {
+    return getName();
+  }
+
+  /**
+   * Returns the name of the metric. Example: {@code severe-errors}. Metric identifiers are
+   * limited to 1000 characters and can include only the following characters: {@code A-Z},
+   * {@code a-z}, {@code 0-9}, and the special characters {@code _-.,+!*',()%/\}. The
+   * forward-slash character ({@code /}) denotes a hierarchy of name pieces, and it cannot be the
+   * first character of the name.
+   */
+  public String getName() {
     return name;
   }
 
   /**
    * Returns an optional description for this metric. Used for documentation purpose.
    */
+  @Deprecated
   public String description() {
+    return getDescription();
+  }
+
+  /**
+   * Returns an optional description for this metric. Used for documentation purpose.
+   */
+  public String getDescription() {
     return description;
   }
 
@@ -146,7 +210,20 @@ public String description() {
    * @see Advanced Log
    *     Filters
    */
+  @Deprecated
   public String filter() {
+    return getFilter();
+  }
+
+  /**
+   * Returns an advanced logs filter. The value of the metric is the number of log entries that
+   * match this filter. Example:
+   * {@code logName=projects/my-projectid/logs/syslog AND severity>=ERROR}.
+   *
+   * @see Advanced Log
+   *     Filters
+   */
+  public String getFilter() {
     return filter;
   }
 
@@ -191,7 +268,15 @@ public Builder toBuilder() {
   /**
    * Returns a builder for {@code MetricInfo} objects given the name of the metric and its filter.
    */
+  @Deprecated
   public static Builder builder(String name, String filter) {
+    return newBuilder(name, filter);
+  }
+
+  /**
+   * Returns a builder for {@code MetricInfo} objects given the name of the metric and its filter.
+   */
+  public static Builder newBuilder(String name, String filter) {
     return new BuilderImpl(name, filter);
   }
 
@@ -213,9 +298,9 @@ LogMetric toPb() {
   }
 
   static MetricInfo fromPb(LogMetric metricPb) {
-    Builder builder = builder(metricPb.getName(), metricPb.getFilter());
+    Builder builder = newBuilder(metricPb.getName(), metricPb.getFilter());
     if (!metricPb.getDescription().equals("")) {
-      builder.description(metricPb.getDescription());
+      builder.setDescription(metricPb.getDescription());
     }
     return builder.build();
   }
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Operation.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Operation.java
index f36888895fcd..468f40feb733 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Operation.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Operation.java
@@ -67,7 +67,16 @@ public static final class Builder {
      * Sets the operation identifier. Log entries with the same identifier are assumed to be part
      * of the same operation. The combination of id and producer must be globally unique.
      */
+    @Deprecated
     public Builder id(String id) {
+      return setId(id);
+    }
+
+    /**
+     * Sets the operation identifier. Log entries with the same identifier are assumed to be part
+     * of the same operation. The combination of id and producer must be globally unique.
+     */
+    public Builder setId(String id) {
       this.id = id;
       return this;
     }
@@ -77,7 +86,17 @@ public Builder id(String id) {
      * unique. Examples: {@code MyDivision.MyBigCompany.com},
      * {@code github.com/MyProject/MyApplication}.
      */
+    @Deprecated
     public Builder producer(String producer) {
+      return setProducer(producer);
+    }
+
+    /**
+     * Sets an arbitrary producer identifier. The combination of producer and id must be globally
+     * unique. Examples: {@code MyDivision.MyBigCompany.com},
+     * {@code github.com/MyProject/MyApplication}.
+     */
+    public Builder setProducer(String producer) {
       this.producer = producer;
       return this;
     }
@@ -86,7 +105,16 @@ public Builder producer(String producer) {
      * Sets whether the corresponding entry is the first log entry in the operation. If not set,
      * {@code false} is used.
      */
+    @Deprecated
     public Builder first(boolean first) {
+      return setFirst(first);
+    }
+
+    /**
+     * Sets whether the corresponding entry is the first log entry in the operation. If not set,
+     * {@code false} is used.
+     */
+    public Builder setFirst(boolean first) {
       this.first = first;
       return this;
     }
@@ -95,7 +123,16 @@ public Builder first(boolean first) {
      * Sets whether the corresponding entry is the last log entry in the operation. If not set,
      * {@code false} is used.
      */
+    @Deprecated
     public Builder last(boolean last) {
+      return setLast(last);
+    }
+
+    /**
+     * Sets whether the corresponding entry is the last log entry in the operation. If not set,
+     * {@code false} is used.
+     */
+    public Builder setLast(boolean last) {
       this.last = last;
       return this;
     }
@@ -120,7 +157,17 @@ public Operation build() {
    * of the same operation. The combination of this value and {@link #producer()} must be globally
    * unique.
    */
+  @Deprecated
   public String id() {
+    return getId();
+  }
+
+  /**
+   * Returns the operation identifier. Log entries with the same identifier are assumed to be part
+   * of the same operation. The combination of this value and {@link #producer()} must be globally
+   * unique.
+   */
+  public String getId() {
     return id;
   }
 
@@ -129,7 +176,17 @@ public String id() {
    * must be globally unique. Examples: {@code MyDivision.MyBigCompany.com},
    * {@code github.com/MyProject/MyApplication}.
    */
+  @Deprecated
   public String producer() {
+    return getProducer();
+  }
+
+  /**
+   * Returns an arbitrary producer identifier. The combination of this value and {@link #id()}
+   * must be globally unique. Examples: {@code MyDivision.MyBigCompany.com},
+   * {@code github.com/MyProject/MyApplication}.
+   */
+  public String getProducer() {
     return producer;
   }
 
@@ -199,7 +256,16 @@ LogEntryOperation toPb() {
    * Returns a builder for {@code Operation} objects given the operation and producer identifiers.
    * The combination of producer and id must be globally unique.
    */
+  @Deprecated
   public static Builder builder(String id, String producer) {
+    return newBuilder(id, producer);
+  }
+
+  /**
+   * Returns a builder for {@code Operation} objects given the operation and producer identifiers.
+   * The combination of producer and id must be globally unique.
+   */
+  public static Builder newBuilder(String id, String producer) {
     return new Builder(id, producer);
   }
 
@@ -208,13 +274,13 @@ public static Builder builder(String id, String producer) {
    * combination of producer and id must be globally unique.
    */
   public static Operation of(String id, String producer) {
-    return builder(id, producer).build();
+    return newBuilder(id, producer).build();
   }
 
   static Operation fromPb(LogEntryOperation operationPb) {
-    return builder(operationPb.getId(), operationPb.getProducer())
-        .first(operationPb.getFirst())
-        .last(operationPb.getLast())
+    return newBuilder(operationPb.getId(), operationPb.getProducer())
+        .setFirst(operationPb.getFirst())
+        .setLast(operationPb.getLast())
         .build();
   }
 }
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Option.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Option.java
index 2e36d65fc4cd..6315ac8c8cde 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Option.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Option.java
@@ -43,11 +43,11 @@ interface OptionType {
   }
 
   @SuppressWarnings("unchecked")
-   T optionType() {
+   T getOptionType() {
     return (T) optionType;
   }
 
-  Object value() {
+  Object getValue() {
     return value;
   }
 
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Payload.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Payload.java
index 48510619db0b..c7b6a8a20f43 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Payload.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Payload.java
@@ -71,7 +71,7 @@ public static final class StringPayload extends Payload {
 
     @Override
     com.google.logging.v2.LogEntry.Builder toPb() {
-      return com.google.logging.v2.LogEntry.newBuilder().setTextPayload(data());
+      return com.google.logging.v2.LogEntry.newBuilder().setTextPayload(getData());
     }
 
     /**
@@ -100,13 +100,21 @@ public static final class JsonPayload extends Payload {
     /**
      * Returns the log entry's JSON data as an unmodifiable map.
      */
-    public Map dataAsMap() {
-      return Structs.asMap(data());
+    @Deprecated
+    public Map dataAsMap() {
+      return getDataAsMap();
+    }
+
+    /**
+     * Returns the log entry's JSON data as an unmodifiable map.
+     */
+    public Map getDataAsMap() {
+      return Structs.asMap(getData());
     }
 
     @Override
     com.google.logging.v2.LogEntry.Builder toPb() {
-      return com.google.logging.v2.LogEntry.newBuilder().setJsonPayload(data());
+      return com.google.logging.v2.LogEntry.newBuilder().setJsonPayload(getData());
     }
 
     /**
@@ -131,7 +139,7 @@ com.google.logging.v2.LogEntry.Builder toPb() {
      *   JsonPayload payload = JsonPayload.of(jsonContent);
      * }
*/ - public static JsonPayload of(Map data) { + public static JsonPayload of(Map data) { return new JsonPayload(Structs.newStruct(data)); } @@ -160,7 +168,7 @@ public static final class ProtoPayload extends Payload { @Override com.google.logging.v2.LogEntry.Builder toPb() { - return com.google.logging.v2.LogEntry.newBuilder().setProtoPayload(data()); + return com.google.logging.v2.LogEntry.newBuilder().setProtoPayload(getData()); } /** @@ -184,14 +192,31 @@ private Payload(Type type, T data) { * Returns the payload type. Payload can be an UTF-8 string ({@link Type#STRING}), a JSON object * ({@link Type#JSON}) or a protobuf object ({@link Type#PROTO}). */ + @Deprecated public Type type() { + return getType(); + } + + /** + * Returns the payload type. Payload can be an UTF-8 string ({@link Type#STRING}), a JSON object + * ({@link Type#JSON}) or a protobuf object ({@link Type#PROTO}). + */ + public Type getType() { return type; } /** * Returns the log entry payload's data. */ + @Deprecated public T data() { + return getData(); + } + + /** + * Returns the log entry payload's data. + */ + public T getData() { return data; } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Sink.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Sink.java index 4a2aede6b62a..5ebac1896896 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Sink.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Sink.java @@ -64,26 +64,50 @@ private Builder(Sink sink) { } @Override + @Deprecated public Builder name(String name) { - delegate.name(name); + return setName(name); + } + + @Override + public Builder setName(String name) { + delegate.setName(name); return this; } @Override + @Deprecated public Builder destination(Destination destination) { - delegate.destination(destination); + return setDestination(destination); + } + + @Override + public Builder setDestination(Destination destination) { + delegate.setDestination(destination); return this; } @Override + @Deprecated public Builder filter(String filter) { - delegate.filter(filter); + return setFilter(filter); + } + + @Override + public Builder setFilter(String filter) { + delegate.setFilter(filter); return this; } @Override + @Deprecated public Builder versionFormat(VersionFormat versionFormat) { - delegate.versionFormat(versionFormat); + return setVersionFormat(versionFormat); + } + + @Override + public Builder setVersionFormat(VersionFormat versionFormat) { + delegate.setVersionFormat(versionFormat); return this; } @@ -124,7 +148,15 @@ public final boolean equals(Object obj) { /** * Returns the sinks's {@code Logging} object used to issue requests. */ + @Deprecated public Logging logging() { + return getLogging(); + } + + /** + * Returns the sinks's {@code Logging} object used to issue requests. + */ + public Logging getLogging() { return logging; } @@ -145,7 +177,7 @@ public Logging logging() { * @throws LoggingException upon failure */ public boolean delete() { - return logging.deleteSink(name()); + return logging.deleteSink(getName()); } /** @@ -168,7 +200,7 @@ public boolean delete() { * @throws LoggingException upon failure */ public Future deleteAsync() { - return logging.deleteSinkAsync(name()); + return logging.deleteSinkAsync(getName()); } /** @@ -186,7 +218,7 @@ public Future deleteAsync() { * @throws LoggingException upon failure */ public Sink reload() { - return logging.getSink(name()); + return logging.getSink(getName()); } /** @@ -207,7 +239,7 @@ public Sink reload() { * @throws LoggingException upon failure */ public Future reloadAsync() { - return logging.getSinkAsync(name()); + return logging.getSinkAsync(getName()); } /** @@ -216,7 +248,7 @@ public Future reloadAsync() { *

Example of updating the sink's information. *

 {@code
    * Sink updatedSink = sink.toBuilder()
-   *     .filter("severity<=ERROR")
+   *     .setFilter("severity<=ERROR")
    *     .build()
    *     .update();
    * }
@@ -236,7 +268,7 @@ public Sink update() { *

Example of asynchronously updating the sink's information. *

 {@code
    * Future future = sink.toBuilder()
-   *     .filter("severity<=ERROR")
+   *     .setFilter("severity<=ERROR")
    *     .build()
    *     .updateAsync();
    * // ...
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/SinkInfo.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/SinkInfo.java
index c2669ac07bae..af218c2b3a11 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/SinkInfo.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/SinkInfo.java
@@ -95,7 +95,15 @@ public static final class BucketDestination extends Destination {
       /**
        * Returns the name of the Google Cloud Storage bucket this destination represents.
        */
+      @Deprecated
       public String bucket() {
+        return getBucket();
+      }
+
+      /**
+       * Returns the name of the Google Cloud Storage bucket this destination represents.
+       */
+      public String getBucket() {
         return bucket;
       }
 
@@ -171,14 +179,31 @@ public static final class DatasetDestination extends Destination {
        * Returns the name of the project where the Google Cloud BigQuery dataset resides. If
        * {@code null}, the default project is used.
        */
+      @Deprecated
       public String project() {
+        return getProject();
+      }
+
+      /**
+       * Returns the name of the project where the Google Cloud BigQuery dataset resides. If
+       * {@code null}, the default project is used.
+       */
+      public String getProject() {
         return project;
       }
 
       /**
        * Returns the name of the Google Cloud BigQuery dataset this destination represents.
        */
+      @Deprecated
       public String dataset() {
+        return getDataset();
+      }
+
+      /**
+       * Returns the name of the Google Cloud BigQuery dataset this destination represents.
+       */
+      public String getDataset() {
         return dataset;
       }
 
@@ -267,14 +292,31 @@ public static final class TopicDestination extends Destination {
        * Returns the name of the project where the Google Cloud Pub/Sub topic resides. If
        * {@code null}, the default project is used.
        */
+      @Deprecated
       public String project() {
+        return getProject();
+      }
+
+      /**
+       * Returns the name of the project where the Google Cloud Pub/Sub topic resides. If
+       * {@code null}, the default project is used.
+       */
+      public String getProject() {
         return project;
       }
 
       /**
        * Returns the name of the Google Cloud Pub/Sub topic this destination represents.
        */
+      @Deprecated
       public String topic() {
+        return getTopic();
+      }
+
+      /**
+       * Returns the name of the Google Cloud Pub/Sub topic this destination represents.
+       */
+      public String getTopic() {
         return topic;
       }
 
@@ -347,7 +389,15 @@ static TopicDestination fromPb(String destinationPb) {
     /**
      * Returns the type of this destination.
      */
+    @Deprecated
     public Type type() {
+      return getType();
+    }
+
+    /**
+     * Returns the type of this destination.
+     */
+    public Type getType() {
       return type;
     }
 
@@ -416,8 +466,16 @@ public abstract static class Builder {
      * limited to 1000 characters and can include only the following characters: {@code A-Z},
      * {@code a-z}, {@code 0-9}, and the special characters {@code _-.}.
      */
+    @Deprecated
     public abstract Builder name(String name);
 
+    /**
+     * Sets the name of the sink. Example: {@code my-severe-errors-to-pubsub}. Sink identifiers are
+     * limited to 1000 characters and can include only the following characters: {@code A-Z},
+     * {@code a-z}, {@code 0-9}, and the special characters {@code _-.}.
+     */
+    public abstract Builder setName(String name);
+
     /**
      * Sets the export destination. Use a {@link Destination.BucketDestination} object to create a
      * sink that exports logs to a Google Cloud Storage bucket. Use a
@@ -428,8 +486,21 @@ public abstract static class Builder {
      * @see 
      *     Exporting Logs
      */
+    @Deprecated
     public abstract Builder destination(Destination destination);
 
+    /**
+     * Sets the export destination. Use a {@link Destination.BucketDestination} object to create a
+     * sink that exports logs to a Google Cloud Storage bucket. Use a
+     * {@link Destination.DatasetDestination} object to create a sink that exports logs to a Google
+     * Cloud BigQuery dataset. Use a {@link Destination.TopicDestination} object to create a sink
+     * that exports logs to a Google Cloud Pub/Sub topic.
+     *
+     * @see 
+     *     Exporting Logs
+     */
+    public abstract Builder setDestination(Destination destination);
+
     /**
      * Sets an advanced logs filter. Only log entries matching that filter are exported. The filter
      * must be consistent with the log entry format specified with
@@ -440,15 +511,36 @@ public abstract static class Builder {
      * @see Advanced Log
      *     Filters
      */
+    @Deprecated
     public abstract Builder filter(String filter);
 
+    /**
+     * Sets an advanced logs filter. Only log entries matching that filter are exported. The filter
+     * must be consistent with the log entry format specified with
+     * {@link #versionFormat(VersionFormat)}, regardless of the format of the log entry that was
+     * originally written to Stackdriver Logging. Example (V2 format):
+     * {@code logName=projects/my-projectid/logs/syslog AND severity>=ERROR}.
+     *
+     * @see Advanced Log
+     *     Filters
+     */
+    public abstract Builder setFilter(String filter);
+
     /**
      * Sets the log entry version to use for this sink's exported log entries. This version does
      * not have to correspond to the version of the log entry when it was written to Google Cloud
      * Logging.
      */
+    @Deprecated
     public abstract Builder versionFormat(VersionFormat versionFormat);
 
+    /**
+     * Sets the log entry version to use for this sink's exported log entries. This version does
+     * not have to correspond to the version of the log entry when it was written to Google Cloud
+     * Logging.
+     */
+    public abstract Builder setVersionFormat(VersionFormat versionFormat);
+
     /**
      * Creates a {@code SinkInfo} object for this builder.
      */
@@ -475,25 +567,49 @@ static final class BuilderImpl extends Builder {
     }
 
     @Override
+    @Deprecated
     public Builder name(String name) {
+      return setName(name);
+    }
+
+    @Override
+    public Builder setName(String name) {
       this.name = name;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder destination(Destination destination) {
+      return setDestination(destination);
+    }
+
+    @Override
+    public Builder setDestination(Destination destination) {
       this.destination = destination;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder filter(String filter) {
+      return setFilter(filter);
+    }
+
+    @Override
+    public Builder setFilter(String filter) {
       this.filter = filter;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder versionFormat(VersionFormat versionFormat) {
+      return setVersionFormat(versionFormat);
+    }
+
+    @Override
+    public Builder setVersionFormat(VersionFormat versionFormat) {
       this.versionFormat = versionFormat;
       return this;
     }
@@ -516,7 +632,17 @@ public SinkInfo build() {
    * limited to 1000 characters and can include only the following characters: {@code A-Z},
    * {@code a-z}, {@code 0-9}, and the special characters {@code _-.}.
    */
+  @Deprecated
   public String name() {
+    return getName();
+  }
+
+  /**
+   * Returns the name of the sink. Example: {@code my-severe-errors-to-pubsub}. Sink identifiers are
+   * limited to 1000 characters and can include only the following characters: {@code A-Z},
+   * {@code a-z}, {@code 0-9}, and the special characters {@code _-.}.
+   */
+  public String getName() {
     return name;
   }
 
@@ -531,7 +657,23 @@ public String name() {
    *     Exporting Logs
    */
   @SuppressWarnings("unchecked")
+  @Deprecated
   public  T destination() {
+    return getDestination();
+  }
+
+  /**
+   * Returns the export destination. This method returns a {@link Destination.BucketDestination} for
+   * sinks that export logs to Google Cloud Storage buckets. Returns
+   * {@link Destination.DatasetDestination} for sinks that export logs to Google Cloud BigQuery
+   * datasets. Returns {@link Destination.TopicDestination} for sinks that export logs to Google
+   * Cloud Pub/Sub topics.
+   *
+   * @see 
+   *     Exporting Logs
+   */
+  @SuppressWarnings("unchecked")
+  public  T getDestination() {
     return (T) destination;
   }
 
@@ -544,7 +686,21 @@ public  T destination() {
    * @see Advanced Log
    *     Filters
    */
+  @Deprecated
   public String filter() {
+    return getFilter();
+  }
+
+  /**
+   * Returns an advanced logs filter. Only log entries matching that filter are exported. The filter
+   * must be consistent with the log entry format specified in {@link #versionFormat()}, regardless
+   * of the format of the log entry that wa originally written to Stackdriver Logging. Example (V2
+   * format): {@code logName=projects/my-projectid/logs/syslog AND severity>=ERROR}.
+   *
+   * @see Advanced Log
+   *     Filters
+   */
+  public String getFilter() {
     return filter;
   }
 
@@ -553,7 +709,17 @@ public String filter() {
    * not have to correspond to the version of the log entry when it was written to Google Cloud
    * Logging.
    */
+  @Deprecated
   public VersionFormat versionFormat() {
+    return getVersionFormat();
+  }
+
+  /**
+   * Returns the log entry version to use for this sink's exported log entries. This version does
+   * not have to correspond to the version of the log entry when it was written to Google Cloud
+   * Logging.
+   */
+  public VersionFormat getVersionFormat() {
     return versionFormat;
   }
 
@@ -600,7 +766,15 @@ public Builder toBuilder() {
   /**
    * Returns a builder for {@code SinkInfo} objects given the name of the sink and its destination.
    */
+  @Deprecated
   public static Builder builder(String name, Destination destination) {
+    return newBuilder(name, destination);
+  }
+
+  /**
+   * Returns a builder for {@code SinkInfo} objects given the name of the sink and its destination.
+   */
+  public static Builder newBuilder(String name, Destination destination) {
     return new BuilderImpl(name, destination);
   }
 
@@ -624,11 +798,11 @@ LogSink toPb(String projectId) {
   }
 
   static SinkInfo fromPb(LogSink sinkPb) {
-    Builder builder = builder(sinkPb.getName(),
+    Builder builder = newBuilder(sinkPb.getName(),
         Destination.fromPb(sinkPb.getDestination()))
-        .versionFormat(VersionFormat.fromPb(sinkPb.getOutputVersionFormat()));
+        .setVersionFormat(VersionFormat.fromPb(sinkPb.getOutputVersionFormat()));
     if (!sinkPb.getFilter().equals("")) {
-      builder.filter(sinkPb.getFilter());
+      builder.setFilter(sinkPb.getFilter());
     }
     return builder.build();
   }
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Structs.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Structs.java
index 1e77cbd7c916..52605c739f5c 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Structs.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Structs.java
@@ -86,12 +86,12 @@ private StructSet(Struct struct) {
 
       @Override
       public Iterator> iterator() {
-        return Iterators.transform(struct.getFields().entrySet().iterator(), VALUE_TO_OBJECT);
+        return Iterators.transform(struct.getFieldsMap().entrySet().iterator(), VALUE_TO_OBJECT);
       }
 
       @Override
       public int size() {
-        return struct.getFields().size();
+        return struct.getFieldsMap().size();
       }
     }
 
@@ -114,7 +114,7 @@ static Map asMap(Struct struct) {
    * 

Notice that all numbers (int, long, float and double) are serialized as double values. * Enums are serialized as strings. */ - static Struct newStruct(Map map) { + static Struct newStruct(Map map) { Map valueMap = Maps.transformValues(checkNotNull(map), OBJECT_TO_VALUE); return Struct.newBuilder().putAllFields(valueMap).build(); } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/package-info.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/package-info.java index 244533e69a21..ab456dc1c615 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/package-info.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/package-info.java @@ -25,9 +25,9 @@ * LoggingOptions options = LoggingOptions.defaultInstance(); * try(Logging logging = options.service()) { * - * LogEntry firstEntry = LogEntry.builder(StringPayload.of("message")) - * .logName("test-log") - * .resource(MonitoredResource.builder("global") + * LogEntry firstEntry = LogEntry.newBuilder(StringPayload.of("message")) + * .setLogName("test-log") + * .setResource(MonitoredResource.builder("global") * .addLabel("project_id", options.projectId()) * .build()) * .build(); diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java index 48b7c183d5a8..65bb9bfaa0d7 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java @@ -28,8 +28,8 @@ /** * Utility to create a remote logging configuration for testing. Logging options can be obtained via - * the {@link #options()} method. Returned options have custom {@link LoggingOptions#retryParams()}: - * {@link RetryParams#maxRetryDelayMillis()} is {@code 30000}, + * the {@link #getOptions()} method. Returned options have custom + * {@link LoggingOptions#retryParams()}: {@link RetryParams#maxRetryDelayMillis()} is {@code 30000}, * {@link RetryParams#totalRetryPeriodMillis()} is {@code 120000} and * {@link RetryParams#initialRetryDelayMillis()} is {@code 250}. * {@link LoggingOptions#initialTimeout()} is set to 60000, {@link LoggingOptions#maxTimeout()} is @@ -47,7 +47,15 @@ private RemoteLoggingHelper(LoggingOptions options) { /** * Returns a {@link LoggingOptions} object to be used for testing. */ + @Deprecated public LoggingOptions options() { + return getOptions(); + } + + /** + * Returns a {@link LoggingOptions} object to be used for testing. + */ + public LoggingOptions getOptions() { return options; } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/package-info.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/package-info.java index 59ac80ff542f..3c765aab6095 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/package-info.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/package-info.java @@ -22,7 +22,7 @@ *

Before the test: *

 {@code
  * RemoteLoggingHelper helper = RemoteLoggingHelper.create();
- * Logging logging = helper.options().service();
+ * Logging logging = helper.getOptions().service();
  * } 
* *

Format resource names to avoid name clashes: diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/AsyncLoggingHandlerTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/AsyncLoggingHandlerTest.java index b10d649bdf2d..e555a6b3cbe3 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/AsyncLoggingHandlerTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/AsyncLoggingHandlerTest.java @@ -61,8 +61,8 @@ public void afterClass() { public void testPublish() { EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); EasyMock.expect(options.service()).andReturn(logging); - LogEntry entry = LogEntry.builder(Payload.StringPayload.of(MESSAGE)) - .severity(Severity.DEBUG) + LogEntry entry = LogEntry.newBuilder(Payload.StringPayload.of(MESSAGE)) + .setSeverity(Severity.DEBUG) .addLabel("levelName", "FINEST") .addLabel("levelValue", String.valueOf(Level.FINEST.intValue())) .build(); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java index 2d1dff31026c..eb523b0dddcf 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java @@ -90,25 +90,25 @@ public abstract class BaseSystemTest { @Test public void testCreateGetUpdateAndDeleteSink() { String name = formatForTest("test-create-get-update-sink"); - SinkInfo sinkInfo = SinkInfo.builder(name, DatasetDestination.of("dataset")) - .filter("severity>=ERROR") - .versionFormat(SinkInfo.VersionFormat.V2) + SinkInfo sinkInfo = SinkInfo.newBuilder(name, DatasetDestination.of("dataset")) + .setFilter("severity>=ERROR") + .setVersionFormat(SinkInfo.VersionFormat.V2) .build(); Sink sink = logging().create(sinkInfo); - assertEquals(name, sink.name()); - assertEquals(SinkInfo.VersionFormat.V2, sink.versionFormat()); - assertEquals("severity>=ERROR", sink.filter()); - DatasetDestination datasetDestination = sink.destination(); - assertEquals(logging().options().projectId(), datasetDestination.project()); - assertEquals("dataset", datasetDestination.dataset()); + assertEquals(name, sink.getName()); + assertEquals(SinkInfo.VersionFormat.V2, sink.getVersionFormat()); + assertEquals("severity>=ERROR", sink.getFilter()); + DatasetDestination datasetDestination = sink.getDestination(); + assertEquals(logging().options().projectId(), datasetDestination.getProject()); + assertEquals("dataset", datasetDestination.getDataset()); assertEquals(sink, logging().getSink(name)); sink = sink.toBuilder() - .filter("severity<=ERROR") + .setFilter("severity<=ERROR") .build() .update(); - assertEquals(name, sink.name()); - assertEquals(SinkInfo.VersionFormat.V2, sink.versionFormat()); - assertEquals("severity<=ERROR", sink.filter()); + assertEquals(name, sink.getName()); + assertEquals(SinkInfo.VersionFormat.V2, sink.getVersionFormat()); + assertEquals("severity<=ERROR", sink.getFilter()); assertTrue(sink.delete()); assertFalse(sink.delete()); } @@ -117,25 +117,25 @@ public void testCreateGetUpdateAndDeleteSink() { public void testCreateGetUpdateAndDeleteSinkAsync() throws ExecutionException, InterruptedException { String name = formatForTest("test-create-get-update-sink-async"); - SinkInfo sinkInfo = SinkInfo.builder(name, DatasetDestination.of("dataset")) - .filter("severity>=ERROR") - .versionFormat(SinkInfo.VersionFormat.V2) + SinkInfo sinkInfo = SinkInfo.newBuilder(name, DatasetDestination.of("dataset")) + .setFilter("severity>=ERROR") + .setVersionFormat(SinkInfo.VersionFormat.V2) .build(); Sink sink = logging().createAsync(sinkInfo).get(); - assertEquals(name, sink.name()); - assertEquals(SinkInfo.VersionFormat.V2, sink.versionFormat()); - assertEquals("severity>=ERROR", sink.filter()); - DatasetDestination datasetDestination = sink.destination(); - assertEquals(logging().options().projectId(), datasetDestination.project()); - assertEquals("dataset", datasetDestination.dataset()); + assertEquals(name, sink.getName()); + assertEquals(SinkInfo.VersionFormat.V2, sink.getVersionFormat()); + assertEquals("severity>=ERROR", sink.getFilter()); + DatasetDestination datasetDestination = sink.getDestination(); + assertEquals(logging().options().projectId(), datasetDestination.getProject()); + assertEquals("dataset", datasetDestination.getDataset()); assertEquals(sink, logging().getSinkAsync(name).get()); sink = sink.toBuilder() - .filter("severity<=ERROR") + .setFilter("severity<=ERROR") .build() .updateAsync().get(); - assertEquals(name, sink.name()); - assertEquals(SinkInfo.VersionFormat.V2, sink.versionFormat()); - assertEquals("severity<=ERROR", sink.filter()); + assertEquals(name, sink.getName()); + assertEquals(SinkInfo.VersionFormat.V2, sink.getVersionFormat()); + assertEquals("severity<=ERROR", sink.getFilter()); assertTrue(sink.deleteAsync().get()); assertFalse(sink.deleteAsync().get()); } @@ -143,36 +143,36 @@ public void testCreateGetUpdateAndDeleteSinkAsync() @Test public void testUpdateNonExistingSink() { String name = formatForTest("test-update-non-existing-sink"); - SinkInfo sinkInfo = SinkInfo.builder(name, DatasetDestination.of("dataset")) - .filter("severity>=ERROR") - .versionFormat(SinkInfo.VersionFormat.V2) + SinkInfo sinkInfo = SinkInfo.newBuilder(name, DatasetDestination.of("dataset")) + .setFilter("severity>=ERROR") + .setVersionFormat(SinkInfo.VersionFormat.V2) .build(); assertNull(logging().getSink(name)); Sink sink = logging().update(sinkInfo); - assertEquals(name, sink.name()); - assertEquals(SinkInfo.VersionFormat.V2, sink.versionFormat()); - assertEquals("severity>=ERROR", sink.filter()); - DatasetDestination datasetDestination = sink.destination(); - assertEquals(logging().options().projectId(), datasetDestination.project()); - assertEquals("dataset", datasetDestination.dataset()); + assertEquals(name, sink.getName()); + assertEquals(SinkInfo.VersionFormat.V2, sink.getVersionFormat()); + assertEquals("severity>=ERROR", sink.getFilter()); + DatasetDestination datasetDestination = sink.getDestination(); + assertEquals(logging().options().projectId(), datasetDestination.getProject()); + assertEquals("dataset", datasetDestination.getDataset()); assertTrue(logging().deleteSink(name)); } @Test public void testUpdateNonExistingSinkAsync() throws ExecutionException, InterruptedException { String name = formatForTest("test-update-non-existing-sink-async"); - SinkInfo sinkInfo = SinkInfo.builder(name, DatasetDestination.of("dataset")) - .filter("severity>=ERROR") - .versionFormat(SinkInfo.VersionFormat.V2) + SinkInfo sinkInfo = SinkInfo.newBuilder(name, DatasetDestination.of("dataset")) + .setFilter("severity>=ERROR") + .setVersionFormat(SinkInfo.VersionFormat.V2) .build(); assertNull(logging().getSinkAsync(name).get()); Sink sink = logging().updateAsync(sinkInfo).get(); - assertEquals(name, sink.name()); - assertEquals(SinkInfo.VersionFormat.V2, sink.versionFormat()); - assertEquals("severity>=ERROR", sink.filter()); - DatasetDestination datasetDestination = sink.destination(); - assertEquals(logging().options().projectId(), datasetDestination.project()); - assertEquals("dataset", datasetDestination.dataset()); + assertEquals(name, sink.getName()); + assertEquals(SinkInfo.VersionFormat.V2, sink.getVersionFormat()); + assertEquals("severity>=ERROR", sink.getFilter()); + DatasetDestination datasetDestination = sink.getDestination(); + assertEquals(logging().options().projectId(), datasetDestination.getProject()); + assertEquals("dataset", datasetDestination.getDataset()); assertTrue(logging().deleteSinkAsync(name).get()); } @@ -216,7 +216,7 @@ public void testListMonitoredResourceDescriptors() { logging().listMonitoredResourceDescriptors(Logging.ListOption.pageSize(1)).iterateAll(); Set descriptorTypes = new HashSet<>(); while (iterator.hasNext()) { - descriptorTypes.add(iterator.next().type()); + descriptorTypes.add(iterator.next().getType()); } for (String type : DESCRIPTOR_TYPES) { assertTrue(descriptorTypes.contains(type)); @@ -230,7 +230,7 @@ public void testListMonitoredResourceDescriptorsAsync() .listMonitoredResourceDescriptorsAsync(Logging.ListOption.pageSize(1)).get().iterateAll(); Set descriptorTypes = new HashSet<>(); while (iterator.hasNext()) { - descriptorTypes.add(iterator.next().type()); + descriptorTypes.add(iterator.next().getType()); } for (String type : DESCRIPTOR_TYPES) { assertTrue(descriptorTypes.contains(type)); @@ -240,22 +240,22 @@ public void testListMonitoredResourceDescriptorsAsync() @Test public void testCreateGetUpdateAndDeleteMetric() { String name = formatForTest("test-create-get-update-metric"); - MetricInfo metricInfo = MetricInfo.builder(name, "severity>=ERROR") - .description("description") + MetricInfo metricInfo = MetricInfo.newBuilder(name, "severity>=ERROR") + .setDescription("description") .build(); Metric metric = logging().create(metricInfo); - assertEquals(name, metric.name()); - assertEquals("severity>=ERROR", metric.filter()); - assertEquals("description", metric.description()); + assertEquals(name, metric.getName()); + assertEquals("severity>=ERROR", metric.getFilter()); + assertEquals("description", metric.getDescription()); assertEquals(metric, logging().getMetric(name)); metric = metric.toBuilder() - .description("newDescription") - .filter("severity>=WARNING") + .setDescription("newDescription") + .setFilter("severity>=WARNING") .build() .update(); - assertEquals(name, metric.name()); - assertEquals("severity>=WARNING", metric.filter()); - assertEquals("newDescription", metric.description()); + assertEquals(name, metric.getName()); + assertEquals("severity>=WARNING", metric.getFilter()); + assertEquals("newDescription", metric.getDescription()); assertTrue(metric.delete()); assertFalse(metric.delete()); } @@ -264,22 +264,22 @@ public void testCreateGetUpdateAndDeleteMetric() { public void testCreateGetUpdateAndDeleteMetricAsync() throws ExecutionException, InterruptedException { String name = formatForTest("test-create-get-update-metric-async"); - MetricInfo metricInfo = MetricInfo.builder(name, "severity>=ERROR") - .description("description") + MetricInfo metricInfo = MetricInfo.newBuilder(name, "severity>=ERROR") + .setDescription("description") .build(); Metric metric = logging().createAsync(metricInfo).get(); - assertEquals(name, metric.name()); - assertEquals("severity>=ERROR", metric.filter()); - assertEquals("description", metric.description()); + assertEquals(name, metric.getName()); + assertEquals("severity>=ERROR", metric.getFilter()); + assertEquals("description", metric.getDescription()); assertEquals(metric, logging().getMetricAsync(name).get()); metric = metric.toBuilder() - .description("newDescription") - .filter("severity>=WARNING") + .setDescription("newDescription") + .setFilter("severity>=WARNING") .build() .updateAsync().get(); - assertEquals(name, metric.name()); - assertEquals("severity>=WARNING", metric.filter()); - assertEquals("newDescription", metric.description()); + assertEquals(name, metric.getName()); + assertEquals("severity>=WARNING", metric.getFilter()); + assertEquals("newDescription", metric.getDescription()); assertTrue(metric.deleteAsync().get()); assertFalse(metric.deleteAsync().get()); } @@ -287,28 +287,28 @@ public void testCreateGetUpdateAndDeleteMetricAsync() @Test public void testUpdateNonExistingMetric() { String name = formatForTest("test-update-non-existing-metric"); - MetricInfo metricInfo = MetricInfo.builder(name, "severity>=ERROR") - .description("description") + MetricInfo metricInfo = MetricInfo.newBuilder(name, "severity>=ERROR") + .setDescription("description") .build(); assertNull(logging().getMetric(name)); Metric metric = logging().update(metricInfo); - assertEquals(name, metric.name()); - assertEquals("severity>=ERROR", metric.filter()); - assertEquals("description", metric.description()); + assertEquals(name, metric.getName()); + assertEquals("severity>=ERROR", metric.getFilter()); + assertEquals("description", metric.getDescription()); assertTrue(metric.delete()); } @Test public void testUpdateNonExistingMetricAsync() throws ExecutionException, InterruptedException { String name = formatForTest("test-update-non-existing-metric-async"); - MetricInfo metricInfo = MetricInfo.builder(name, "severity>=ERROR") - .description("description") + MetricInfo metricInfo = MetricInfo.newBuilder(name, "severity>=ERROR") + .setDescription("description") .build(); assertNull(logging().getMetricAsync(name).get()); Metric metric = logging().updateAsync(metricInfo).get(); - assertEquals(name, metric.name()); - assertEquals("severity>=ERROR", metric.filter()); - assertEquals("description", metric.description()); + assertEquals(name, metric.getName()); + assertEquals("severity>=ERROR", metric.getFilter()); + assertEquals("description", metric.getDescription()); assertTrue(metric.deleteAsync().get()); } @@ -351,19 +351,19 @@ public void testWriteAndListLogEntries() throws InterruptedException { String logName = formatForTest("test-write-log-entries-log"); String filter = "logName = projects/" + logging().options().projectId() + "/logs/" + logName; StringPayload firstPayload = StringPayload.of("stringPayload"); - LogEntry firstEntry = LogEntry.builder(firstPayload) + LogEntry firstEntry = LogEntry.newBuilder(firstPayload) .addLabel("key1", "value1") - .logName(logName) - .httpRequest(HttpRequest.builder().status(500).build()) - .resource(MonitoredResource.builder("global").build()) + .setLogName(logName) + .setHttpRequest(HttpRequest.newBuilder().setStatus(500).build()) + .setResource(MonitoredResource.newBuilder("global").build()) .build(); JsonPayload secondPayload = JsonPayload.of(ImmutableMap.of("jsonKey", "jsonValue")); - LogEntry secondEntry = LogEntry.builder(secondPayload) + LogEntry secondEntry = LogEntry.newBuilder(secondPayload) .addLabel("key2", "value2") - .logName(logName) - .operation(Operation.of("operationId", "operationProducer")) - .resource(MonitoredResource.builder("cloudsql_database").build()) + .setLogName(logName) + .setOperation(Operation.of("operationId", "operationProducer")) + .setResource(MonitoredResource.newBuilder("cloudsql_database").build()) .build(); logging().write(ImmutableList.of(firstEntry)); logging().write(ImmutableList.of(secondEntry)); @@ -376,32 +376,32 @@ public void testWriteAndListLogEntries() throws InterruptedException { Iterator iterator = page.iterateAll(); assertTrue(iterator.hasNext()); LogEntry entry = iterator.next(); - assertEquals(firstPayload, entry.payload()); - assertEquals(logName, entry.logName()); - assertEquals(ImmutableMap.of("key1", "value1"), entry.labels()); - assertEquals("global", entry.resource().type()); - assertEquals(HttpRequest.builder().status(500).build(), entry.httpRequest()); - assertEquals(Severity.DEFAULT, entry.severity()); - assertNull(entry.operation()); - assertNotNull(entry.insertId()); - assertNotNull(entry.timestamp()); + assertEquals(firstPayload, entry.getPayload()); + assertEquals(logName, entry.getLogName()); + assertEquals(ImmutableMap.of("key1", "value1"), entry.getLabels()); + assertEquals("global", entry.getResource().getType()); + assertEquals(HttpRequest.newBuilder().setStatus(500).build(), entry.getHttpRequest()); + assertEquals(Severity.DEFAULT, entry.getSeverity()); + assertNull(entry.getOperation()); + assertNotNull(entry.getInsertId()); + assertNotNull(entry.getTimestamp()); assertTrue(iterator.hasNext()); entry = iterator.next(); - assertEquals(secondPayload, entry.payload()); - assertEquals(logName, entry.logName()); - assertEquals(ImmutableMap.of("key2", "value2"), entry.labels()); - assertEquals("cloudsql_database", entry.resource().type()); - assertEquals(Operation.of("operationId", "operationProducer"), entry.operation()); - assertEquals(Severity.DEFAULT, entry.severity()); - assertNull(entry.httpRequest()); - assertNotNull(entry.insertId()); - assertNotNull(entry.timestamp()); + assertEquals(secondPayload, entry.getPayload()); + assertEquals(logName, entry.getLogName()); + assertEquals(ImmutableMap.of("key2", "value2"), entry.getLabels()); + assertEquals("cloudsql_database", entry.getResource().getType()); + assertEquals(Operation.of("operationId", "operationProducer"), entry.getOperation()); + assertEquals(Severity.DEFAULT, entry.getSeverity()); + assertNull(entry.getHttpRequest()); + assertNotNull(entry.getInsertId()); + assertNotNull(entry.getTimestamp()); page = logging().listLogEntries(EntryListOption.filter(filter), EntryListOption.sortOrder(SortingField.TIMESTAMP, SortingOrder.DESCENDING)); iterator = page.iterateAll(); - Long lastTimestamp = iterator.next().timestamp(); + Long lastTimestamp = iterator.next().getTimestamp(); while (iterator.hasNext()) { - assertTrue(iterator.next().timestamp() <= lastTimestamp); + assertTrue(iterator.next().getTimestamp() <= lastTimestamp); } assertTrue(logging().deleteLog(logName)); } @@ -411,13 +411,13 @@ public void testWriteAndListLogEntriesAsync() throws InterruptedException, Execu String logName = formatForTest("test-write-log-entries-async-log"); String filter = "logName = projects/" + logging().options().projectId() + "/logs/" + logName; StringPayload firstPayload = StringPayload.of("stringPayload"); - LogEntry firstEntry = LogEntry.builder(firstPayload).severity(Severity.ALERT).build(); + LogEntry firstEntry = LogEntry.newBuilder(firstPayload).setSeverity(Severity.ALERT).build(); ProtoPayload secondPayload = ProtoPayload.of(Any.pack(StringValue.newBuilder().setValue("protoPayload").build())); - LogEntry secondEntry = LogEntry.builder(secondPayload).severity(Severity.DEBUG).build(); + LogEntry secondEntry = LogEntry.newBuilder(secondPayload).setSeverity(Severity.DEBUG).build(); logging().writeAsync(ImmutableList.of(firstEntry, secondEntry), WriteOption.labels(ImmutableMap.of("key1", "value1")), - WriteOption.resource(MonitoredResource.builder("global").build()), + WriteOption.resource(MonitoredResource.newBuilder("global").build()), WriteOption.logName(logName)).get(); EntryListOption[] options = {EntryListOption.filter(filter), EntryListOption.pageSize(1)}; AsyncPage page = logging().listLogEntriesAsync(options).get(); @@ -428,26 +428,26 @@ public void testWriteAndListLogEntriesAsync() throws InterruptedException, Execu Iterator iterator = page.iterateAll(); assertTrue(iterator.hasNext()); LogEntry entry = iterator.next(); - assertEquals(firstPayload, entry.payload()); - assertEquals(logName, entry.logName()); - assertEquals(ImmutableMap.of("key1", "value1"), entry.labels()); - assertEquals("global", entry.resource().type()); - assertNull(entry.httpRequest()); - assertEquals(Severity.ALERT, entry.severity()); - assertNull(entry.operation()); - assertNotNull(entry.insertId()); - assertNotNull(entry.timestamp()); + assertEquals(firstPayload, entry.getPayload()); + assertEquals(logName, entry.getLogName()); + assertEquals(ImmutableMap.of("key1", "value1"), entry.getLabels()); + assertEquals("global", entry.getResource().getType()); + assertNull(entry.getHttpRequest()); + assertEquals(Severity.ALERT, entry.getSeverity()); + assertNull(entry.getOperation()); + assertNotNull(entry.getInsertId()); + assertNotNull(entry.getTimestamp()); assertTrue(iterator.hasNext()); entry = iterator.next(); - assertEquals(secondPayload, entry.payload()); - assertEquals(logName, entry.logName()); - assertEquals(ImmutableMap.of("key1", "value1"), entry.labels()); - assertEquals("global", entry.resource().type()); - assertNull(entry.operation()); - assertEquals(Severity.DEBUG, entry.severity()); - assertNull(entry.httpRequest()); - assertNotNull(entry.insertId()); - assertNotNull(entry.timestamp()); + assertEquals(secondPayload, entry.getPayload()); + assertEquals(logName, entry.getLogName()); + assertEquals(ImmutableMap.of("key1", "value1"), entry.getLabels()); + assertEquals("global", entry.getResource().getType()); + assertNull(entry.getOperation()); + assertEquals(Severity.DEBUG, entry.getSeverity()); + assertNull(entry.getHttpRequest()); + assertNotNull(entry.getInsertId()); + assertNotNull(entry.getTimestamp()); assertTrue(logging().deleteLogAsync(logName).get()); } @@ -482,18 +482,19 @@ public void testLoggingHandler() throws InterruptedException { } assertTrue(iterator.hasNext()); LogEntry entry = iterator.next(); - assertTrue(entry.payload() instanceof StringPayload); - assertTrue(entry.payload().data().contains("Message")); - assertEquals(logName, entry.logName()); + assertTrue(entry.getPayload() instanceof StringPayload); + assertTrue(entry.getPayload().getData().contains("Message")); + assertEquals(logName, entry.getLogName()); assertEquals(ImmutableMap.of("levelName", "INFO", - "levelValue", String.valueOf(Level.INFO.intValue())), entry.labels()); - assertEquals("global", entry.resource().type()); - assertEquals(ImmutableMap.of("project_id", options.projectId()), entry.resource().labels()); - assertNull(entry.httpRequest()); - assertEquals(Severity.INFO, entry.severity()); - assertNull(entry.operation()); - assertNotNull(entry.insertId()); - assertNotNull(entry.timestamp()); + "levelValue", String.valueOf(Level.INFO.intValue())), entry.getLabels()); + assertEquals("global", entry.getResource().getType()); + assertEquals(ImmutableMap.of("project_id", options.projectId()), + entry.getResource().getLabels()); + assertNull(entry.getHttpRequest()); + assertEquals(Severity.INFO, entry.getSeverity()); + assertNull(entry.getOperation()); + assertNotNull(entry.getInsertId()); + assertNotNull(entry.getTimestamp()); assertFalse(iterator.hasNext()); logger.removeHandler(handler); logging().deleteLog(logName); @@ -522,17 +523,17 @@ public void testAsyncLoggingHandler() throws InterruptedException { } assertTrue(iterator.hasNext()); LogEntry entry = iterator.next(); - assertTrue(entry.payload() instanceof StringPayload); - assertTrue(entry.payload().data().contains("Message")); - assertEquals(logName, entry.logName()); + assertTrue(entry.getPayload() instanceof StringPayload); + assertTrue(entry.getPayload().getData().contains("Message")); + assertEquals(logName, entry.getLogName()); assertEquals(ImmutableMap.of("levelName", "WARNING", - "levelValue", String.valueOf(Level.WARNING.intValue())), entry.labels()); - assertEquals(resource, entry.resource()); - assertNull(entry.httpRequest()); - assertEquals(Severity.WARNING, entry.severity()); - assertNull(entry.operation()); - assertNotNull(entry.insertId()); - assertNotNull(entry.timestamp()); + "levelValue", String.valueOf(Level.WARNING.intValue())), entry.getLabels()); + assertEquals(resource, entry.getResource()); + assertNull(entry.getHttpRequest()); + assertEquals(Severity.WARNING, entry.getSeverity()); + assertNull(entry.getOperation()); + assertNotNull(entry.getInsertId()); + assertNotNull(entry.getTimestamp()); assertFalse(iterator.hasNext()); logger.removeHandler(handler); logging().deleteLog(logName); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/HttpRequestTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/HttpRequestTest.java index 41eba99b327a..ca8fece87ee0 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/HttpRequestTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/HttpRequestTest.java @@ -43,7 +43,22 @@ public class HttpRequestTest { private static final boolean CACHE_HIT = true; private static final boolean CACHE_VALIDATED_WITH_ORIGIN_SERVER = false; private static final Long CACHE_FILL_BYTES = 3L; - private static final HttpRequest HTTP_REQUEST = HttpRequest.builder() + private static final HttpRequest HTTP_REQUEST = HttpRequest.newBuilder() + .setRequestMethod(REQUEST_METHOD) + .setRequestUrl(REQUEST_URL) + .setRequestSize(REQUEST_SIZE) + .setStatus(STATUS) + .setResponseSize(REPONSE_SIZE) + .setUserAgent(USER_AGENT) + .setRemoteIp(REMOTE_IP) + .setServerIp(SERVER_IP) + .setReferer(REFERER) + .setCacheLookup(CACHE_LOOKUP) + .setCacheHit(CACHE_HIT) + .setCacheValidatedWithOriginServer(CACHE_VALIDATED_WITH_ORIGIN_SERVER) + .setCacheFillBytes(CACHE_FILL_BYTES) + .build(); + private static final HttpRequest DEPRECATED_HTTP_REQUEST = HttpRequest.builder() .requestMethod(REQUEST_METHOD) .requestUrl(REQUEST_URL) .requestSize(REQUEST_SIZE) @@ -64,122 +79,140 @@ public class HttpRequestTest { @Test public void testBuilder() { - assertEquals(REQUEST_METHOD, HTTP_REQUEST.requestMethod()); - assertEquals(REQUEST_URL, HTTP_REQUEST.requestUrl()); - assertEquals(REQUEST_SIZE, HTTP_REQUEST.requestSize()); - assertEquals(STATUS, HTTP_REQUEST.status()); - assertEquals(REPONSE_SIZE, HTTP_REQUEST.responseSize()); - assertEquals(USER_AGENT, HTTP_REQUEST.userAgent()); - assertEquals(REMOTE_IP, HTTP_REQUEST.remoteIp()); - assertEquals(SERVER_IP, HTTP_REQUEST.serverIp()); - assertEquals(REFERER, HTTP_REQUEST.referer()); + assertEquals(REQUEST_METHOD, HTTP_REQUEST.getRequestMethod()); + assertEquals(REQUEST_URL, HTTP_REQUEST.getRequestUrl()); + assertEquals(REQUEST_SIZE, HTTP_REQUEST.getRequestSize()); + assertEquals(STATUS, HTTP_REQUEST.getStatus()); + assertEquals(REPONSE_SIZE, HTTP_REQUEST.getResponseSize()); + assertEquals(USER_AGENT, HTTP_REQUEST.getUserAgent()); + assertEquals(REMOTE_IP, HTTP_REQUEST.getRemoteIp()); + assertEquals(SERVER_IP, HTTP_REQUEST.getServerIp()); + assertEquals(REFERER, HTTP_REQUEST.getReferer()); assertEquals(CACHE_LOOKUP, HTTP_REQUEST.cacheLookup()); assertEquals(CACHE_HIT, HTTP_REQUEST.cacheHit()); assertEquals(CACHE_VALIDATED_WITH_ORIGIN_SERVER, HTTP_REQUEST.cacheValidatedWithOriginServer()); - assertEquals(CACHE_FILL_BYTES, HTTP_REQUEST.cacheFillBytes()); + assertEquals(CACHE_FILL_BYTES, HTTP_REQUEST.getCacheFillBytes()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(REQUEST_METHOD, DEPRECATED_HTTP_REQUEST.requestMethod()); + assertEquals(REQUEST_URL, DEPRECATED_HTTP_REQUEST.requestUrl()); + assertEquals(REQUEST_SIZE, DEPRECATED_HTTP_REQUEST.requestSize()); + assertEquals(STATUS, DEPRECATED_HTTP_REQUEST.status()); + assertEquals(REPONSE_SIZE, DEPRECATED_HTTP_REQUEST.responseSize()); + assertEquals(USER_AGENT, DEPRECATED_HTTP_REQUEST.userAgent()); + assertEquals(REMOTE_IP, DEPRECATED_HTTP_REQUEST.remoteIp()); + assertEquals(SERVER_IP, DEPRECATED_HTTP_REQUEST.serverIp()); + assertEquals(REFERER, DEPRECATED_HTTP_REQUEST.referer()); + assertEquals(CACHE_LOOKUP, DEPRECATED_HTTP_REQUEST.cacheLookup()); + assertEquals(CACHE_HIT, DEPRECATED_HTTP_REQUEST.cacheHit()); + assertEquals(CACHE_VALIDATED_WITH_ORIGIN_SERVER, + DEPRECATED_HTTP_REQUEST.cacheValidatedWithOriginServer()); + assertEquals(CACHE_FILL_BYTES, DEPRECATED_HTTP_REQUEST.cacheFillBytes()); } @Test public void testBuilderDefaultValues() { - HttpRequest httpRequest = HttpRequest.builder().build(); - assertNull(httpRequest.requestMethod()); - assertNull(httpRequest.requestUrl()); - assertNull(httpRequest.requestSize()); - assertNull(httpRequest.status()); - assertNull(httpRequest.responseSize()); - assertNull(httpRequest.userAgent()); - assertNull(httpRequest.remoteIp()); - assertNull(httpRequest.serverIp()); - assertNull(httpRequest.referer()); + HttpRequest httpRequest = HttpRequest.newBuilder().build(); + assertNull(httpRequest.getRequestMethod()); + assertNull(httpRequest.getRequestUrl()); + assertNull(httpRequest.getRequestSize()); + assertNull(httpRequest.getStatus()); + assertNull(httpRequest.getResponseSize()); + assertNull(httpRequest.getUserAgent()); + assertNull(httpRequest.getRemoteIp()); + assertNull(httpRequest.getServerIp()); + assertNull(httpRequest.getReferer()); assertFalse(httpRequest.cacheLookup()); assertFalse(httpRequest.cacheHit()); assertFalse(httpRequest.cacheValidatedWithOriginServer()); - assertNull(httpRequest.cacheFillBytes()); + assertNull(httpRequest.getCacheFillBytes()); } @Test public void testToBuilder() { compareHttpRequest(HTTP_REQUEST, HTTP_REQUEST.toBuilder().build()); HttpRequest httpRequest = HTTP_REQUEST.toBuilder() - .requestMethod(RequestMethod.POST) - .requestUrl("http://www.other-example.com") - .requestSize(4) - .status(201) - .responseSize(5) - .userAgent("otherUserAgent") - .remoteIp("192.168.1.3") - .serverIp("192.168.1.4") - .referer("Referer: http://www.other-example.com") - .cacheLookup(true) - .cacheHit(true) - .cacheValidatedWithOriginServer(true) - .cacheFillBytes(6) + .setRequestMethod(RequestMethod.POST) + .setRequestUrl("http://www.other-example.com") + .setRequestSize(4) + .setStatus(201) + .setResponseSize(5) + .setUserAgent("otherUserAgent") + .setRemoteIp("192.168.1.3") + .setServerIp("192.168.1.4") + .setReferer("Referer: http://www.other-example.com") + .setCacheLookup(true) + .setCacheHit(true) + .setCacheValidatedWithOriginServer(true) + .setCacheFillBytes(6) .build(); - assertEquals(RequestMethod.POST, httpRequest.requestMethod()); - assertEquals("http://www.other-example.com", httpRequest.requestUrl()); - assertEquals(4, (long) httpRequest.requestSize()); - assertEquals(201, (int) httpRequest.status()); - assertEquals(5, (long) httpRequest.responseSize()); - assertEquals("otherUserAgent", httpRequest.userAgent()); - assertEquals("192.168.1.3", httpRequest.remoteIp()); - assertEquals("192.168.1.4", httpRequest.serverIp()); - assertEquals("Referer: http://www.other-example.com", httpRequest.referer()); + assertEquals(RequestMethod.POST, httpRequest.getRequestMethod()); + assertEquals("http://www.other-example.com", httpRequest.getRequestUrl()); + assertEquals(4, (long) httpRequest.getRequestSize()); + assertEquals(201, (int) httpRequest.getStatus()); + assertEquals(5, (long) httpRequest.getResponseSize()); + assertEquals("otherUserAgent", httpRequest.getUserAgent()); + assertEquals("192.168.1.3", httpRequest.getRemoteIp()); + assertEquals("192.168.1.4", httpRequest.getServerIp()); + assertEquals("Referer: http://www.other-example.com", httpRequest.getReferer()); assertTrue(httpRequest.cacheLookup()); assertTrue(httpRequest.cacheHit()); assertTrue(httpRequest.cacheValidatedWithOriginServer()); - assertEquals(6, (long) httpRequest.cacheFillBytes()); + assertEquals(6, (long) httpRequest.getCacheFillBytes()); } @Test public void testToAndFromPb() { HttpRequest httpRequest = HttpRequest.fromPb(HTTP_REQUEST.toPb()); compareHttpRequest(HTTP_REQUEST, httpRequest); - assertEquals(REQUEST_METHOD, httpRequest.requestMethod()); - assertEquals(REQUEST_URL, httpRequest.requestUrl()); - assertEquals(REQUEST_SIZE, httpRequest.requestSize()); - assertEquals(STATUS, httpRequest.status()); - assertEquals(REPONSE_SIZE, httpRequest.responseSize()); - assertEquals(USER_AGENT, httpRequest.userAgent()); - assertEquals(REMOTE_IP, httpRequest.remoteIp()); - assertEquals(SERVER_IP, httpRequest.serverIp()); - assertEquals(REFERER, httpRequest.referer()); + assertEquals(REQUEST_METHOD, httpRequest.getRequestMethod()); + assertEquals(REQUEST_URL, httpRequest.getRequestUrl()); + assertEquals(REQUEST_SIZE, httpRequest.getRequestSize()); + assertEquals(STATUS, httpRequest.getStatus()); + assertEquals(REPONSE_SIZE, httpRequest.getResponseSize()); + assertEquals(USER_AGENT, httpRequest.getUserAgent()); + assertEquals(REMOTE_IP, httpRequest.getRemoteIp()); + assertEquals(SERVER_IP, httpRequest.getServerIp()); + assertEquals(REFERER, httpRequest.getReferer()); assertEquals(CACHE_LOOKUP, httpRequest.cacheLookup()); assertEquals(CACHE_HIT, httpRequest.cacheHit()); assertEquals(CACHE_VALIDATED_WITH_ORIGIN_SERVER, httpRequest.cacheValidatedWithOriginServer()); - assertEquals(CACHE_FILL_BYTES, httpRequest.cacheFillBytes()); - HttpRequest incompleteHttpRequest = HttpRequest.builder().build(); + assertEquals(CACHE_FILL_BYTES, httpRequest.getCacheFillBytes()); + HttpRequest incompleteHttpRequest = HttpRequest.newBuilder().build(); httpRequest = HttpRequest.fromPb(incompleteHttpRequest.toPb()); compareHttpRequest(incompleteHttpRequest, httpRequest); - assertNull(httpRequest.requestMethod()); - assertNull(httpRequest.requestUrl()); - assertNull(httpRequest.requestSize()); - assertNull(httpRequest.status()); - assertNull(httpRequest.responseSize()); - assertNull(httpRequest.userAgent()); - assertNull(httpRequest.remoteIp()); - assertNull(httpRequest.serverIp()); - assertNull(httpRequest.referer()); + assertNull(httpRequest.getRequestMethod()); + assertNull(httpRequest.getRequestUrl()); + assertNull(httpRequest.getRequestSize()); + assertNull(httpRequest.getStatus()); + assertNull(httpRequest.getResponseSize()); + assertNull(httpRequest.getUserAgent()); + assertNull(httpRequest.getRemoteIp()); + assertNull(httpRequest.getServerIp()); + assertNull(httpRequest.getReferer()); assertFalse(httpRequest.cacheLookup()); assertFalse(httpRequest.cacheHit()); assertFalse(httpRequest.cacheValidatedWithOriginServer()); - assertNull(httpRequest.cacheFillBytes()); + assertNull(httpRequest.getCacheFillBytes()); } private void compareHttpRequest(HttpRequest expected, HttpRequest value) { assertEquals(expected, value); - assertEquals(expected.requestMethod(), value.requestMethod()); - assertEquals(expected.requestUrl(), value.requestUrl()); - assertEquals(expected.requestSize(), value.requestSize()); - assertEquals(expected.status(), value.status()); - assertEquals(expected.responseSize(), value.responseSize()); - assertEquals(expected.userAgent(), value.userAgent()); - assertEquals(expected.remoteIp(), value.remoteIp()); - assertEquals(expected.serverIp(), value.serverIp()); - assertEquals(expected.referer(), value.referer()); + assertEquals(expected.getRequestMethod(), value.getRequestMethod()); + assertEquals(expected.getRequestUrl(), value.getRequestUrl()); + assertEquals(expected.getRequestSize(), value.getRequestSize()); + assertEquals(expected.getStatus(), value.getStatus()); + assertEquals(expected.getResponseSize(), value.getResponseSize()); + assertEquals(expected.getUserAgent(), value.getUserAgent()); + assertEquals(expected.getRemoteIp(), value.getRemoteIp()); + assertEquals(expected.getServerIp(), value.getServerIp()); + assertEquals(expected.getReferer(), value.getReferer()); assertEquals(expected.cacheLookup(), value.cacheLookup()); assertEquals(expected.cacheHit(), value.cacheHit()); assertEquals(expected.cacheValidatedWithOriginServer(), value.cacheValidatedWithOriginServer()); - assertEquals(expected.cacheFillBytes(), value.cacheFillBytes()); + assertEquals(expected.getCacheFillBytes(), value.getCacheFillBytes()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LogEntryTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LogEntryTest.java index ff2f93676b41..0f6c0f1c7d94 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LogEntryTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LogEntryTest.java @@ -34,15 +34,16 @@ public class LogEntryTest { private static final String LOG_NAME = "syslog"; - private static final MonitoredResource RESOURCE = MonitoredResource.builder("cloudsql_database") - .labels(ImmutableMap.of("datasetId", "myDataset", "zone", "myZone")) - .build(); + private static final MonitoredResource RESOURCE = + MonitoredResource.newBuilder("cloudsql_database") + .setLabels(ImmutableMap.of("datasetId", "myDataset", "zone", "myZone")) + .build(); private static final long TIMESTAMP = 42; private static final Severity SEVERITY = Severity.ALERT; private static final String INSERT_ID = "insertId"; - private static final HttpRequest HTTP_REQUEST = HttpRequest.builder() - .requestMethod(HttpRequest.RequestMethod.GET) - .status(404) + private static final HttpRequest HTTP_REQUEST = HttpRequest.newBuilder() + .setRequestMethod(HttpRequest.RequestMethod.GET) + .setStatus(404) .build(); private static final Map LABELS = ImmutableMap.of("key1", "value1", "key2", "value2"); @@ -52,7 +53,37 @@ public class LogEntryTest { JsonPayload.of(ImmutableMap.of("key", "val")); private static final ProtoPayload PROTO_PAYLOAD = ProtoPayload.of(Any.pack(Empty.getDefaultInstance())); - private static final LogEntry STRING_ENTRY = LogEntry.builder(STRING_PAYLOAD) + private static final LogEntry STRING_ENTRY = LogEntry.newBuilder(STRING_PAYLOAD) + .setLogName(LOG_NAME) + .setResource(RESOURCE) + .setTimestamp(TIMESTAMP) + .setSeverity(SEVERITY) + .setInsertId(INSERT_ID) + .setHttpRequest(HTTP_REQUEST) + .setLabels(LABELS) + .setOperation(OPERATION) + .build(); + private static final LogEntry JSON_ENTRY = LogEntry.newBuilder(JSON_PAYLOAD) + .setLogName(LOG_NAME) + .setResource(RESOURCE) + .setTimestamp(TIMESTAMP) + .setSeverity(SEVERITY) + .setInsertId(INSERT_ID) + .setHttpRequest(HTTP_REQUEST) + .setLabels(LABELS) + .setOperation(OPERATION) + .build(); + private static final LogEntry PROTO_ENTRY = LogEntry.newBuilder(PROTO_PAYLOAD) + .setLogName(LOG_NAME) + .setResource(RESOURCE) + .setTimestamp(TIMESTAMP) + .setSeverity(SEVERITY) + .setInsertId(INSERT_ID) + .setHttpRequest(HTTP_REQUEST) + .setLabels(LABELS) + .setOperation(OPERATION) + .build(); + private static final LogEntry DEPRECATED_STRING_ENTRY = LogEntry.builder(STRING_PAYLOAD) .logName(LOG_NAME) .resource(RESOURCE) .timestamp(TIMESTAMP) @@ -62,7 +93,7 @@ public class LogEntryTest { .labels(LABELS) .operation(OPERATION) .build(); - private static final LogEntry JSON_ENTRY = LogEntry.builder(JSON_PAYLOAD) + private static final LogEntry DEPRECATED_JSON_ENTRY = LogEntry.builder(JSON_PAYLOAD) .logName(LOG_NAME) .resource(RESOURCE) .timestamp(TIMESTAMP) @@ -72,7 +103,7 @@ public class LogEntryTest { .labels(LABELS) .operation(OPERATION) .build(); - private static final LogEntry PROTO_ENTRY = LogEntry.builder(PROTO_PAYLOAD) + private static final LogEntry DEPRECATED_PROTO_ENTRY = LogEntry.builder(PROTO_PAYLOAD) .logName(LOG_NAME) .resource(RESOURCE) .timestamp(TIMESTAMP) @@ -86,57 +117,109 @@ public class LogEntryTest { @Test public void testOf() { LogEntry logEntry = LogEntry.of(STRING_PAYLOAD); - assertEquals(STRING_PAYLOAD, logEntry.payload()); - assertEquals(Severity.DEFAULT, logEntry.severity()); - assertEquals(ImmutableMap.of(), logEntry.labels()); - assertNull(logEntry.logName()); - assertNull(logEntry.resource()); - assertNull(logEntry.timestamp()); - assertNull(logEntry.insertId()); - assertNull(logEntry.httpRequest()); - assertNull(logEntry.operation()); + assertEquals(STRING_PAYLOAD, logEntry.getPayload()); + assertEquals(Severity.DEFAULT, logEntry.getSeverity()); + assertEquals(ImmutableMap.of(), logEntry.getLabels()); + assertNull(logEntry.getLogName()); + assertNull(logEntry.getResource()); + assertNull(logEntry.getTimestamp()); + assertNull(logEntry.getInsertId()); + assertNull(logEntry.getHttpRequest()); + assertNull(logEntry.getOperation()); logEntry = LogEntry.of(LOG_NAME, RESOURCE, STRING_PAYLOAD); - assertEquals(STRING_PAYLOAD, logEntry.payload()); - assertEquals(LOG_NAME, logEntry.logName()); - assertEquals(RESOURCE, logEntry.resource()); - assertEquals(Severity.DEFAULT, logEntry.severity()); - assertEquals(ImmutableMap.of(), logEntry.labels()); - assertEquals(ImmutableMap.of(), logEntry.labels()); - assertNull(logEntry.timestamp()); - assertNull(logEntry.insertId()); - assertNull(logEntry.httpRequest()); - assertNull(logEntry.operation()); + assertEquals(STRING_PAYLOAD, logEntry.getPayload()); + assertEquals(LOG_NAME, logEntry.getLogName()); + assertEquals(RESOURCE, logEntry.getResource()); + assertEquals(Severity.DEFAULT, logEntry.getSeverity()); + assertEquals(ImmutableMap.of(), logEntry.getLabels()); + assertEquals(ImmutableMap.of(), logEntry.getLabels()); + assertNull(logEntry.getTimestamp()); + assertNull(logEntry.getInsertId()); + assertNull(logEntry.getHttpRequest()); + assertNull(logEntry.getOperation()); } @Test public void testBuilder() { - assertEquals(LOG_NAME, STRING_ENTRY.logName()); - assertEquals(RESOURCE, STRING_ENTRY.resource()); - assertEquals(TIMESTAMP, (long) STRING_ENTRY.timestamp()); - assertEquals(SEVERITY, STRING_ENTRY.severity()); - assertEquals(INSERT_ID, STRING_ENTRY.insertId()); - assertEquals(HTTP_REQUEST, STRING_ENTRY.httpRequest()); - assertEquals(LABELS, STRING_ENTRY.labels()); - assertEquals(OPERATION, STRING_ENTRY.operation()); - assertEquals(STRING_PAYLOAD, STRING_ENTRY.payload()); - assertEquals(LOG_NAME, JSON_ENTRY.logName()); - assertEquals(RESOURCE, JSON_ENTRY.resource()); - assertEquals(TIMESTAMP, (long) JSON_ENTRY.timestamp()); - assertEquals(SEVERITY, JSON_ENTRY.severity()); - assertEquals(INSERT_ID, JSON_ENTRY.insertId()); - assertEquals(HTTP_REQUEST, JSON_ENTRY.httpRequest()); - assertEquals(LABELS, JSON_ENTRY.labels()); - assertEquals(OPERATION, JSON_ENTRY.operation()); - assertEquals(JSON_PAYLOAD, JSON_ENTRY.payload()); - assertEquals(LOG_NAME, PROTO_ENTRY.logName()); - assertEquals(RESOURCE, PROTO_ENTRY.resource()); - assertEquals(TIMESTAMP, (long) PROTO_ENTRY.timestamp()); - assertEquals(SEVERITY, PROTO_ENTRY.severity()); - assertEquals(INSERT_ID, PROTO_ENTRY.insertId()); - assertEquals(HTTP_REQUEST, PROTO_ENTRY.httpRequest()); - assertEquals(LABELS, PROTO_ENTRY.labels()); - assertEquals(OPERATION, PROTO_ENTRY.operation()); - assertEquals(PROTO_PAYLOAD, PROTO_ENTRY.payload()); + assertEquals(LOG_NAME, STRING_ENTRY.getLogName()); + assertEquals(RESOURCE, STRING_ENTRY.getResource()); + assertEquals(TIMESTAMP, (long) STRING_ENTRY.getTimestamp()); + assertEquals(SEVERITY, STRING_ENTRY.getSeverity()); + assertEquals(INSERT_ID, STRING_ENTRY.getInsertId()); + assertEquals(HTTP_REQUEST, STRING_ENTRY.getHttpRequest()); + assertEquals(LABELS, STRING_ENTRY.getLabels()); + assertEquals(OPERATION, STRING_ENTRY.getOperation()); + assertEquals(STRING_PAYLOAD, STRING_ENTRY.getPayload()); + assertEquals(LOG_NAME, JSON_ENTRY.getLogName()); + assertEquals(RESOURCE, JSON_ENTRY.getResource()); + assertEquals(TIMESTAMP, (long) JSON_ENTRY.getTimestamp()); + assertEquals(SEVERITY, JSON_ENTRY.getSeverity()); + assertEquals(INSERT_ID, JSON_ENTRY.getInsertId()); + assertEquals(HTTP_REQUEST, JSON_ENTRY.getHttpRequest()); + assertEquals(LABELS, JSON_ENTRY.getLabels()); + assertEquals(OPERATION, JSON_ENTRY.getOperation()); + assertEquals(JSON_PAYLOAD, JSON_ENTRY.getPayload()); + assertEquals(LOG_NAME, PROTO_ENTRY.getLogName()); + assertEquals(RESOURCE, PROTO_ENTRY.getResource()); + assertEquals(TIMESTAMP, (long) PROTO_ENTRY.getTimestamp()); + assertEquals(SEVERITY, PROTO_ENTRY.getSeverity()); + assertEquals(INSERT_ID, PROTO_ENTRY.getInsertId()); + assertEquals(HTTP_REQUEST, PROTO_ENTRY.getHttpRequest()); + assertEquals(LABELS, PROTO_ENTRY.getLabels()); + assertEquals(OPERATION, PROTO_ENTRY.getOperation()); + assertEquals(PROTO_PAYLOAD, PROTO_ENTRY.getPayload()); + LogEntry logEntry = LogEntry.newBuilder(STRING_PAYLOAD) + .setPayload(StringPayload.of("otherPayload")) + .setLogName(LOG_NAME) + .setResource(RESOURCE) + .setTimestamp(TIMESTAMP) + .setSeverity(SEVERITY) + .setInsertId(INSERT_ID) + .setHttpRequest(HTTP_REQUEST) + .addLabel("key1", "value1") + .addLabel("key2", "value2") + .setOperation(OPERATION) + .build(); + assertEquals(LOG_NAME, logEntry.getLogName()); + assertEquals(RESOURCE, logEntry.getResource()); + assertEquals(TIMESTAMP, (long) logEntry.getTimestamp()); + assertEquals(SEVERITY, logEntry.getSeverity()); + assertEquals(INSERT_ID, logEntry.getInsertId()); + assertEquals(HTTP_REQUEST, logEntry.getHttpRequest()); + assertEquals(LABELS, logEntry.getLabels()); + assertEquals(OPERATION, logEntry.getOperation()); + assertEquals(StringPayload.of("otherPayload"), logEntry.getPayload()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(LOG_NAME, DEPRECATED_STRING_ENTRY.logName()); + assertEquals(RESOURCE, DEPRECATED_STRING_ENTRY.resource()); + assertEquals(TIMESTAMP, (long) DEPRECATED_STRING_ENTRY.timestamp()); + assertEquals(SEVERITY, DEPRECATED_STRING_ENTRY.severity()); + assertEquals(INSERT_ID, DEPRECATED_STRING_ENTRY.insertId()); + assertEquals(HTTP_REQUEST, DEPRECATED_STRING_ENTRY.httpRequest()); + assertEquals(LABELS, DEPRECATED_STRING_ENTRY.labels()); + assertEquals(OPERATION, DEPRECATED_STRING_ENTRY.operation()); + assertEquals(STRING_PAYLOAD, DEPRECATED_STRING_ENTRY.payload()); + assertEquals(LOG_NAME, DEPRECATED_JSON_ENTRY.logName()); + assertEquals(RESOURCE, DEPRECATED_JSON_ENTRY.resource()); + assertEquals(TIMESTAMP, (long) DEPRECATED_JSON_ENTRY.timestamp()); + assertEquals(SEVERITY, DEPRECATED_JSON_ENTRY.severity()); + assertEquals(INSERT_ID, DEPRECATED_JSON_ENTRY.insertId()); + assertEquals(HTTP_REQUEST, DEPRECATED_JSON_ENTRY.httpRequest()); + assertEquals(LABELS, DEPRECATED_JSON_ENTRY.labels()); + assertEquals(OPERATION, DEPRECATED_JSON_ENTRY.operation()); + assertEquals(JSON_PAYLOAD, DEPRECATED_JSON_ENTRY.payload()); + assertEquals(LOG_NAME, DEPRECATED_PROTO_ENTRY.logName()); + assertEquals(RESOURCE, DEPRECATED_PROTO_ENTRY.resource()); + assertEquals(TIMESTAMP, (long) DEPRECATED_PROTO_ENTRY.timestamp()); + assertEquals(SEVERITY, DEPRECATED_PROTO_ENTRY.severity()); + assertEquals(INSERT_ID, DEPRECATED_PROTO_ENTRY.insertId()); + assertEquals(HTTP_REQUEST, DEPRECATED_PROTO_ENTRY.httpRequest()); + assertEquals(LABELS, DEPRECATED_PROTO_ENTRY.labels()); + assertEquals(OPERATION, DEPRECATED_PROTO_ENTRY.operation()); + assertEquals(PROTO_PAYLOAD, DEPRECATED_PROTO_ENTRY.payload()); LogEntry logEntry = LogEntry.builder(STRING_PAYLOAD) .payload(StringPayload.of("otherPayload")) .logName(LOG_NAME) @@ -163,41 +246,41 @@ public void testBuilder() { @Test public void testToBuilder() { compareLogEntry(STRING_ENTRY, STRING_ENTRY.toBuilder().build()); - HttpRequest request = HttpRequest.builder() - .requestMethod(HttpRequest.RequestMethod.POST) - .status(500) + HttpRequest request = HttpRequest.newBuilder() + .setRequestMethod(HttpRequest.RequestMethod.POST) + .setStatus(500) .build(); LogEntry logEntry = STRING_ENTRY.toBuilder() - .payload(StringPayload.of("otherPayload")) - .logName("otherLogName") - .resource(MonitoredResource.builder("global").build()) - .timestamp(43) - .severity(Severity.DEBUG) - .insertId("otherInsertId") - .httpRequest(request) + .setPayload(StringPayload.of("otherPayload")) + .setLogName("otherLogName") + .setResource(MonitoredResource.newBuilder("global").build()) + .setTimestamp(43) + .setSeverity(Severity.DEBUG) + .setInsertId("otherInsertId") + .setHttpRequest(request) .clearLabels() .addLabel("key", "value") - .operation(Operation.of("otherId", "otherProducer")) + .setOperation(Operation.of("otherId", "otherProducer")) .build(); - assertEquals("otherLogName", logEntry.logName()); - assertEquals(MonitoredResource.builder("global").build(), logEntry.resource()); - assertEquals(43, (long) logEntry.timestamp()); - assertEquals(Severity.DEBUG, logEntry.severity()); - assertEquals("otherInsertId", logEntry.insertId()); - assertEquals(request, logEntry.httpRequest()); - assertEquals(ImmutableMap.of("key", "value"), logEntry.labels()); - assertEquals(Operation.of("otherId", "otherProducer"), logEntry.operation()); - assertEquals(StringPayload.of("otherPayload"), logEntry.payload()); + assertEquals("otherLogName", logEntry.getLogName()); + assertEquals(MonitoredResource.newBuilder("global").build(), logEntry.getResource()); + assertEquals(43, (long) logEntry.getTimestamp()); + assertEquals(Severity.DEBUG, logEntry.getSeverity()); + assertEquals("otherInsertId", logEntry.getInsertId()); + assertEquals(request, logEntry.getHttpRequest()); + assertEquals(ImmutableMap.of("key", "value"), logEntry.getLabels()); + assertEquals(Operation.of("otherId", "otherProducer"), logEntry.getOperation()); + assertEquals(StringPayload.of("otherPayload"), logEntry.getPayload()); logEntry = logEntry.toBuilder() - .payload(STRING_PAYLOAD) - .logName(LOG_NAME) - .resource(RESOURCE) - .timestamp(TIMESTAMP) - .severity(SEVERITY) - .insertId(INSERT_ID) - .httpRequest(HTTP_REQUEST) - .labels(LABELS) - .operation(OPERATION) + .setPayload(STRING_PAYLOAD) + .setLogName(LOG_NAME) + .setResource(RESOURCE) + .setTimestamp(TIMESTAMP) + .setSeverity(SEVERITY) + .setInsertId(INSERT_ID) + .setHttpRequest(HTTP_REQUEST) + .setLabels(LABELS) + .setOperation(OPERATION) .build(); compareLogEntry(STRING_ENTRY, logEntry); } @@ -215,15 +298,15 @@ public void testToAndFromPb() { private void compareLogEntry(LogEntry expected, LogEntry value) { assertEquals(expected, value); - assertEquals(expected.logName(), value.logName()); - assertEquals(expected.resource(), value.resource()); - assertEquals(expected.timestamp(), value.timestamp()); - assertEquals(expected.severity(), value.severity()); - assertEquals(expected.insertId(), value.insertId()); - assertEquals(expected.httpRequest(), value.httpRequest()); - assertEquals(expected.labels(), value.labels()); - assertEquals(expected.operation(), value.operation()); - assertEquals(expected.payload(), value.payload()); + assertEquals(expected.getLogName(), value.getLogName()); + assertEquals(expected.getResource(), value.getResource()); + assertEquals(expected.getTimestamp(), value.getTimestamp()); + assertEquals(expected.getSeverity(), value.getSeverity()); + assertEquals(expected.getInsertId(), value.getInsertId()); + assertEquals(expected.getHttpRequest(), value.getHttpRequest()); + assertEquals(expected.getLabels(), value.getLabels()); + assertEquals(expected.getOperation(), value.getOperation()); + assertEquals(expected.getPayload(), value.getPayload()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingHandlerTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingHandlerTest.java index f8f1bf7a9bab..50282b59f760 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingHandlerTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingHandlerTest.java @@ -46,68 +46,68 @@ public class LoggingHandlerTest { private static final String PROJECT = "project"; private static final MonitoredResource DEFAULT_RESOURCE = MonitoredResource.of("global", ImmutableMap.of("project_id", PROJECT)); - private static final LogEntry FINEST_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.DEBUG) + private static final LogEntry FINEST_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.DEBUG) .addLabel("levelName", "FINEST") .addLabel("levelValue", String.valueOf(Level.FINEST.intValue())) .build(); - private static final LogEntry FINER_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.DEBUG) + private static final LogEntry FINER_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.DEBUG) .addLabel("levelName", "FINER") .addLabel("levelValue", String.valueOf(Level.FINER.intValue())) .build(); - private static final LogEntry FINE_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.DEBUG) + private static final LogEntry FINE_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.DEBUG) .addLabel("levelName", "FINE") .addLabel("levelValue", String.valueOf(Level.FINE.intValue())) .build(); - private static final LogEntry CONFIG_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.INFO) + private static final LogEntry CONFIG_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.INFO) .addLabel("levelName", "CONFIG") .addLabel("levelValue", String.valueOf(Level.CONFIG.intValue())) .build(); - private static final LogEntry INFO_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.INFO) + private static final LogEntry INFO_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.INFO) .addLabel("levelName", "INFO") .addLabel("levelValue", String.valueOf(Level.INFO.intValue())) .build(); - private static final LogEntry WARNING_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.WARNING) + private static final LogEntry WARNING_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.WARNING) .addLabel("levelName", "WARNING") .addLabel("levelValue", String.valueOf(Level.WARNING.intValue())) .build(); - private static final LogEntry SEVERE_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.ERROR) + private static final LogEntry SEVERE_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.ERROR) .addLabel("levelName", "SEVERE") .addLabel("levelValue", String.valueOf(Level.SEVERE.intValue())) .build(); - private static final LogEntry DEBUG_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.DEBUG) + private static final LogEntry DEBUG_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.DEBUG) .addLabel("levelName", "DEBUG") .addLabel("levelValue", String.valueOf(LoggingLevel.DEBUG.intValue())) .build(); - private static final LogEntry NOTICE_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.NOTICE) + private static final LogEntry NOTICE_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.NOTICE) .addLabel("levelName", "NOTICE") .addLabel("levelValue", String.valueOf(LoggingLevel.NOTICE.intValue())) .build(); - private static final LogEntry ERROR_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.ERROR) + private static final LogEntry ERROR_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.ERROR) .addLabel("levelName", "ERROR") .addLabel("levelValue", String.valueOf(LoggingLevel.ERROR.intValue())) .build(); - private static final LogEntry CRITICAL_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.CRITICAL) + private static final LogEntry CRITICAL_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.CRITICAL) .addLabel("levelName", "CRITICAL") .addLabel("levelValue", String.valueOf(LoggingLevel.CRITICAL.intValue())) .build(); - private static final LogEntry ALERT_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.ALERT) + private static final LogEntry ALERT_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.ALERT) .addLabel("levelName", "ALERT") .addLabel("levelValue", String.valueOf(LoggingLevel.ALERT.intValue())) .build(); - private static final LogEntry EMERGENCY_ENTRY = LogEntry.builder(StringPayload.of(MESSAGE)) - .severity(Severity.EMERGENCY) + private static final LogEntry EMERGENCY_ENTRY = LogEntry.newBuilder(StringPayload.of(MESSAGE)) + .setSeverity(Severity.EMERGENCY) .addLabel("levelName", "EMERGENCY") .addLabel("levelValue", String.valueOf(LoggingLevel.EMERGENCY.intValue())) .build(); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingImplTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingImplTest.java index 2c70ba2da03f..f55b21f27efc 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingImplTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingImplTest.java @@ -89,8 +89,8 @@ public class LoggingImplTest { private static final String METRIC_NAME_PB = "projects/" + PROJECT + "/metrics/" + METRIC_NAME; private static final String FILTER = "logName=projects/my-projectid/logs/syslog"; private static final String DESCRIPTION = "description"; - private static final MetricInfo METRIC_INFO = MetricInfo.builder(METRIC_NAME, FILTER) - .description(DESCRIPTION) + private static final MetricInfo METRIC_INFO = MetricInfo.newBuilder(METRIC_NAME, FILTER) + .setDescription(DESCRIPTION) .build(); private static final com.google.api.MonitoredResourceDescriptor DESCRIPTOR_PB = com.google.api.MonitoredResourceDescriptor.getDefaultInstance(); @@ -99,14 +99,14 @@ public class LoggingImplTest { private static final String LOG_NAME = "log"; private static final String LOG_NAME_PB = "projects/" + PROJECT + "/logs/" + LOG_NAME; private static final MonitoredResource MONITORED_RESOURCE = - MonitoredResource.builder("global").addLabel("project-id", PROJECT).build(); - private static final LogEntry LOG_ENTRY1 = LogEntry.builder(StringPayload.of("entry1")) - .logName(LOG_NAME) - .resource(MONITORED_RESOURCE) + MonitoredResource.newBuilder("global").addLabel("project-id", PROJECT).build(); + private static final LogEntry LOG_ENTRY1 = LogEntry.newBuilder(StringPayload.of("entry1")) + .setLogName(LOG_NAME) + .setResource(MONITORED_RESOURCE) .build(); - private static final LogEntry LOG_ENTRY2 = LogEntry.builder(StringPayload.of("entry2")) - .logName(LOG_NAME) - .resource(MONITORED_RESOURCE) + private static final LogEntry LOG_ENTRY2 = LogEntry.newBuilder(StringPayload.of("entry2")) + .setLogName(LOG_NAME) + .setResource(MONITORED_RESOURCE) .build(); private static final Function SINK_TO_PB_FUNCTION = new Function() { diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingLevelTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingLevelTest.java index c2a93a7711f7..3c5ccee1884b 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingLevelTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingLevelTest.java @@ -29,6 +29,7 @@ public class LoggingLevelTest { public void testDebug() { LoggingLevel debug = LoggingLevel.DEBUG; assertEquals(Severity.DEBUG, debug.severity()); + assertEquals(Severity.DEBUG, debug.getSeverity()); assertEquals("DEBUG", debug.getName()); assertTrue(debug.intValue() < Level.FINEST.intValue()); assertTrue(debug.intValue() > Level.ALL.intValue()); @@ -38,6 +39,7 @@ public void testDebug() { public void testNotice() { LoggingLevel notice = LoggingLevel.NOTICE; assertEquals(Severity.NOTICE, notice.severity()); + assertEquals(Severity.NOTICE, notice.getSeverity()); assertEquals("NOTICE", notice.getName()); assertTrue(notice.intValue() > Level.INFO.intValue()); assertTrue(notice.intValue() < Level.WARNING.intValue()); @@ -47,6 +49,7 @@ public void testNotice() { public void testError() { LoggingLevel error = LoggingLevel.ERROR; assertEquals(Severity.ERROR, error.severity()); + assertEquals(Severity.ERROR, error.getSeverity()); assertEquals("ERROR", error.getName()); assertTrue(error.intValue() > Level.WARNING.intValue()); assertTrue(error.intValue() < Level.SEVERE.intValue()); @@ -56,6 +59,7 @@ public void testError() { public void testCritical() { LoggingLevel critical = LoggingLevel.CRITICAL; assertEquals(Severity.CRITICAL, critical.severity()); + assertEquals(Severity.CRITICAL, critical.getSeverity()); assertEquals("CRITICAL", critical.getName()); assertTrue(critical.intValue() > LoggingLevel.SEVERE.intValue()); assertTrue(critical.intValue() < Level.OFF.intValue()); @@ -65,6 +69,7 @@ public void testCritical() { public void testAlert() { LoggingLevel alert = LoggingLevel.ALERT; assertEquals(Severity.ALERT, alert.severity()); + assertEquals(Severity.ALERT, alert.getSeverity()); assertEquals("ALERT", alert.getName()); assertTrue(alert.intValue() > LoggingLevel.CRITICAL.intValue()); assertTrue(alert.intValue() < Level.OFF.intValue()); @@ -74,6 +79,7 @@ public void testAlert() { public void testEmergency() { LoggingLevel emergency = LoggingLevel.EMERGENCY; assertEquals(Severity.EMERGENCY, emergency.severity()); + assertEquals(Severity.EMERGENCY, emergency.getSeverity()); assertEquals("EMERGENCY", emergency.getName()); assertTrue(emergency.intValue() > LoggingLevel.ALERT.intValue()); assertTrue(emergency.intValue() < Level.OFF.intValue()); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingTest.java index 5c05185ad268..495b067eb39d 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingTest.java @@ -44,46 +44,46 @@ public class LoggingTest { public void testListOption() { // page token ListOption listOption = ListOption.pageToken(PAGE_TOKEN); - assertEquals(PAGE_TOKEN, listOption.value()); - assertEquals(ListOption.OptionType.PAGE_TOKEN, listOption.optionType()); + assertEquals(PAGE_TOKEN, listOption.getValue()); + assertEquals(ListOption.OptionType.PAGE_TOKEN, listOption.getOptionType()); // page size listOption = ListOption.pageSize(PAGE_SIZE); - assertEquals(PAGE_SIZE, listOption.value()); - assertEquals(ListOption.OptionType.PAGE_SIZE, listOption.optionType()); + assertEquals(PAGE_SIZE, listOption.getValue()); + assertEquals(ListOption.OptionType.PAGE_SIZE, listOption.getOptionType()); } @Test public void testEntryListOption() { EntryListOption listOption = EntryListOption.pageToken(PAGE_TOKEN); - assertEquals(PAGE_TOKEN, listOption.value()); - assertEquals(EntryListOption.OptionType.PAGE_TOKEN, listOption.optionType()); + assertEquals(PAGE_TOKEN, listOption.getValue()); + assertEquals(EntryListOption.OptionType.PAGE_TOKEN, listOption.getOptionType()); // page size listOption = EntryListOption.pageSize(PAGE_SIZE); - assertEquals(PAGE_SIZE, listOption.value()); - assertEquals(EntryListOption.OptionType.PAGE_SIZE, listOption.optionType()); + assertEquals(PAGE_SIZE, listOption.getValue()); + assertEquals(EntryListOption.OptionType.PAGE_SIZE, listOption.getOptionType()); // filter listOption = EntryListOption.filter(FILTER); - assertEquals(FILTER, listOption.value()); - assertEquals(EntryListOption.OptionType.FILTER, listOption.optionType()); + assertEquals(FILTER, listOption.getValue()); + assertEquals(EntryListOption.OptionType.FILTER, listOption.getOptionType()); // sort order listOption = EntryListOption.sortOrder(SortingField.TIMESTAMP, SortingOrder.ASCENDING); - assertEquals("timestamp asc", listOption.value()); - assertEquals(EntryListOption.OptionType.ORDER_BY, listOption.optionType()); + assertEquals("timestamp asc", listOption.getValue()); + assertEquals(EntryListOption.OptionType.ORDER_BY, listOption.getOptionType()); listOption = EntryListOption.sortOrder(SortingField.TIMESTAMP, SortingOrder.DESCENDING); - assertEquals("timestamp desc", listOption.value()); - assertEquals(EntryListOption.OptionType.ORDER_BY, listOption.optionType()); + assertEquals("timestamp desc", listOption.getValue()); + assertEquals(EntryListOption.OptionType.ORDER_BY, listOption.getOptionType()); } @Test public void testWriteOption() { WriteOption writeOption = WriteOption.labels(LABELS); - assertEquals(LABELS, writeOption.value()); - assertEquals(WriteOption.OptionType.LABELS, writeOption.optionType()); + assertEquals(LABELS, writeOption.getValue()); + assertEquals(WriteOption.OptionType.LABELS, writeOption.getOptionType()); writeOption = WriteOption.logName(LOG_NAME); - assertEquals(LOG_NAME, writeOption.value()); - assertEquals(WriteOption.OptionType.LOG_NAME, writeOption.optionType()); + assertEquals(LOG_NAME, writeOption.getValue()); + assertEquals(WriteOption.OptionType.LOG_NAME, writeOption.getOptionType()); writeOption = WriteOption.resource(RESOURCE); - assertEquals(RESOURCE, writeOption.value()); - assertEquals(WriteOption.OptionType.RESOURCE, writeOption.optionType()); + assertEquals(RESOURCE, writeOption.getValue()); + assertEquals(WriteOption.OptionType.RESOURCE, writeOption.getOptionType()); } } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricInfoTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricInfoTest.java index 5b4be469cbbb..8e1682dc1701 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricInfoTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricInfoTest.java @@ -29,29 +29,34 @@ public class MetricInfoTest { private static final String NEW_NAME = "newName"; private static final String NEW_FILTER = "logName=projects/my-projectid/logs/newSyslog"; private static final String NEW_DESCRIPTION = "newDescription"; - private static final MetricInfo METRIC_INFO = MetricInfo.builder(NAME, FILTER) + private static final MetricInfo METRIC_INFO = MetricInfo.newBuilder(NAME, FILTER) + .setDescription(DESCRIPTION) + .build(); + private static final MetricInfo DEPRECATED_METRIC_INFO = MetricInfo.builder(NAME, FILTER) .description(DESCRIPTION) .build(); @Test public void testOf() { MetricInfo metricInfo = MetricInfo.of(NAME, FILTER); - assertEquals(NAME, metricInfo.name()); - assertEquals(FILTER, metricInfo.filter()); - assertNull(metricInfo.description()); + assertEquals(NAME, metricInfo.getName()); + assertEquals(FILTER, metricInfo.getFilter()); + assertNull(metricInfo.getDescription()); } @Test public void testBuilder() { - assertEquals(NAME, METRIC_INFO.name()); - assertEquals(FILTER, METRIC_INFO.filter()); - assertEquals(DESCRIPTION, METRIC_INFO.description()); + assertEquals(NAME, METRIC_INFO.getName()); + assertEquals(FILTER, METRIC_INFO.getFilter()); + assertEquals(DESCRIPTION, METRIC_INFO.getDescription()); } @Test - public void testToBuilder() { - compareMetricInfo(METRIC_INFO, METRIC_INFO.toBuilder().build()); - MetricInfo metricInfo = METRIC_INFO.toBuilder() + public void testBuilderDeprecated() { + assertEquals(NAME, DEPRECATED_METRIC_INFO.getName()); + assertEquals(FILTER, DEPRECATED_METRIC_INFO.getFilter()); + assertEquals(DESCRIPTION, DEPRECATED_METRIC_INFO.getDescription()); + MetricInfo metricInfo = DEPRECATED_METRIC_INFO.toBuilder() .name(NEW_NAME) .description(NEW_DESCRIPTION) .filter(NEW_FILTER) @@ -59,10 +64,23 @@ public void testToBuilder() { assertEquals(NEW_NAME, metricInfo.name()); assertEquals(NEW_FILTER, metricInfo.filter()); assertEquals(NEW_DESCRIPTION, metricInfo.description()); + } + + @Test + public void testToBuilder() { + compareMetricInfo(METRIC_INFO, METRIC_INFO.toBuilder().build()); + MetricInfo metricInfo = METRIC_INFO.toBuilder() + .setName(NEW_NAME) + .setDescription(NEW_DESCRIPTION) + .setFilter(NEW_FILTER) + .build(); + assertEquals(NEW_NAME, metricInfo.getName()); + assertEquals(NEW_FILTER, metricInfo.getFilter()); + assertEquals(NEW_DESCRIPTION, metricInfo.getDescription()); metricInfo = metricInfo.toBuilder() - .name(NAME) - .description(DESCRIPTION) - .filter(FILTER) + .setName(NAME) + .setDescription(DESCRIPTION) + .setFilter(FILTER) .build(); compareMetricInfo(METRIC_INFO, metricInfo); } @@ -76,9 +94,9 @@ public void testToAndFromPb() { private void compareMetricInfo(MetricInfo expected, MetricInfo value) { assertEquals(expected, value); - assertEquals(expected.name(), value.name()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.filter(), value.filter()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getFilter(), value.getFilter()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricTest.java index 839745ca7283..6f9b00edc23f 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricTest.java @@ -24,6 +24,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import com.google.common.util.concurrent.Futures; @@ -41,8 +42,8 @@ public class MetricTest { private static final String NEW_NAME = "newName"; private static final String NEW_FILTER = "logName=projects/my-projectid/logs/newSyslog"; private static final String NEW_DESCRIPTION = "newDescription"; - private static final MetricInfo METRIC_INFO = MetricInfo.builder(NAME, FILTER) - .description(DESCRIPTION) + private static final MetricInfo METRIC_INFO = MetricInfo.newBuilder(NAME, FILTER) + .setDescription(DESCRIPTION) .build(); private final Logging serviceMockReturnsOptions = createStrictMock(Logging.class); private final LoggingOptions mockOptions = createMock(LoggingOptions.class); @@ -70,7 +71,22 @@ public void tearDown() throws Exception { public void testBuilder() { initializeExpectedMetric(2); replay(logging); - MetricInfo builtMetric = expectedMetric.toBuilder() + Metric builtMetric = expectedMetric.toBuilder() + .setName(NEW_NAME) + .setFilter(NEW_FILTER) + .setDescription(NEW_DESCRIPTION) + .build(); + assertEquals(NEW_NAME, builtMetric.getName()); + assertEquals(NEW_DESCRIPTION, builtMetric.getDescription()); + assertEquals(NEW_FILTER, builtMetric.getFilter()); + assertSame(serviceMockReturnsOptions, builtMetric.getLogging()); + } + + @Test + public void testBuilderDeprecated() { + initializeExpectedMetric(2); + replay(logging); + Metric builtMetric = expectedMetric.toBuilder() .name(NEW_NAME) .filter(NEW_FILTER) .description(NEW_DESCRIPTION) @@ -78,6 +94,7 @@ public void testBuilder() { assertEquals(NEW_NAME, builtMetric.name()); assertEquals(NEW_DESCRIPTION, builtMetric.description()); assertEquals(NEW_FILTER, builtMetric.filter()); + assertSame(serviceMockReturnsOptions, builtMetric.logging()); } @Test @@ -90,7 +107,7 @@ public void testToBuilder() { @Test public void testReload() { initializeExpectedMetric(2); - MetricInfo updatedInfo = METRIC_INFO.toBuilder().filter(NEW_FILTER).build(); + MetricInfo updatedInfo = METRIC_INFO.toBuilder().setFilter(NEW_FILTER).build(); Metric expectedMetric = new Metric(serviceMockReturnsOptions, new MetricInfo.BuilderImpl(updatedInfo)); expect(logging.options()).andReturn(mockOptions); @@ -114,7 +131,7 @@ public void testReloadNull() { @Test public void testReloadAsync() throws ExecutionException, InterruptedException { initializeExpectedMetric(2); - MetricInfo updatedInfo = METRIC_INFO.toBuilder().filter(NEW_FILTER).build(); + MetricInfo updatedInfo = METRIC_INFO.toBuilder().setFilter(NEW_FILTER).build(); Metric expectedMetric = new Metric(serviceMockReturnsOptions, new MetricInfo.BuilderImpl(updatedInfo)); expect(logging.options()).andReturn(mockOptions); expect(logging.getMetricAsync(NAME)) @@ -138,28 +155,28 @@ public void testReloadAsyncNull() throws ExecutionException, InterruptedExceptio @Test public void testUpdate() { initializeExpectedMetric(2); - MetricInfo updatedInfo = METRIC_INFO.toBuilder().filter(NEW_FILTER).build(); + MetricInfo updatedInfo = METRIC_INFO.toBuilder().setFilter(NEW_FILTER).build(); Metric expectedMetric = new Metric(serviceMockReturnsOptions, new MetricInfo.BuilderImpl(updatedInfo)); expect(logging.options()).andReturn(mockOptions).times(2); expect(logging.update(expectedMetric)).andReturn(expectedMetric); replay(logging); initializeMetric(); - Metric updatedMetric = metric.toBuilder().filter(NEW_FILTER).build().update(); + Metric updatedMetric = metric.toBuilder().setFilter(NEW_FILTER).build().update(); compareMetric(expectedMetric, updatedMetric); } @Test public void testUpdateAsync() throws ExecutionException, InterruptedException { initializeExpectedMetric(2); - MetricInfo updatedInfo = METRIC_INFO.toBuilder().filter(NEW_FILTER).build(); + MetricInfo updatedInfo = METRIC_INFO.toBuilder().setFilter(NEW_FILTER).build(); Metric expectedMetric = new Metric(serviceMockReturnsOptions, new MetricInfo.BuilderImpl(updatedInfo)); expect(logging.options()).andReturn(mockOptions).times(2); expect(logging.updateAsync(expectedMetric)).andReturn(Futures.immediateFuture(expectedMetric)); replay(logging); initializeMetric(); - Metric updatedMetric = metric.toBuilder().filter(NEW_FILTER).build().updateAsync().get(); + Metric updatedMetric = metric.toBuilder().setFilter(NEW_FILTER).build().updateAsync().get(); compareMetric(expectedMetric, updatedMetric); } @@ -205,9 +222,9 @@ public void testDeleteAsyncFalse() throws ExecutionException, InterruptedExcepti private void compareMetric(Metric expected, Metric value) { assertEquals(expected, value); - assertEquals(expected.name(), value.name()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.filter(), value.filter()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getFilter(), value.getFilter()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/OperationTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/OperationTest.java index 9de7d6fa61c9..1b7601379b05 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/OperationTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/OperationTest.java @@ -28,23 +28,30 @@ public class OperationTest { private static final String PRODUCER = "producer"; private static final Boolean FIRST = true; private static final Boolean LAST = false; - private static final Operation OPERATION = Operation.builder(ID, PRODUCER) + private static final Operation OPERATION = Operation.newBuilder(ID, PRODUCER) + .setFirst(FIRST) + .setLast(LAST) + .build(); + private static final Operation DEPRECATED_OPERATION = Operation.builder(ID, PRODUCER) .first(FIRST) .last(LAST) .build(); @Test public void testBuilder() { - assertEquals(ID, OPERATION.id()); - assertEquals(PRODUCER, OPERATION.producer()); + assertEquals(ID, OPERATION.getId()); + assertEquals(PRODUCER, OPERATION.getProducer()); assertTrue(OPERATION.first()); assertFalse(OPERATION.last()); } @Test - public void testToBuilder() { - compareLogOperation(OPERATION, OPERATION.toBuilder().build()); - Operation operation = OPERATION.toBuilder() + public void testBuilderDeprecated() { + assertEquals(ID, DEPRECATED_OPERATION.id()); + assertEquals(PRODUCER, DEPRECATED_OPERATION.producer()); + assertTrue(DEPRECATED_OPERATION.first()); + assertFalse(DEPRECATED_OPERATION.last()); + Operation operation = DEPRECATED_OPERATION.toBuilder() .id("newId") .producer("newProducer") .first(false) @@ -54,11 +61,26 @@ public void testToBuilder() { assertEquals("newProducer", operation.producer()); assertFalse(operation.first()); assertTrue(operation.last()); + } + + @Test + public void testToBuilder() { + compareLogOperation(OPERATION, OPERATION.toBuilder().build()); + Operation operation = OPERATION.toBuilder() + .setId("newId") + .setProducer("newProducer") + .setFirst(false) + .setLast(true) + .build(); + assertEquals("newId", operation.getId()); + assertEquals("newProducer", operation.getProducer()); + assertFalse(operation.first()); + assertTrue(operation.last()); operation = operation.toBuilder() - .id(ID) - .producer(PRODUCER) - .first(FIRST) - .last(LAST) + .setId(ID) + .setProducer(PRODUCER) + .setFirst(FIRST) + .setLast(LAST) .build(); compareLogOperation(OPERATION, operation); } @@ -66,8 +88,8 @@ public void testToBuilder() { @Test public void testOf() { Operation operation = Operation.of(ID, PRODUCER); - assertEquals(ID, operation.id()); - assertEquals(PRODUCER, operation.producer()); + assertEquals(ID, operation.getId()); + assertEquals(PRODUCER, operation.getProducer()); assertFalse(operation.first()); assertFalse(operation.last()); } @@ -81,8 +103,8 @@ public void testToAndFromPb() { private void compareLogOperation(Operation expected, Operation value) { assertEquals(expected, value); - assertEquals(expected.id(), value.id()); - assertEquals(expected.producer(), value.producer()); + assertEquals(expected.getId(), value.getId()); + assertEquals(expected.getProducer(), value.getProducer()); assertEquals(expected.first(), value.first()); assertEquals(expected.last(), value.last()); assertEquals(expected.hashCode(), value.hashCode()); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/OptionTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/OptionTest.java index 536a9f6d4ef4..274c41bb345f 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/OptionTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/OptionTest.java @@ -55,11 +55,11 @@ public void testHashCode() { @Test public void testConstructor() { - assertEquals(OPTION_TYPE, OPTION.optionType()); - assertEquals(VALUE, OPTION.value()); + assertEquals(OPTION_TYPE, OPTION.getOptionType()); + assertEquals(VALUE, OPTION.getValue()); Option option = new Option(OPTION_TYPE, null) {}; - assertEquals(OPTION_TYPE, option.optionType()); - assertNull(option.value()); + assertEquals(OPTION_TYPE, option.getOptionType()); + assertNull(option.getValue()); thrown.expect(NullPointerException.class); new Option(null, VALUE) {}; } @@ -67,10 +67,10 @@ public void testConstructor() { @Test public void testListOption() { Option option = ListOption.pageSize(42); - assertEquals(ListOption.OptionType.PAGE_SIZE, option.optionType()); - assertEquals(42, option.value()); + assertEquals(ListOption.OptionType.PAGE_SIZE, option.getOptionType()); + assertEquals(42, option.getValue()); option = ListOption.pageToken("cursor"); - assertEquals(ListOption.OptionType.PAGE_TOKEN, option.optionType()); - assertEquals("cursor", option.value()); + assertEquals(ListOption.OptionType.PAGE_TOKEN, option.getOptionType()); + assertEquals("cursor", option.getValue()); } } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/PayloadTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/PayloadTest.java index d2e4705a6441..bc77fc3df0bc 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/PayloadTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/PayloadTest.java @@ -96,6 +96,21 @@ public class PayloadTest { @Test public void testOf() { + assertEquals(Type.STRING, STRING_PAYLOAD.getType()); + assertEquals(STRING_DATA, STRING_PAYLOAD.getData()); + assertEquals(Type.JSON, JSON_PAYLOAD.getType()); + assertEquals(STRUCT_DATA, JSON_PAYLOAD.getData()); + assertEquals(JSON_DATA, JSON_PAYLOAD.getDataAsMap()); + assertEquals(Type.PROTO, PROTO_PAYLOAD.getType()); + assertEquals(PROTO_DATA, PROTO_PAYLOAD.getData()); + JsonPayload jsonPayload = JsonPayload.of(STRUCT_DATA); + assertEquals(Type.JSON, jsonPayload.getType()); + assertEquals(STRUCT_DATA, jsonPayload.getData()); + assertEquals(JSON_DATA, jsonPayload.getDataAsMap()); + } + + @Test + public void testOfDeprecated() { assertEquals(Type.STRING, STRING_PAYLOAD.type()); assertEquals(STRING_DATA, STRING_PAYLOAD.data()); assertEquals(Type.JSON, JSON_PAYLOAD.type()); @@ -124,8 +139,8 @@ public void testToAndFromPb() { private void comparePayload(Payload expected, Payload value) { assertEquals(expected, value); - assertEquals(expected.type(), value.type()); - assertEquals(expected.data(), value.data()); + assertEquals(expected.getType(), value.getType()); + assertEquals(expected.getData(), value.getData()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java index 2cd728c8f910..ca172c933506 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java @@ -44,9 +44,9 @@ public class SerializationTest extends BaseSerializationTest { .authCredentials(AuthCredentials.noAuth()) .host("localhost") .build().service(); - private static final HttpRequest HTTP_REQUEST = HttpRequest.builder() - .requestMethod(HttpRequest.RequestMethod.GET) - .status(404) + private static final HttpRequest HTTP_REQUEST = HttpRequest.newBuilder() + .setRequestMethod(HttpRequest.RequestMethod.GET) + .setStatus(404) .build(); private static final Operation OPERATION = Operation.of("id", "producer"); private static final StringPayload STRING_PAYLOAD = StringPayload.of("payload"); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkInfoTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkInfoTest.java index e22b2259e82f..265f52d428d1 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkInfoTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkInfoTest.java @@ -40,30 +40,61 @@ public class SinkInfoTest { DatasetDestination.of("project", "dataset"); private static final TopicDestination TOPIC_DESTINATION = TopicDestination.of("project", "topic"); - private static final SinkInfo BUCKET_SINK_INFO = SinkInfo.builder(NAME, BUCKET_DESTINATION) - .filter(FILTER) - .versionFormat(VERSION) + private static final SinkInfo BUCKET_SINK_INFO = SinkInfo.newBuilder(NAME, BUCKET_DESTINATION) + .setFilter(FILTER) + .setVersionFormat(VERSION) .build(); - private static final SinkInfo DATASET_SINK_INFO = SinkInfo.builder(NAME, DATASET_DESTINATION) - .filter(FILTER) - .versionFormat(VERSION) + private static final SinkInfo DATASET_SINK_INFO = SinkInfo.newBuilder(NAME, DATASET_DESTINATION) + .setFilter(FILTER) + .setVersionFormat(VERSION) .build(); - private static final SinkInfo TOPIC_SINK_INFO = SinkInfo.builder(NAME, TOPIC_DESTINATION) - .filter(FILTER) - .versionFormat(VERSION) + private static final SinkInfo TOPIC_SINK_INFO = SinkInfo.newBuilder(NAME, TOPIC_DESTINATION) + .setFilter(FILTER) + .setVersionFormat(VERSION) .build(); + private static final SinkInfo DEPRECATED_BUCKET_SINK_INFO = + SinkInfo.builder(NAME, BUCKET_DESTINATION) + .filter(FILTER) + .versionFormat(VERSION) + .build(); + private static final SinkInfo DEPRECATED_DATASET_SINK_INFO = + SinkInfo.builder(NAME, DATASET_DESTINATION) + .filter(FILTER) + .versionFormat(VERSION) + .build(); + private static final SinkInfo DEPRECATED_TOPIC_SINK_INFO = + SinkInfo.builder(NAME, TOPIC_DESTINATION) + .filter(FILTER) + .versionFormat(VERSION) + .build(); @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testOfBucketDestination() { + assertEquals(Destination.Type.BUCKET, BUCKET_DESTINATION.getType()); + assertEquals("bucket", BUCKET_DESTINATION.getBucket()); + } + + @Test + public void testOfBucketDestinationDeprecated() { assertEquals(Destination.Type.BUCKET, BUCKET_DESTINATION.type()); assertEquals("bucket", BUCKET_DESTINATION.bucket()); } @Test public void testOfDatasetDestination() { + assertEquals(Destination.Type.DATASET, DATASET_DESTINATION.getType()); + assertEquals("project", DATASET_DESTINATION.getProject()); + assertEquals("dataset", DATASET_DESTINATION.getDataset()); + DatasetDestination datasetDestination = DatasetDestination.of("dataset"); + assertNull(datasetDestination.getProject()); + assertEquals("dataset", datasetDestination.getDataset()); + } + + @Test + public void testOfDatasetDestinationDeprecated() { assertEquals(Destination.Type.DATASET, DATASET_DESTINATION.type()); assertEquals("project", DATASET_DESTINATION.project()); assertEquals("dataset", DATASET_DESTINATION.dataset()); @@ -74,6 +105,16 @@ public void testOfDatasetDestination() { @Test public void testOfTopicDestination() { + assertEquals(Destination.Type.TOPIC, TOPIC_DESTINATION.getType()); + assertEquals("project", TOPIC_DESTINATION.getProject()); + assertEquals("topic", TOPIC_DESTINATION.getTopic()); + TopicDestination topicDestination = TopicDestination.of("topic"); + assertNull(topicDestination.getProject()); + assertEquals("topic", topicDestination.getTopic()); + } + + @Test + public void testOfTopicDestinationDeprecated() { assertEquals(Destination.Type.TOPIC, TOPIC_DESTINATION.type()); assertEquals("project", TOPIC_DESTINATION.project()); assertEquals("topic", TOPIC_DESTINATION.topic()); @@ -85,18 +126,18 @@ public void testOfTopicDestination() { @Test public void testToAndFromPbDestination() { BucketDestination bucketDestination = Destination.fromPb(BUCKET_DESTINATION.toPb("other")); - assertEquals(Destination.Type.BUCKET, bucketDestination.type()); - assertEquals("bucket", bucketDestination.bucket()); + assertEquals(Destination.Type.BUCKET, bucketDestination.getType()); + assertEquals("bucket", bucketDestination.getBucket()); compareBucketDestination(BUCKET_DESTINATION, bucketDestination); DatasetDestination datasetDestination = Destination.fromPb(DATASET_DESTINATION.toPb("other")); - assertEquals(Destination.Type.DATASET, datasetDestination.type()); - assertEquals("project", datasetDestination.project()); - assertEquals("dataset", datasetDestination.dataset()); + assertEquals(Destination.Type.DATASET, datasetDestination.getType()); + assertEquals("project", datasetDestination.getProject()); + assertEquals("dataset", datasetDestination.getDataset()); compareDatasetDestination(DATASET_DESTINATION, datasetDestination); TopicDestination topicDestination = Destination.fromPb(TOPIC_DESTINATION.toPb("other")); - assertEquals(Destination.Type.TOPIC, topicDestination.type()); - assertEquals("project", topicDestination.project()); - assertEquals("topic", topicDestination.topic()); + assertEquals(Destination.Type.TOPIC, topicDestination.getType()); + assertEquals("project", topicDestination.getProject()); + assertEquals("topic", topicDestination.getTopic()); compareTopicDestination(TOPIC_DESTINATION, topicDestination); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("wrongDestination is not a valid sink destination"); @@ -108,35 +149,44 @@ public void testToAndFromPbDestination_NoProjectId() { DatasetDestination datasetDestination = DatasetDestination.fromPb(DatasetDestination.of("dataset").toPb("project")); compareDatasetDestination(DATASET_DESTINATION, datasetDestination); - assertEquals("project", datasetDestination.project()); + assertEquals("project", datasetDestination.getProject()); TopicDestination topicDestination = TopicDestination.fromPb(TopicDestination.of("topic").toPb("project")); - assertEquals("project", topicDestination.project()); + assertEquals("project", topicDestination.getProject()); compareTopicDestination(TOPIC_DESTINATION, topicDestination); } @Test public void testBuilder() { - assertEquals(NAME, BUCKET_SINK_INFO.name()); - assertEquals(BUCKET_DESTINATION, BUCKET_SINK_INFO.destination()); - assertEquals(FILTER, BUCKET_SINK_INFO.filter()); - assertEquals(VERSION, BUCKET_SINK_INFO.versionFormat()); - assertEquals(NAME, DATASET_SINK_INFO.name()); - assertEquals(DATASET_DESTINATION, DATASET_SINK_INFO.destination()); - assertEquals(FILTER, DATASET_SINK_INFO.filter()); - assertEquals(VERSION, DATASET_SINK_INFO.versionFormat()); - assertEquals(NAME, TOPIC_SINK_INFO.name()); - assertEquals(TOPIC_DESTINATION, TOPIC_SINK_INFO.destination()); - assertEquals(FILTER, TOPIC_SINK_INFO.filter()); - assertEquals(VERSION, TOPIC_SINK_INFO.versionFormat()); + assertEquals(NAME, BUCKET_SINK_INFO.getName()); + assertEquals(BUCKET_DESTINATION, BUCKET_SINK_INFO.getDestination()); + assertEquals(FILTER, BUCKET_SINK_INFO.getFilter()); + assertEquals(VERSION, BUCKET_SINK_INFO.getVersionFormat()); + assertEquals(NAME, DATASET_SINK_INFO.getName()); + assertEquals(DATASET_DESTINATION, DATASET_SINK_INFO.getDestination()); + assertEquals(FILTER, DATASET_SINK_INFO.getFilter()); + assertEquals(VERSION, DATASET_SINK_INFO.getVersionFormat()); + assertEquals(NAME, TOPIC_SINK_INFO.getName()); + assertEquals(TOPIC_DESTINATION, TOPIC_SINK_INFO.getDestination()); + assertEquals(FILTER, TOPIC_SINK_INFO.getFilter()); + assertEquals(VERSION, TOPIC_SINK_INFO.getVersionFormat()); } @Test - public void testToBuilder() { - compareSinkInfo(BUCKET_SINK_INFO, BUCKET_SINK_INFO.toBuilder().build()); - compareSinkInfo(DATASET_SINK_INFO, DATASET_SINK_INFO.toBuilder().build()); - compareSinkInfo(TOPIC_SINK_INFO, TOPIC_SINK_INFO.toBuilder().build()); - SinkInfo updatedSinkInfo = BUCKET_SINK_INFO.toBuilder() + public void testBuilderDeprecated() { + assertEquals(NAME, DEPRECATED_BUCKET_SINK_INFO.name()); + assertEquals(BUCKET_DESTINATION, DEPRECATED_BUCKET_SINK_INFO.destination()); + assertEquals(FILTER, DEPRECATED_BUCKET_SINK_INFO.filter()); + assertEquals(VERSION, DEPRECATED_BUCKET_SINK_INFO.versionFormat()); + assertEquals(NAME, DEPRECATED_DATASET_SINK_INFO.name()); + assertEquals(DATASET_DESTINATION, DEPRECATED_DATASET_SINK_INFO.destination()); + assertEquals(FILTER, DEPRECATED_DATASET_SINK_INFO.filter()); + assertEquals(VERSION, DEPRECATED_DATASET_SINK_INFO.versionFormat()); + assertEquals(NAME, DEPRECATED_TOPIC_SINK_INFO.name()); + assertEquals(TOPIC_DESTINATION, DEPRECATED_TOPIC_SINK_INFO.destination()); + assertEquals(FILTER, DEPRECATED_TOPIC_SINK_INFO.filter()); + assertEquals(VERSION, DEPRECATED_TOPIC_SINK_INFO.versionFormat()); + SinkInfo updatedSinkInfo = DEPRECATED_BUCKET_SINK_INFO.toBuilder() .destination(TOPIC_DESTINATION) .name("newName") .filter("logName=projects/my-projectid/logs/syslog") @@ -146,11 +196,28 @@ public void testToBuilder() { assertEquals(TOPIC_DESTINATION, updatedSinkInfo.destination()); assertEquals("logName=projects/my-projectid/logs/syslog", updatedSinkInfo.filter()); assertEquals(VersionFormat.V2, updatedSinkInfo.versionFormat()); + } + + @Test + public void testToBuilder() { + compareSinkInfo(BUCKET_SINK_INFO, BUCKET_SINK_INFO.toBuilder().build()); + compareSinkInfo(DATASET_SINK_INFO, DATASET_SINK_INFO.toBuilder().build()); + compareSinkInfo(TOPIC_SINK_INFO, TOPIC_SINK_INFO.toBuilder().build()); + SinkInfo updatedSinkInfo = BUCKET_SINK_INFO.toBuilder() + .setDestination(TOPIC_DESTINATION) + .setName("newName") + .setFilter("logName=projects/my-projectid/logs/syslog") + .setVersionFormat(VersionFormat.V2) + .build(); + assertEquals("newName", updatedSinkInfo.getName()); + assertEquals(TOPIC_DESTINATION, updatedSinkInfo.getDestination()); + assertEquals("logName=projects/my-projectid/logs/syslog", updatedSinkInfo.getFilter()); + assertEquals(VersionFormat.V2, updatedSinkInfo.getVersionFormat()); updatedSinkInfo = BUCKET_SINK_INFO.toBuilder() - .destination(BUCKET_DESTINATION) - .name(NAME) - .filter(FILTER) - .versionFormat(VersionFormat.V1) + .setDestination(BUCKET_DESTINATION) + .setName(NAME) + .setFilter(FILTER) + .setVersionFormat(VersionFormat.V1) .build(); assertEquals(BUCKET_SINK_INFO, updatedSinkInfo); } @@ -182,33 +249,33 @@ public void testToAndFromPb_NoProjectId() { private void compareBucketDestination(BucketDestination expected, BucketDestination value) { assertEquals(expected, value); - assertEquals(expected.bucket(), value.bucket()); + assertEquals(expected.getBucket(), value.getBucket()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } private void compareDatasetDestination(DatasetDestination expected, DatasetDestination value) { assertEquals(expected, value); - assertEquals(expected.project(), value.project()); - assertEquals(expected.dataset(), value.dataset()); + assertEquals(expected.getProject(), value.getProject()); + assertEquals(expected.getDataset(), value.getDataset()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } private void compareTopicDestination(TopicDestination expected, TopicDestination value) { assertEquals(expected, value); - assertEquals(expected.project(), value.project()); - assertEquals(expected.topic(), value.topic()); + assertEquals(expected.getProject(), value.getProject()); + assertEquals(expected.getTopic(), value.getTopic()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } private void compareSinkInfo(SinkInfo expected, SinkInfo value) { assertEquals(expected, value); - assertEquals(expected.name(), value.name()); - assertEquals(expected.destination(), value.destination()); - assertEquals(expected.filter(), value.filter()); - assertEquals(expected.versionFormat(), value.versionFormat()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getDestination(), value.getDestination()); + assertEquals(expected.getFilter(), value.getFilter()); + assertEquals(expected.getVersionFormat(), value.getVersionFormat()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkTest.java index c7afe584d01f..de4325765ef5 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkTest.java @@ -48,9 +48,9 @@ public class SinkTest { private static final VersionFormat NEW_VERSION = VersionFormat.V2; private static final BucketDestination BUCKET_DESTINATION = BucketDestination.of("bucket"); private static final DatasetDestination DATASET_DESTINATION = DatasetDestination.of("dataset"); - private static final SinkInfo SINK_INFO = SinkInfo.builder(NAME, BUCKET_DESTINATION) - .filter(FILTER) - .versionFormat(VERSION) + private static final SinkInfo SINK_INFO = SinkInfo.newBuilder(NAME, BUCKET_DESTINATION) + .setFilter(FILTER) + .setVersionFormat(VERSION) .build(); private final Logging serviceMockReturnsOptions = createStrictMock(Logging.class); private final LoggingOptions mockOptions = createMock(LoggingOptions.class); @@ -78,7 +78,23 @@ public void tearDown() throws Exception { public void testBuilder() { initializeExpectedSink(2); replay(logging); - SinkInfo builtSink = expectedSink.toBuilder() + Sink builtSink = expectedSink.toBuilder() + .setName(NEW_NAME) + .setFilter(NEW_FILTER) + .setDestination(DATASET_DESTINATION) + .setVersionFormat(NEW_VERSION) + .build(); + assertEquals(NEW_NAME, builtSink.getName()); + assertEquals(DATASET_DESTINATION, builtSink.getDestination()); + assertEquals(NEW_FILTER, builtSink.getFilter()); + assertEquals(NEW_VERSION, builtSink.getVersionFormat()); + } + + @Test + public void testBuilderDeprecated() { + initializeExpectedSink(2); + replay(logging); + Sink builtSink = expectedSink.toBuilder() .name(NEW_NAME) .filter(NEW_FILTER) .destination(DATASET_DESTINATION) @@ -100,7 +116,7 @@ public void testToBuilder() { @Test public void testReload() { initializeExpectedSink(2); - SinkInfo updatedInfo = SINK_INFO.toBuilder().filter(NEW_FILTER).build(); + SinkInfo updatedInfo = SINK_INFO.toBuilder().setFilter(NEW_FILTER).build(); Sink expectedSink = new Sink(serviceMockReturnsOptions, new SinkInfo.BuilderImpl(updatedInfo)); expect(logging.options()).andReturn(mockOptions); @@ -124,7 +140,7 @@ public void testReloadNull() { @Test public void testReloadAsync() throws ExecutionException, InterruptedException { initializeExpectedSink(2); - SinkInfo updatedInfo = SINK_INFO.toBuilder().filter(NEW_FILTER).build(); + SinkInfo updatedInfo = SINK_INFO.toBuilder().setFilter(NEW_FILTER).build(); Sink expectedSink = new Sink(serviceMockReturnsOptions, new SinkInfo.BuilderImpl(updatedInfo)); expect(logging.options()).andReturn(mockOptions); expect(logging.getSinkAsync(NAME)) @@ -148,26 +164,26 @@ public void testReloadAsyncNull() throws ExecutionException, InterruptedExceptio @Test public void testUpdate() { initializeExpectedSink(2); - SinkInfo updatedInfo = SINK_INFO.toBuilder().filter(NEW_FILTER).build(); + SinkInfo updatedInfo = SINK_INFO.toBuilder().setFilter(NEW_FILTER).build(); Sink expectedSink = new Sink(serviceMockReturnsOptions, new SinkInfo.BuilderImpl(updatedInfo)); expect(logging.options()).andReturn(mockOptions).times(2); expect(logging.update(expectedSink)).andReturn(expectedSink); replay(logging); initializeSink(); - Sink updatedSink = sink.toBuilder().filter(NEW_FILTER).build().update(); + Sink updatedSink = sink.toBuilder().setFilter(NEW_FILTER).build().update(); compareSink(expectedSink, updatedSink); } @Test public void testUpdateAsync() throws ExecutionException, InterruptedException { initializeExpectedSink(2); - SinkInfo updatedInfo = SINK_INFO.toBuilder().filter(NEW_FILTER).build(); + SinkInfo updatedInfo = SINK_INFO.toBuilder().setFilter(NEW_FILTER).build(); Sink expectedSink = new Sink(serviceMockReturnsOptions, new SinkInfo.BuilderImpl(updatedInfo)); expect(logging.options()).andReturn(mockOptions).times(2); expect(logging.updateAsync(expectedSink)).andReturn(Futures.immediateFuture(expectedSink)); replay(logging); initializeSink(); - Sink updatedSink = sink.toBuilder().filter(NEW_FILTER).build().updateAsync().get(); + Sink updatedSink = sink.toBuilder().setFilter(NEW_FILTER).build().updateAsync().get(); compareSink(expectedSink, updatedSink); } @@ -213,10 +229,10 @@ public void testDeleteAsyncFalse() throws ExecutionException, InterruptedExcepti private void compareSink(Sink expected, Sink value) { assertEquals(expected, value); - assertEquals(expected.name(), value.name()); - assertEquals(expected.destination(), value.destination()); - assertEquals(expected.filter(), value.filter()); - assertEquals(expected.versionFormat(), value.versionFormat()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getDestination(), value.getDestination()); + assertEquals(expected.getFilter(), value.getFilter()); + assertEquals(expected.getVersionFormat(), value.getVersionFormat()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/StructsTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/StructsTest.java index 7b6a0df4e612..34b5bb5a9c34 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/StructsTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/StructsTest.java @@ -100,7 +100,7 @@ private void checkMapField(Map map, String key, T expected) { } private void checkStructField(Struct struct, String key, Value expected) { - Map map = struct.getFields(); + Map map = struct.getFieldsMap(); checkMapField(map, key, expected); } @@ -158,7 +158,7 @@ public void testNewStruct() { @Test public void testNewStructEmpty() { Struct struct = Structs.newStruct(EMPTY_MAP); - assertTrue(struct.getFields().isEmpty()); + assertTrue(struct.getFieldsMap().isEmpty()); } @Test diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/it/ITLoggingTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/it/ITLoggingTest.java index e4e70c7cc7ca..f3df67838816 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/it/ITLoggingTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/it/ITLoggingTest.java @@ -35,7 +35,7 @@ public class ITLoggingTest extends BaseSystemTest { @BeforeClass public static void beforeClass() { RemoteLoggingHelper helper = RemoteLoggingHelper.create(); - logging = helper.options().service(); + logging = helper.getOptions().service(); } @AfterClass From 9c0efb7cc09ebbffb75fd671324200e5fb172f2f Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Fri, 21 Oct 2016 17:15:57 +0200 Subject: [PATCH 16/32] Rename setters/getters/builders for ResourceManager classes to meet proto conventions (#1321) * Rename setters/getters/builders for ResourceManager classes to meet proto conventions * Update ResourceManager examples, snippets and READMEs to use renamed getters/setters/builders --- README.md | 6 +- .../ResourceManagerExample.java | 12 +- .../snippets/GetOrCreateProject.java | 4 +- .../snippets/UpdateAndListProjects.java | 6 +- google-cloud-resourcemanager/README.md | 4 +- .../google/cloud/resourcemanager/Option.java | 4 +- .../google/cloud/resourcemanager/Project.java | 60 +++-- .../cloud/resourcemanager/ProjectInfo.java | 147 ++++++++++-- .../resourcemanager/ResourceManagerImpl.java | 2 +- .../cloud/resourcemanager/package-info.java | 6 +- .../testing/LocalResourceManagerHelper.java | 8 + .../resourcemanager/testing/package-info.java | 2 +- .../cloud/resourcemanager/OptionTest.java | 8 +- .../resourcemanager/ProjectInfoTest.java | 84 ++++--- .../cloud/resourcemanager/ProjectTest.java | 103 +++++---- .../ResourceManagerImplTest.java | 216 +++++++++--------- .../resourcemanager/SerializationTest.java | 14 +- .../LocalResourceManagerHelperTest.java | 2 +- 18 files changed, 442 insertions(+), 246 deletions(-) diff --git a/README.md b/README.md index 0230de56ae63..2a09189e7879 100644 --- a/README.md +++ b/README.md @@ -512,13 +512,13 @@ if (project != null) { .addLabel("launch-status", "in-development") .build() .replace(); - System.out.println("Updated the labels of project " + newProject.projectId() - + " to be " + newProject.labels()); + System.out.println("Updated the labels of project " + newProject.getProjectId() + + " to be " + newProject.getLabels()); } Iterator projectIterator = resourceManager.list().iterateAll(); System.out.println("Projects I can view:"); while (projectIterator.hasNext()) { - System.out.println(projectIterator.next().projectId()); + System.out.println(projectIterator.next().getProjectId()); } ``` diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/ResourceManagerExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/ResourceManagerExample.java index 118b374d305d..68589ce59582 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/ResourceManagerExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/ResourceManagerExample.java @@ -64,7 +64,7 @@ public void run(ResourceManager resourceManager, String... args) { } } Project project = - resourceManager.create(ProjectInfo.builder(projectId).labels(labels).build()); + resourceManager.create(ProjectInfo.newBuilder(projectId).setLabels(labels).build()); System.out.printf( "Successfully created project '%s': %s.%n", projectId, projectDetails(project)); } @@ -160,15 +160,15 @@ public String[] getOptionalParams() { private static String projectDetails(ProjectInfo project) { return new StringBuilder() .append("{projectId:") - .append(project.projectId()) + .append(project.getProjectId()) .append(", projectNumber:") - .append(project.projectNumber()) + .append(project.getProjectNumber()) .append(", createTimeMillis:") - .append(project.createTimeMillis()) + .append(project.getCreateTimeMillis()) .append(", state:") - .append(project.state()) + .append(project.getState()) .append(", labels:") - .append(project.labels()) + .append(project.getLabels()) .append("}") .toString(); } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/GetOrCreateProject.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/GetOrCreateProject.java index 796e29bc3b0c..79278c77affe 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/GetOrCreateProject.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/GetOrCreateProject.java @@ -42,8 +42,8 @@ public static void main(String... args) { Project project = resourceManager.get(projectId); if (project == null) { // Create a project. - project = resourceManager.create(ProjectInfo.builder(projectId).build()); + project = resourceManager.create(ProjectInfo.newBuilder(projectId).build()); } - System.out.println("Got project " + project.projectId() + " from the server."); + System.out.println("Got project " + project.getProjectId() + " from the server."); } } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/UpdateAndListProjects.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/UpdateAndListProjects.java index 2dba787279f2..0a502787316e 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/UpdateAndListProjects.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/UpdateAndListProjects.java @@ -48,15 +48,15 @@ public static void main(String... args) { .addLabel("launch-status", "in-development") .build() .replace(); - System.out.println("Updated the labels of project " + newProject.projectId() - + " to be " + newProject.labels()); + System.out.println("Updated the labels of project " + newProject.getProjectId() + + " to be " + newProject.getLabels()); } // List all the projects you have permission to view. Iterator projectIterator = resourceManager.list().iterateAll(); System.out.println("Projects I can view:"); while (projectIterator.hasNext()) { - System.out.println(projectIterator.next().projectId()); + System.out.println(projectIterator.next().getProjectId()); } } } diff --git a/google-cloud-resourcemanager/README.md b/google-cloud-resourcemanager/README.md index c41fb5593577..73ca172f3658 100644 --- a/google-cloud-resourcemanager/README.md +++ b/google-cloud-resourcemanager/README.md @@ -117,7 +117,7 @@ project ID). ```java String projectId = "my-globally-unique-project-id"; // Change to a unique project ID -Project project = resourceManager.create(ProjectInfo.builder(projectId).build()); +Project project = resourceManager.create(ProjectInfo.newBuilder(projectId).build()); ``` Note that the return value from `create` is a `Project` that includes additional read-only @@ -159,7 +159,7 @@ Then add the following code to print a list of projects you can view: Iterator projectIterator = resourceManager.list().iterateAll(); System.out.println("Projects I can view:"); while (projectIterator.hasNext()) { - System.out.println(projectIterator.next().projectId()); + System.out.println(projectIterator.next().getProjectId()); } ``` diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/Option.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/Option.java index ae53ad7004b4..33a0f0ecafbf 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/Option.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/Option.java @@ -39,11 +39,11 @@ abstract class Option implements Serializable { this.value = value; } - ResourceManagerRpc.Option rpcOption() { + ResourceManagerRpc.Option getRpcOption() { return rpcOption; } - Object value() { + Object getValue() { return value; } diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/Project.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/Project.java index b24830c983c4..a34765c1c94b 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/Project.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/Project.java @@ -54,14 +54,26 @@ public static class Builder extends ProjectInfo.Builder { } @Override + @Deprecated public Builder name(String name) { - infoBuilder.name(name); + return setName(name); + } + + @Override + public Builder setName(String name) { + infoBuilder.setName(name); return this; } @Override + @Deprecated public Builder projectId(String projectId) { - infoBuilder.projectId(projectId); + return setProjectId(projectId); + } + + @Override + public Builder setProjectId(String projectId) { + infoBuilder.setProjectId(projectId); return this; } @@ -84,32 +96,38 @@ public Builder clearLabels() { } @Override + @Deprecated public Builder labels(Map labels) { - infoBuilder.labels(labels); + return setLabels(labels); + } + + @Override + public Builder setLabels(Map labels) { + infoBuilder.setLabels(labels); return this; } @Override - Builder projectNumber(Long projectNumber) { - infoBuilder.projectNumber(projectNumber); + Builder setProjectNumber(Long projectNumber) { + infoBuilder.setProjectNumber(projectNumber); return this; } @Override - Builder state(State state) { - infoBuilder.state(state); + Builder setState(State state) { + infoBuilder.setState(state); return this; } @Override - Builder createTimeMillis(Long createTimeMillis) { - infoBuilder.createTimeMillis(createTimeMillis); + Builder setCreateTimeMillis(Long createTimeMillis) { + infoBuilder.setCreateTimeMillis(createTimeMillis); return this; } @Override - Builder parent(ResourceId parent) { - infoBuilder.parent(parent); + Builder setParent(ResourceId parent) { + infoBuilder.setParent(parent); return this; } @@ -128,7 +146,15 @@ public Project build() { /** * Returns the {@link ResourceManager} service object associated with this Project. */ + @Deprecated public ResourceManager resourceManager() { + return getResourceManager(); + } + + /** + * Returns the {@link ResourceManager} service object associated with this Project. + */ + public ResourceManager getResourceManager() { return resourceManager; } @@ -140,7 +166,7 @@ public ResourceManager resourceManager() { * @throws ResourceManagerException upon failure */ public Project reload() { - return resourceManager.get(projectId()); + return resourceManager.get(getProjectId()); } /** @@ -166,7 +192,7 @@ public Project reload() { * Resource Manager delete */ public void delete() { - resourceManager.delete(projectId()); + resourceManager.delete(getProjectId()); } /** @@ -183,7 +209,7 @@ public void delete() { * Resource Manager undelete */ public void undelete() { - resourceManager.undelete(projectId()); + resourceManager.undelete(getProjectId()); } /** @@ -212,7 +238,7 @@ public Project replace() { * Resource Manager getIamPolicy */ public Policy getPolicy() { - return resourceManager.getPolicy(projectId()); + return resourceManager.getPolicy(getProjectId()); } /** @@ -227,7 +253,7 @@ public Policy getPolicy() { * Resource Manager setIamPolicy */ public Policy replacePolicy(Policy newPolicy) { - return resourceManager.replacePolicy(projectId(), newPolicy); + return resourceManager.replacePolicy(getProjectId(), newPolicy); } /** @@ -250,7 +276,7 @@ public Policy replacePolicy(Policy newPolicy) { * Services */ List testPermissions(List permissions) { - return resourceManager.testPermissions(projectId(), permissions); + return resourceManager.testPermissions(getProjectId(), permissions); } @Override diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ProjectInfo.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ProjectInfo.java index a477319a5108..9b8fe7c0cbe0 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ProjectInfo.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ProjectInfo.java @@ -85,7 +85,7 @@ static class ResourceId implements Serializable { this.type = checkNotNull(type); } - String id() { + String getId() { return id; } @@ -129,8 +129,18 @@ public abstract static class Builder { * uppercase letters, numbers, hyphen, single-quote, double-quote, space, and exclamation point. * This field can be changed after project creation. */ + @Deprecated public abstract Builder name(String name); + /** + * Set the user-assigned name of the project. + * + *

This field is optional and can remain unset. Allowed characters are: lowercase and + * uppercase letters, numbers, hyphen, single-quote, double-quote, space, and exclamation point. + * This field can be changed after project creation. + */ + public abstract Builder setName(String name); + /** * Set the unique, user-assigned ID of the project. * @@ -138,8 +148,18 @@ public abstract static class Builder { * Trailing hyphens are prohibited. This field cannot be changed after the server creates the * project. */ + @Deprecated public abstract Builder projectId(String projectId); + /** + * Set the unique, user-assigned ID of the project. + * + *

The ID must be 6 to 30 lowercase letters, digits, or hyphens. It must start with a letter. + * Trailing hyphens are prohibited. This field cannot be changed after the server creates the + * project. + */ + public abstract Builder setProjectId(String projectId); + /** * Add a label associated with this project. * @@ -166,15 +186,27 @@ public abstract static class Builder { * more than 256 labels can be associated with a given resource. This field can be changed after * project creation. */ + @Deprecated public abstract Builder labels(Map labels); - abstract Builder projectNumber(Long projectNumber); + /** + * Set the labels associated with this project. + * + *

Label keys must be between 1 and 63 characters long and must conform to the following + * regular expression: [a-z]([-a-z0-9]*[a-z0-9])?. Label values must be between 0 and 63 + * characters long and must conform to the regular expression ([a-z]([-a-z0-9]*[a-z0-9])?)?. No + * more than 256 labels can be associated with a given resource. This field can be changed after + * project creation. + */ + public abstract Builder setLabels(Map labels); + + abstract Builder setProjectNumber(Long projectNumber); - abstract Builder state(State state); + abstract Builder setState(State state); - abstract Builder createTimeMillis(Long createTimeMillis); + abstract Builder setCreateTimeMillis(Long createTimeMillis); - abstract Builder parent(ResourceId parent); + abstract Builder setParent(ResourceId parent); public abstract ProjectInfo build(); } @@ -204,13 +236,25 @@ static class BuilderImpl extends Builder { } @Override + @Deprecated public Builder name(String name) { + return setName(name); + } + + @Override + public Builder setName(String name) { this.name = firstNonNull(name, Data.nullOf(String.class)); return this; } @Override + @Deprecated public Builder projectId(String projectId) { + return setProjectId(projectId); + } + + @Override + public Builder setProjectId(String projectId) { this.projectId = checkNotNull(projectId); return this; } @@ -234,31 +278,37 @@ public Builder clearLabels() { } @Override + @Deprecated public Builder labels(Map labels) { + return setLabels(labels); + } + + @Override + public Builder setLabels(Map labels) { this.labels = Maps.newHashMap(checkNotNull(labels)); return this; } @Override - Builder projectNumber(Long projectNumber) { + Builder setProjectNumber(Long projectNumber) { this.projectNumber = projectNumber; return this; } @Override - Builder state(State state) { + Builder setState(State state) { this.state = state; return this; } @Override - Builder createTimeMillis(Long createTimeMillis) { + Builder setCreateTimeMillis(Long createTimeMillis) { this.createTimeMillis = createTimeMillis; return this; } @Override - Builder parent(ResourceId parent) { + Builder setParent(ResourceId parent) { this.parent = parent; return this; } @@ -284,7 +334,17 @@ public ProjectInfo build() { * *

This field cannot be changed after the server creates the project. */ + @Deprecated public String projectId() { + return getProjectId(); + } + + /** + * Get the unique, user-assigned ID of the project. + * + *

This field cannot be changed after the server creates the project. + */ + public String getProjectId() { return projectId; } @@ -293,7 +353,17 @@ public String projectId() { * *

This field is optional, can remain unset, and can be changed after project creation. */ + @Deprecated public String name() { + return getName(); + } + + /** + * Get the user-assigned name of the project. + * + *

This field is optional, can remain unset, and can be changed after project creation. + */ + public String getName() { return Data.isNull(name) ? null : name; } @@ -302,14 +372,32 @@ public String name() { * *

This field is set by the server and is read-only. */ + @Deprecated public Long projectNumber() { + return getProjectNumber(); + } + + /** + * Get number uniquely identifying the project. + * + *

This field is set by the server and is read-only. + */ + public Long getProjectNumber() { return projectNumber; } /** * Get the immutable map of labels associated with this project. */ + @Deprecated public Map labels() { + return getLabels(); + } + + /** + * Get the immutable map of labels associated with this project. + */ + public Map getLabels() { return labels; } @@ -319,11 +407,22 @@ public Map labels() { *

This is a read-only field. To change the lifecycle state of your project, use the * {@code delete} or {@code undelete} method. */ + @Deprecated public State state() { return state; } - ResourceId parent() { + /** + * Get the project's lifecycle state. + * + *

This is a read-only field. To change the lifecycle state of your project, use the + * {@code delete} or {@code undelete} method. + */ + public State getState() { + return state; + } + + ResourceId getParent() { return parent; } @@ -332,7 +431,17 @@ ResourceId parent() { * *

This field is set by the server and is read-only. */ + @Deprecated public Long createTimeMillis() { + return getCreateTimeMillis(); + } + + /** + * Get the project's creation time (in milliseconds). + * + *

This field is set by the server and is read-only. + */ + public Long getCreateTimeMillis() { return createTimeMillis; } @@ -349,7 +458,12 @@ public int hashCode() { return Objects.hash(name, projectId, labels, projectNumber, state, createTimeMillis, parent); } + @Deprecated public static Builder builder(String id) { + return newBuilder(id); + } + + public static Builder newBuilder(String id) { return new BuilderImpl(id); } @@ -377,21 +491,22 @@ com.google.api.services.cloudresourcemanager.model.Project toPb() { } static ProjectInfo fromPb(com.google.api.services.cloudresourcemanager.model.Project projectPb) { - Builder builder = builder(projectPb.getProjectId()).projectNumber(projectPb.getProjectNumber()); + Builder builder = newBuilder(projectPb.getProjectId()) + .setProjectNumber(projectPb.getProjectNumber()); if (projectPb.getName() != null && !projectPb.getName().equals("Unnamed")) { - builder.name(projectPb.getName()); + builder.setName(projectPb.getName()); } if (projectPb.getLabels() != null) { - builder.labels(projectPb.getLabels()); + builder.setLabels(projectPb.getLabels()); } if (projectPb.getLifecycleState() != null) { - builder.state(State.valueOf(projectPb.getLifecycleState())); + builder.setState(State.valueOf(projectPb.getLifecycleState())); } if (projectPb.getCreateTime() != null) { - builder.createTimeMillis(DateTime.parse(projectPb.getCreateTime()).getMillis()); + builder.setCreateTimeMillis(DateTime.parse(projectPb.getCreateTime()).getMillis()); } if (projectPb.getParent() != null) { - builder.parent(ResourceId.fromPb(projectPb.getParent())); + builder.setParent(ResourceId.fromPb(projectPb.getParent())); } return builder.build(); } diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerImpl.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerImpl.java index 7b539be61402..67daa57a02b7 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerImpl.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerImpl.java @@ -234,7 +234,7 @@ public List call() { private Map optionMap(Option... options) { Map temp = Maps.newEnumMap(ResourceManagerRpc.Option.class); for (Option option : options) { - Object prev = temp.put(option.rpcOption(), option.value()); + Object prev = temp.put(option.getRpcOption(), option.getValue()); checkArgument(prev == null, "Duplicate option %s", option); } return ImmutableMap.copyOf(temp); diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/package-info.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/package-info.java index 9f6285ceb1e8..3f8d94de756e 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/package-info.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/package-info.java @@ -43,13 +43,13 @@ * .addLabel("launch-status", "in-development") * .build() * .replace(); - * System.out.println("Updated the labels of project " + newProject.projectId() - * + " to be " + newProject.labels()); + * System.out.println("Updated the labels of project " + newProject.getProjectId() + * + " to be " + newProject.getLabels()); * } * Iterator projectIterator = resourceManager.list().iterateAll(); * System.out.println("Projects I can view:"); * while (projectIterator.hasNext()) { - * System.out.println(projectIterator.next().projectId()); + * System.out.println(projectIterator.next().getProjectId()); * }}

*

Remember that you must authenticate using the Google Cloud SDK. See more about * providing diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java index 48934d602bfe..d794514e1b2f 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java @@ -675,7 +675,15 @@ public static LocalResourceManagerHelper create() { /** * Returns a {@link ResourceManagerOptions} instance that sets the host to use the mock server. */ + @Deprecated public ResourceManagerOptions options() { + return getOptions(); + } + + /** + * Returns a {@link ResourceManagerOptions} instance that sets the host to use the mock server. + */ + public ResourceManagerOptions getOptions() { return ResourceManagerOptions.builder() .host("http://localhost:" + port) .authCredentials(AuthCredentials.noAuth()) diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/package-info.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/package-info.java index d007d00eaeab..b65d84934ac4 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/package-info.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/package-info.java @@ -22,7 +22,7 @@ *

 {@code
  * LocalResourceManagerHelper resourceManagerHelper = LocalResourceManagerHelper.create();
  * resourceManagerHelper.start();
- * ResourceManager resourceManager = resourceManagerHelper.options().service();
+ * ResourceManager resourceManager = resourceManagerHelper.getOptions().service();
  * }
* *

After the test: diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/OptionTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/OptionTest.java index 097a5c61c13d..352d42998b5b 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/OptionTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/OptionTest.java @@ -55,11 +55,11 @@ public void testHashCode() { @Test public void testConstructor() { - assertEquals(RPC_OPTION, OPTION.rpcOption()); - assertEquals(VALUE, OPTION.value()); + assertEquals(RPC_OPTION, OPTION.getRpcOption()); + assertEquals(VALUE, OPTION.getValue()); Option option = new Option(RPC_OPTION, null) {}; - assertEquals(RPC_OPTION, option.rpcOption()); - assertNull(option.value()); + assertEquals(RPC_OPTION, option.getRpcOption()); + assertNull(option.getValue()); thrown.expect(NullPointerException.class); new Option(null, VALUE) {}; } diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectInfoTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectInfoTest.java index 2b276f485a72..2d3db2b13364 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectInfoTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectInfoTest.java @@ -36,26 +36,51 @@ public class ProjectInfoTest { private static final ProjectInfo.State STATE = ProjectInfo.State.DELETE_REQUESTED; private static final ProjectInfo.ResourceId PARENT = new ProjectInfo.ResourceId("id", "organization"); - private static final ProjectInfo FULL_PROJECT_INFO = ProjectInfo.builder(PROJECT_ID) + private static final ProjectInfo FULL_PROJECT_INFO = ProjectInfo.newBuilder(PROJECT_ID) + .setName(NAME) + .setLabels(LABELS) + .setProjectNumber(PROJECT_NUMBER) + .setCreateTimeMillis(CREATE_TIME_MILLIS) + .setState(STATE) + .setParent(PARENT) + .build(); + private static final ProjectInfo PARTIAL_PROJECT_INFO = ProjectInfo.newBuilder(PROJECT_ID).build(); + private static final ProjectInfo UNNAMED_PROJECT_FROM_LIST = + PARTIAL_PROJECT_INFO.toBuilder().setName("Unnamed").build(); + private static final ProjectInfo DEPRECATED_PROJECT_INFO = ProjectInfo.builder(PROJECT_ID) .name(NAME) .labels(LABELS) - .projectNumber(PROJECT_NUMBER) - .createTimeMillis(CREATE_TIME_MILLIS) - .state(STATE) - .parent(PARENT) + .setProjectNumber(PROJECT_NUMBER) + .setCreateTimeMillis(CREATE_TIME_MILLIS) + .setState(STATE) + .setParent(PARENT) .build(); - private static final ProjectInfo PARTIAL_PROJECT_INFO = ProjectInfo.builder(PROJECT_ID).build(); - private static final ProjectInfo UNNAMED_PROJECT_FROM_LIST = - PARTIAL_PROJECT_INFO.toBuilder().name("Unnamed").build(); @Test public void testBuilder() { - assertEquals(PROJECT_ID, FULL_PROJECT_INFO.projectId()); - assertEquals(NAME, FULL_PROJECT_INFO.name()); - assertEquals(LABELS, FULL_PROJECT_INFO.labels()); - assertEquals(PROJECT_NUMBER, FULL_PROJECT_INFO.projectNumber()); - assertEquals(CREATE_TIME_MILLIS, FULL_PROJECT_INFO.createTimeMillis()); - assertEquals(STATE, FULL_PROJECT_INFO.state()); + assertEquals(PROJECT_ID, FULL_PROJECT_INFO.getProjectId()); + assertEquals(NAME, FULL_PROJECT_INFO.getName()); + assertEquals(LABELS, FULL_PROJECT_INFO.getLabels()); + assertEquals(PROJECT_NUMBER, FULL_PROJECT_INFO.getProjectNumber()); + assertEquals(CREATE_TIME_MILLIS, FULL_PROJECT_INFO.getCreateTimeMillis()); + assertEquals(STATE, FULL_PROJECT_INFO.getState()); + + assertEquals(PROJECT_ID, PARTIAL_PROJECT_INFO.getProjectId()); + assertEquals(null, PARTIAL_PROJECT_INFO.getName()); + assertTrue(PARTIAL_PROJECT_INFO.getLabels().isEmpty()); + assertEquals(null, PARTIAL_PROJECT_INFO.getProjectNumber()); + assertEquals(null, PARTIAL_PROJECT_INFO.getCreateTimeMillis()); + assertEquals(null, PARTIAL_PROJECT_INFO.getState()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(PROJECT_ID, DEPRECATED_PROJECT_INFO.projectId()); + assertEquals(NAME, DEPRECATED_PROJECT_INFO.name()); + assertEquals(LABELS, DEPRECATED_PROJECT_INFO.labels()); + assertEquals(PROJECT_NUMBER, DEPRECATED_PROJECT_INFO.projectNumber()); + assertEquals(CREATE_TIME_MILLIS, DEPRECATED_PROJECT_INFO.createTimeMillis()); + assertEquals(STATE, DEPRECATED_PROJECT_INFO.state()); assertEquals(PROJECT_ID, PARTIAL_PROJECT_INFO.projectId()); assertEquals(null, PARTIAL_PROJECT_INFO.name()); @@ -83,27 +108,26 @@ public void testToAndFromPb() { public void testEquals() { compareProjects( FULL_PROJECT_INFO, - ProjectInfo.builder(PROJECT_ID) - .name(NAME) - .labels(LABELS) - .projectNumber(PROJECT_NUMBER) - .createTimeMillis(CREATE_TIME_MILLIS) - .state(STATE) - .parent(PARENT) + ProjectInfo.newBuilder(PROJECT_ID) + .setName(NAME) + .setLabels(LABELS) + .setProjectNumber(PROJECT_NUMBER) + .setCreateTimeMillis(CREATE_TIME_MILLIS) + .setState(STATE) + .setParent(PARENT) .build()); - compareProjects(PARTIAL_PROJECT_INFO, ProjectInfo.builder(PROJECT_ID).build()); + compareProjects(PARTIAL_PROJECT_INFO, ProjectInfo.newBuilder(PROJECT_ID).build()); assertNotEquals(FULL_PROJECT_INFO, PARTIAL_PROJECT_INFO); } private void compareProjects(ProjectInfo expected, ProjectInfo value) { assertEquals(expected, value); - assertEquals(expected.projectId(), value.projectId()); - assertEquals(expected.name(), value.name()); - assertEquals(expected.labels(), value.labels()); - assertEquals(expected.projectNumber(), value.projectNumber()); - assertEquals(expected.createTimeMillis(), value.createTimeMillis()); - assertEquals(expected.state(), value.state()); - assertEquals(expected.parent(), value.parent()); + assertEquals(expected.getProjectId(), value.getProjectId()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getLabels(), value.getLabels()); + assertEquals(expected.getProjectNumber(), value.getProjectNumber()); + assertEquals(expected.getCreateTimeMillis(), value.getCreateTimeMillis()); + assertEquals(expected.getState(), value.getState()); + assertEquals(expected.getParent(), value.getParent()); } } - diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectTest.java index 195152a87c88..bb23c8e5b1ae 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectTest.java @@ -46,12 +46,12 @@ public class ProjectTest { private static final Long PROJECT_NUMBER = 123L; private static final Long CREATE_TIME_MILLIS = 123456789L; private static final ProjectInfo.State STATE = ProjectInfo.State.DELETE_REQUESTED; - private static final ProjectInfo PROJECT_INFO = ProjectInfo.builder(PROJECT_ID) - .name(NAME) - .labels(LABELS) - .projectNumber(PROJECT_NUMBER) - .createTimeMillis(CREATE_TIME_MILLIS) - .state(STATE) + private static final ProjectInfo PROJECT_INFO = ProjectInfo.newBuilder(PROJECT_ID) + .setName(NAME) + .setLabels(LABELS) + .setProjectNumber(PROJECT_NUMBER) + .setCreateTimeMillis(CREATE_TIME_MILLIS) + .setState(STATE) .build(); private static final Identity USER = Identity.user("abc@gmail.com"); private static final Identity SERVICE_ACCOUNT = @@ -101,45 +101,68 @@ public void testBuilder() { replay(resourceManager); Project.Builder builder = new Project.Builder(new Project(resourceManager, new ProjectInfo.BuilderImpl("wrong-id"))); - Project project = builder.projectId(PROJECT_ID) - .name(NAME) - .labels(LABELS) - .projectNumber(PROJECT_NUMBER) - .createTimeMillis(CREATE_TIME_MILLIS) - .state(STATE) + Project project = builder.setProjectId(PROJECT_ID) + .setName(NAME) + .setLabels(LABELS) + .setProjectNumber(PROJECT_NUMBER) + .setCreateTimeMillis(CREATE_TIME_MILLIS) + .setState(STATE) .build(); - assertEquals(PROJECT_ID, project.projectId()); - assertEquals(NAME, project.name()); - assertEquals(LABELS, project.labels()); - assertEquals(PROJECT_NUMBER, project.projectNumber()); - assertEquals(CREATE_TIME_MILLIS, project.createTimeMillis()); - assertEquals(STATE, project.state()); - assertEquals(resourceManager.options(), project.resourceManager().options()); - assertNull(project.parent()); + assertEquals(PROJECT_ID, project.getProjectId()); + assertEquals(NAME, project.getName()); + assertEquals(LABELS, project.getLabels()); + assertEquals(PROJECT_NUMBER, project.getProjectNumber()); + assertEquals(CREATE_TIME_MILLIS, project.getCreateTimeMillis()); + assertEquals(STATE, project.getState()); + assertEquals(resourceManager.options(), project.getResourceManager().options()); + assertNull(project.getParent()); ResourceId parent = new ResourceId("id", "type"); project = project.toBuilder() .clearLabels() .addLabel("k3", "v3") .addLabel("k4", "v4") .removeLabel("k4") - .parent(parent) + .setParent(parent) + .build(); + assertEquals(PROJECT_ID, project.getProjectId()); + assertEquals(NAME, project.getName()); + assertEquals(ImmutableMap.of("k3", "v3"), project.getLabels()); + assertEquals(PROJECT_NUMBER, project.getProjectNumber()); + assertEquals(CREATE_TIME_MILLIS, project.getCreateTimeMillis()); + assertEquals(STATE, project.getState()); + assertEquals(resourceManager.options(), project.getResourceManager().options()); + assertEquals(parent, project.getParent()); + } + + @Test + public void testBuilderDeprecated() { + expect(resourceManager.options()).andReturn(mockOptions).times(4); + replay(resourceManager); + Project.Builder builder = + new Project.Builder(new Project(resourceManager, new ProjectInfo.BuilderImpl("wrong-id"))); + Project project = builder.projectId(PROJECT_ID) + .name(NAME) + .labels(LABELS) + .setProjectNumber(PROJECT_NUMBER) + .setCreateTimeMillis(CREATE_TIME_MILLIS) + .setState(STATE) .build(); assertEquals(PROJECT_ID, project.projectId()); assertEquals(NAME, project.name()); - assertEquals(ImmutableMap.of("k3", "v3"), project.labels()); + assertEquals(LABELS, project.labels()); assertEquals(PROJECT_NUMBER, project.projectNumber()); assertEquals(CREATE_TIME_MILLIS, project.createTimeMillis()); assertEquals(STATE, project.state()); assertEquals(resourceManager.options(), project.resourceManager().options()); - assertEquals(parent, project.parent()); + assertNull(project.getParent()); } @Test public void testGet() { initializeExpectedProject(1); - expect(resourceManager.get(PROJECT_INFO.projectId())).andReturn(expectedProject); + expect(resourceManager.get(PROJECT_INFO.getProjectId())).andReturn(expectedProject); replay(resourceManager); - Project loadedProject = resourceManager.get(PROJECT_INFO.projectId()); + Project loadedProject = resourceManager.get(PROJECT_INFO.getProjectId()); assertEquals(expectedProject, loadedProject); } @@ -150,7 +173,7 @@ public void testReload() { Project expectedProject = new Project(serviceMockReturnsOptions, new ProjectInfo.BuilderImpl(newInfo)); expect(resourceManager.options()).andReturn(mockOptions); - expect(resourceManager.get(PROJECT_INFO.projectId())).andReturn(expectedProject); + expect(resourceManager.get(PROJECT_INFO.getProjectId())).andReturn(expectedProject); replay(resourceManager); initializeProject(); Project newProject = project.reload(); @@ -160,16 +183,16 @@ public void testReload() { @Test public void testLoadNull() { initializeExpectedProject(1); - expect(resourceManager.get(PROJECT_INFO.projectId())).andReturn(null); + expect(resourceManager.get(PROJECT_INFO.getProjectId())).andReturn(null); replay(resourceManager); - assertNull(resourceManager.get(PROJECT_INFO.projectId())); + assertNull(resourceManager.get(PROJECT_INFO.getProjectId())); } @Test public void testReloadNull() { initializeExpectedProject(1); expect(resourceManager.options()).andReturn(mockOptions); - expect(resourceManager.get(PROJECT_INFO.projectId())).andReturn(null); + expect(resourceManager.get(PROJECT_INFO.getProjectId())).andReturn(null); replay(resourceManager); Project reloadedProject = new Project(resourceManager, new ProjectInfo.BuilderImpl(PROJECT_INFO)).reload(); @@ -180,14 +203,14 @@ public void testReloadNull() { public void testResourceManager() { initializeExpectedProject(1); replay(resourceManager); - assertEquals(serviceMockReturnsOptions, expectedProject.resourceManager()); + assertEquals(serviceMockReturnsOptions, expectedProject.getResourceManager()); } @Test public void testDelete() { initializeExpectedProject(1); expect(resourceManager.options()).andReturn(mockOptions); - resourceManager.delete(PROJECT_INFO.projectId()); + resourceManager.delete(PROJECT_INFO.getProjectId()); replay(resourceManager); initializeProject(); project.delete(); @@ -197,7 +220,7 @@ public void testDelete() { public void testUndelete() { initializeExpectedProject(1); expect(resourceManager.options()).andReturn(mockOptions); - resourceManager.undelete(PROJECT_INFO.projectId()); + resourceManager.undelete(PROJECT_INFO.getProjectId()); replay(resourceManager); initializeProject(); project.undelete(); @@ -253,16 +276,16 @@ public void testTestPermissions() { private void compareProjects(Project expected, Project value) { assertEquals(expected, value); compareProjectInfos(expected, value); - assertEquals(expected.resourceManager().options(), value.resourceManager().options()); + assertEquals(expected.getResourceManager().options(), value.getResourceManager().options()); } private void compareProjectInfos(ProjectInfo expected, ProjectInfo value) { - assertEquals(expected.projectId(), value.projectId()); - assertEquals(expected.name(), value.name()); - assertEquals(expected.labels(), value.labels()); - assertEquals(expected.projectNumber(), value.projectNumber()); - assertEquals(expected.createTimeMillis(), value.createTimeMillis()); - assertEquals(expected.state(), value.state()); - assertEquals(expected.parent(), value.parent()); + assertEquals(expected.getProjectId(), value.getProjectId()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getLabels(), value.getLabels()); + assertEquals(expected.getProjectNumber(), value.getProjectNumber()); + assertEquals(expected.getCreateTimeMillis(), value.getCreateTimeMillis()); + assertEquals(expected.getState(), value.getState()); + assertEquals(expected.getParent(), value.getParent()); } } diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ResourceManagerImplTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ResourceManagerImplTest.java index e92c712521d5..58ea3a2f63f3 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ResourceManagerImplTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ResourceManagerImplTest.java @@ -56,19 +56,19 @@ public class ResourceManagerImplTest { private static final LocalResourceManagerHelper RESOURCE_MANAGER_HELPER = LocalResourceManagerHelper.create(); private static final ResourceManager RESOURCE_MANAGER = - RESOURCE_MANAGER_HELPER.options().service(); + RESOURCE_MANAGER_HELPER.getOptions().service(); private static final ProjectGetOption GET_FIELDS = ProjectGetOption.fields(ProjectField.NAME, ProjectField.CREATE_TIME); private static final ProjectListOption LIST_FIELDS = ProjectListOption.fields(ProjectField.NAME, ProjectField.LABELS); private static final ProjectListOption LIST_FILTER = ProjectListOption.filter("id:* name:myProject labels.color:blue LABELS.SIZE:*"); - private static final ProjectInfo PARTIAL_PROJECT = ProjectInfo.builder("partial-project").build(); + private static final ProjectInfo PARTIAL_PROJECT = ProjectInfo.newBuilder("partial-project").build(); private static final ResourceId PARENT = new ResourceId("id", "type"); - private static final ProjectInfo COMPLETE_PROJECT = ProjectInfo.builder("complete-project") - .name("name") - .labels(ImmutableMap.of("k1", "v1")) - .parent(PARENT) + private static final ProjectInfo COMPLETE_PROJECT = ProjectInfo.newBuilder("complete-project") + .setName("name") + .setLabels(ImmutableMap.of("k1", "v1")) + .setParent(PARENT) .build(); private static final Map EMPTY_RPC_OPTIONS = ImmutableMap.of(); private static final Policy POLICY = Policy.builder() @@ -91,7 +91,7 @@ public void setUp() { private void clearProjects() { for (Project project : RESOURCE_MANAGER.list().values()) { - RESOURCE_MANAGER_HELPER.removeProject(project.projectId()); + RESOURCE_MANAGER_HELPER.removeProject(project.getProjectId()); } } @@ -101,22 +101,22 @@ public static void afterClass() { } private void compareReadWriteFields(ProjectInfo expected, ProjectInfo actual) { - assertEquals(expected.projectId(), actual.projectId()); - assertEquals(expected.name(), actual.name()); - assertEquals(expected.labels(), actual.labels()); - assertEquals(expected.parent(), actual.parent()); + assertEquals(expected.getProjectId(), actual.getProjectId()); + assertEquals(expected.getName(), actual.getName()); + assertEquals(expected.getLabels(), actual.getLabels()); + assertEquals(expected.getParent(), actual.getParent()); } @Test public void testCreate() { Project returnedProject = RESOURCE_MANAGER.create(PARTIAL_PROJECT); compareReadWriteFields(PARTIAL_PROJECT, returnedProject); - assertEquals(ProjectInfo.State.ACTIVE, returnedProject.state()); - assertNull(returnedProject.name()); - assertNull(returnedProject.parent()); - assertNotNull(returnedProject.projectNumber()); - assertNotNull(returnedProject.createTimeMillis()); - assertSame(RESOURCE_MANAGER, returnedProject.resourceManager()); + assertEquals(ProjectInfo.State.ACTIVE, returnedProject.getState()); + assertNull(returnedProject.getName()); + assertNull(returnedProject.getParent()); + assertNotNull(returnedProject.getProjectNumber()); + assertNotNull(returnedProject.getCreateTimeMillis()); + assertSame(RESOURCE_MANAGER, returnedProject.getResourceManager()); try { RESOURCE_MANAGER.create(PARTIAL_PROJECT); fail("Should fail, project already exists."); @@ -127,18 +127,18 @@ public void testCreate() { } returnedProject = RESOURCE_MANAGER.create(COMPLETE_PROJECT); compareReadWriteFields(COMPLETE_PROJECT, returnedProject); - assertEquals(ProjectInfo.State.ACTIVE, returnedProject.state()); - assertNotNull(returnedProject.projectNumber()); - assertNotNull(returnedProject.createTimeMillis()); - assertSame(RESOURCE_MANAGER, returnedProject.resourceManager()); + assertEquals(ProjectInfo.State.ACTIVE, returnedProject.getState()); + assertNotNull(returnedProject.getProjectNumber()); + assertNotNull(returnedProject.getCreateTimeMillis()); + assertSame(RESOURCE_MANAGER, returnedProject.getResourceManager()); } @Test public void testDelete() { RESOURCE_MANAGER.create(COMPLETE_PROJECT); - RESOURCE_MANAGER.delete(COMPLETE_PROJECT.projectId()); + RESOURCE_MANAGER.delete(COMPLETE_PROJECT.getProjectId()); assertEquals(ProjectInfo.State.DELETE_REQUESTED, - RESOURCE_MANAGER.get(COMPLETE_PROJECT.projectId()).state()); + RESOURCE_MANAGER.get(COMPLETE_PROJECT.getProjectId()).getState()); try { RESOURCE_MANAGER.delete("some-nonexistant-project-id"); fail("Should fail because the project doesn't exist."); @@ -151,27 +151,27 @@ public void testDelete() { @Test public void testGet() { RESOURCE_MANAGER.create(COMPLETE_PROJECT); - Project returnedProject = RESOURCE_MANAGER.get(COMPLETE_PROJECT.projectId()); + Project returnedProject = RESOURCE_MANAGER.get(COMPLETE_PROJECT.getProjectId()); compareReadWriteFields(COMPLETE_PROJECT, returnedProject); - assertEquals(RESOURCE_MANAGER, returnedProject.resourceManager()); - RESOURCE_MANAGER_HELPER.removeProject(COMPLETE_PROJECT.projectId()); - assertNull(RESOURCE_MANAGER.get(COMPLETE_PROJECT.projectId())); + assertEquals(RESOURCE_MANAGER, returnedProject.getResourceManager()); + RESOURCE_MANAGER_HELPER.removeProject(COMPLETE_PROJECT.getProjectId()); + assertNull(RESOURCE_MANAGER.get(COMPLETE_PROJECT.getProjectId())); } @Test public void testGetWithOptions() { Project originalProject = RESOURCE_MANAGER.create(COMPLETE_PROJECT); - Project returnedProject = RESOURCE_MANAGER.get(COMPLETE_PROJECT.projectId(), GET_FIELDS); + Project returnedProject = RESOURCE_MANAGER.get(COMPLETE_PROJECT.getProjectId(), GET_FIELDS); assertFalse(COMPLETE_PROJECT.equals(returnedProject)); - assertEquals(COMPLETE_PROJECT.projectId(), returnedProject.projectId()); - assertEquals(COMPLETE_PROJECT.name(), returnedProject.name()); - assertEquals(originalProject.createTimeMillis(), returnedProject.createTimeMillis()); - assertNull(returnedProject.parent()); - assertNull(returnedProject.projectNumber()); - assertNull(returnedProject.state()); - assertTrue(returnedProject.labels().isEmpty()); - assertEquals(RESOURCE_MANAGER, originalProject.resourceManager()); - assertEquals(RESOURCE_MANAGER, returnedProject.resourceManager()); + assertEquals(COMPLETE_PROJECT.getProjectId(), returnedProject.getProjectId()); + assertEquals(COMPLETE_PROJECT.getName(), returnedProject.getName()); + assertEquals(originalProject.getCreateTimeMillis(), returnedProject.getCreateTimeMillis()); + assertNull(returnedProject.getParent()); + assertNull(returnedProject.getProjectNumber()); + assertNull(returnedProject.getState()); + assertTrue(returnedProject.getLabels().isEmpty()); + assertEquals(RESOURCE_MANAGER, originalProject.getResourceManager()); + assertEquals(RESOURCE_MANAGER, returnedProject.getResourceManager()); } @Test @@ -181,14 +181,14 @@ public void testList() { RESOURCE_MANAGER.create(PARTIAL_PROJECT); RESOURCE_MANAGER.create(COMPLETE_PROJECT); for (Project p : RESOURCE_MANAGER.list().values()) { - if (p.projectId().equals(PARTIAL_PROJECT.projectId())) { + if (p.getProjectId().equals(PARTIAL_PROJECT.getProjectId())) { compareReadWriteFields(PARTIAL_PROJECT, p); - } else if (p.projectId().equals(COMPLETE_PROJECT.projectId())) { + } else if (p.getProjectId().equals(COMPLETE_PROJECT.getProjectId())) { compareReadWriteFields(COMPLETE_PROJECT, p); } else { fail("Some unexpected project returned by list."); } - assertSame(RESOURCE_MANAGER, p.resourceManager()); + assertSame(RESOURCE_MANAGER, p.getResourceManager()); } } @@ -213,14 +213,14 @@ public void testListFieldOptions() { RESOURCE_MANAGER.create(COMPLETE_PROJECT); Page projects = RESOURCE_MANAGER.list(LIST_FIELDS); Project returnedProject = projects.iterateAll().next(); - assertEquals(COMPLETE_PROJECT.projectId(), returnedProject.projectId()); - assertEquals(COMPLETE_PROJECT.name(), returnedProject.name()); - assertEquals(COMPLETE_PROJECT.labels(), returnedProject.labels()); - assertNull(returnedProject.parent()); - assertNull(returnedProject.projectNumber()); - assertNull(returnedProject.state()); - assertNull(returnedProject.createTimeMillis()); - assertSame(RESOURCE_MANAGER, returnedProject.resourceManager()); + assertEquals(COMPLETE_PROJECT.getProjectId(), returnedProject.getProjectId()); + assertEquals(COMPLETE_PROJECT.getName(), returnedProject.getName()); + assertEquals(COMPLETE_PROJECT.getLabels(), returnedProject.getLabels()); + assertNull(returnedProject.getParent()); + assertNull(returnedProject.getProjectNumber()); + assertNull(returnedProject.getState()); + assertNull(returnedProject.getCreateTimeMillis()); + assertSame(RESOURCE_MANAGER, returnedProject.getResourceManager()); } @Test @@ -231,45 +231,45 @@ public void testListPagingWithFieldOptions() { assertNotNull(projects.nextPageCursor()); Iterator iterator = projects.values().iterator(); Project returnedProject = iterator.next(); - assertEquals(COMPLETE_PROJECT.projectId(), returnedProject.projectId()); - assertEquals(COMPLETE_PROJECT.name(), returnedProject.name()); - assertEquals(COMPLETE_PROJECT.labels(), returnedProject.labels()); - assertNull(returnedProject.parent()); - assertNull(returnedProject.projectNumber()); - assertNull(returnedProject.state()); - assertNull(returnedProject.createTimeMillis()); - assertSame(RESOURCE_MANAGER, returnedProject.resourceManager()); + assertEquals(COMPLETE_PROJECT.getProjectId(), returnedProject.getProjectId()); + assertEquals(COMPLETE_PROJECT.getName(), returnedProject.getName()); + assertEquals(COMPLETE_PROJECT.getLabels(), returnedProject.getLabels()); + assertNull(returnedProject.getParent()); + assertNull(returnedProject.getProjectNumber()); + assertNull(returnedProject.getState()); + assertNull(returnedProject.getCreateTimeMillis()); + assertSame(RESOURCE_MANAGER, returnedProject.getResourceManager()); assertFalse(iterator.hasNext()); projects = projects.nextPage(); iterator = projects.values().iterator(); returnedProject = iterator.next(); - assertEquals(PARTIAL_PROJECT.projectId(), returnedProject.projectId()); - assertEquals(PARTIAL_PROJECT.name(), returnedProject.name()); - assertEquals(PARTIAL_PROJECT.labels(), returnedProject.labels()); - assertNull(returnedProject.parent()); - assertNull(returnedProject.projectNumber()); - assertNull(returnedProject.state()); - assertNull(returnedProject.createTimeMillis()); - assertSame(RESOURCE_MANAGER, returnedProject.resourceManager()); + assertEquals(PARTIAL_PROJECT.getProjectId(), returnedProject.getProjectId()); + assertEquals(PARTIAL_PROJECT.getName(), returnedProject.getName()); + assertEquals(PARTIAL_PROJECT.getLabels(), returnedProject.getLabels()); + assertNull(returnedProject.getParent()); + assertNull(returnedProject.getProjectNumber()); + assertNull(returnedProject.getState()); + assertNull(returnedProject.getCreateTimeMillis()); + assertSame(RESOURCE_MANAGER, returnedProject.getResourceManager()); assertFalse(iterator.hasNext()); assertNull(projects.nextPageCursor()); } @Test public void testListFilterOptions() { - ProjectInfo matchingProject = ProjectInfo.builder("matching-project") - .name("MyProject") - .labels(ImmutableMap.of("color", "blue", "size", "big")) + ProjectInfo matchingProject = ProjectInfo.newBuilder("matching-project") + .setName("MyProject") + .setLabels(ImmutableMap.of("color", "blue", "size", "big")) .build(); - ProjectInfo nonMatchingProject1 = ProjectInfo.builder("non-matching-project1") - .name("myProject") - .labels(ImmutableMap.of("color", "blue")) + ProjectInfo nonMatchingProject1 = ProjectInfo.newBuilder("non-matching-project1") + .setName("myProject") + .setLabels(ImmutableMap.of("color", "blue")) .build(); - ProjectInfo nonMatchingProject2 = ProjectInfo.builder("non-matching-project2") - .name("myProj") - .labels(ImmutableMap.of("color", "blue", "size", "big")) + ProjectInfo nonMatchingProject2 = ProjectInfo.newBuilder("non-matching-project2") + .setName("myProj") + .setLabels(ImmutableMap.of("color", "blue", "size", "big")) .build(); - ProjectInfo nonMatchingProject3 = ProjectInfo.builder("non-matching-project3").build(); + ProjectInfo nonMatchingProject3 = ProjectInfo.newBuilder("non-matching-project3").build(); RESOURCE_MANAGER.create(matchingProject); RESOURCE_MANAGER.create(nonMatchingProject1); RESOURCE_MANAGER.create(nonMatchingProject2); @@ -278,7 +278,7 @@ public void testListFilterOptions() { assertFalse(p.equals(nonMatchingProject1)); assertFalse(p.equals(nonMatchingProject2)); compareReadWriteFields(matchingProject, p); - assertSame(RESOURCE_MANAGER, p.resourceManager()); + assertSame(RESOURCE_MANAGER, p.getResourceManager()); } } @@ -286,21 +286,21 @@ public void testListFilterOptions() { public void testReplace() { ProjectInfo createdProject = RESOURCE_MANAGER.create(COMPLETE_PROJECT); Map newLabels = ImmutableMap.of("new k1", "new v1"); - ProjectInfo anotherCompleteProject = ProjectInfo.builder(COMPLETE_PROJECT.projectId()) - .labels(newLabels) - .projectNumber(987654321L) - .createTimeMillis(230682061315L) - .state(ProjectInfo.State.DELETE_REQUESTED) - .parent(createdProject.parent()) + ProjectInfo anotherCompleteProject = ProjectInfo.newBuilder(COMPLETE_PROJECT.getProjectId()) + .setLabels(newLabels) + .setProjectNumber(987654321L) + .setCreateTimeMillis(230682061315L) + .setState(ProjectInfo.State.DELETE_REQUESTED) + .setParent(createdProject.getParent()) .build(); Project returnedProject = RESOURCE_MANAGER.replace(anotherCompleteProject); compareReadWriteFields(anotherCompleteProject, returnedProject); - assertEquals(createdProject.projectNumber(), returnedProject.projectNumber()); - assertEquals(createdProject.createTimeMillis(), returnedProject.createTimeMillis()); - assertEquals(createdProject.state(), returnedProject.state()); - assertEquals(RESOURCE_MANAGER, returnedProject.resourceManager()); + assertEquals(createdProject.getProjectNumber(), returnedProject.getProjectNumber()); + assertEquals(createdProject.getCreateTimeMillis(), returnedProject.getCreateTimeMillis()); + assertEquals(createdProject.getState(), returnedProject.getState()); + assertEquals(RESOURCE_MANAGER, returnedProject.getResourceManager()); ProjectInfo nonexistantProject = - ProjectInfo.builder("some-project-id-that-does-not-exist").build(); + ProjectInfo.newBuilder("some-project-id-that-does-not-exist").build(); try { RESOURCE_MANAGER.replace(nonexistantProject); fail("Should fail because the project doesn't exist."); @@ -313,14 +313,14 @@ public void testReplace() { @Test public void testUndelete() { RESOURCE_MANAGER.create(COMPLETE_PROJECT); - RESOURCE_MANAGER.delete(COMPLETE_PROJECT.projectId()); + RESOURCE_MANAGER.delete(COMPLETE_PROJECT.getProjectId()); assertEquals( ProjectInfo.State.DELETE_REQUESTED, - RESOURCE_MANAGER.get(COMPLETE_PROJECT.projectId()).state()); - RESOURCE_MANAGER.undelete(COMPLETE_PROJECT.projectId()); - ProjectInfo revivedProject = RESOURCE_MANAGER.get(COMPLETE_PROJECT.projectId()); + RESOURCE_MANAGER.get(COMPLETE_PROJECT.getProjectId()).getState()); + RESOURCE_MANAGER.undelete(COMPLETE_PROJECT.getProjectId()); + ProjectInfo revivedProject = RESOURCE_MANAGER.get(COMPLETE_PROJECT.getProjectId()); compareReadWriteFields(COMPLETE_PROJECT, revivedProject); - assertEquals(ProjectInfo.State.ACTIVE, revivedProject.state()); + assertEquals(ProjectInfo.State.ACTIVE, revivedProject.getState()); try { RESOURCE_MANAGER.undelete("invalid-project-id"); fail("Should fail because the project doesn't exist."); @@ -332,10 +332,10 @@ public void testUndelete() { @Test public void testGetPolicy() { - assertNull(RESOURCE_MANAGER.getPolicy(COMPLETE_PROJECT.projectId())); + assertNull(RESOURCE_MANAGER.getPolicy(COMPLETE_PROJECT.getProjectId())); RESOURCE_MANAGER.create(COMPLETE_PROJECT); - RESOURCE_MANAGER.replacePolicy(COMPLETE_PROJECT.projectId(), POLICY); - Policy retrieved = RESOURCE_MANAGER.getPolicy(COMPLETE_PROJECT.projectId()); + RESOURCE_MANAGER.replacePolicy(COMPLETE_PROJECT.getProjectId(), POLICY); + Policy retrieved = RESOURCE_MANAGER.getPolicy(COMPLETE_PROJECT.getProjectId()); assertEquals(POLICY.bindings(), retrieved.bindings()); assertNotNull(retrieved.etag()); assertEquals(0, retrieved.version()); @@ -351,17 +351,17 @@ public void testReplacePolicy() { assertTrue(e.getMessage().endsWith("project was not found.")); } RESOURCE_MANAGER.create(PARTIAL_PROJECT); - Policy oldPolicy = RESOURCE_MANAGER.getPolicy(PARTIAL_PROJECT.projectId()); - RESOURCE_MANAGER.replacePolicy(PARTIAL_PROJECT.projectId(), POLICY); + Policy oldPolicy = RESOURCE_MANAGER.getPolicy(PARTIAL_PROJECT.getProjectId()); + RESOURCE_MANAGER.replacePolicy(PARTIAL_PROJECT.getProjectId(), POLICY); try { - RESOURCE_MANAGER.replacePolicy(PARTIAL_PROJECT.projectId(), oldPolicy); + RESOURCE_MANAGER.replacePolicy(PARTIAL_PROJECT.getProjectId(), oldPolicy); fail("Policy with an invalid etag didn't cause error."); } catch (ResourceManagerException e) { assertEquals(409, e.code()); assertTrue(e.getMessage().contains("Policy etag mismatch")); } - String originalEtag = RESOURCE_MANAGER.getPolicy(PARTIAL_PROJECT.projectId()).etag(); - Policy newPolicy = RESOURCE_MANAGER.replacePolicy(PARTIAL_PROJECT.projectId(), POLICY); + String originalEtag = RESOURCE_MANAGER.getPolicy(PARTIAL_PROJECT.getProjectId()).etag(); + Policy newPolicy = RESOURCE_MANAGER.replacePolicy(PARTIAL_PROJECT.getProjectId(), POLICY); assertEquals(POLICY.bindings(), newPolicy.bindings()); assertNotNull(newPolicy.etag()); assertNotEquals(originalEtag, newPolicy.etag()); @@ -379,7 +379,7 @@ public void testTestPermissions() { } RESOURCE_MANAGER.create(PARTIAL_PROJECT); assertEquals(ImmutableList.of(true), - RESOURCE_MANAGER.testPermissions(PARTIAL_PROJECT.projectId(), permissions)); + RESOURCE_MANAGER.testPermissions(PARTIAL_PROJECT.getProjectId(), permissions)); } @Test @@ -393,11 +393,11 @@ public void testRetryableException() { .serviceRpcFactory(rpcFactoryMock) .build() .service(); - EasyMock.expect(resourceManagerRpcMock.get(PARTIAL_PROJECT.projectId(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(resourceManagerRpcMock.get(PARTIAL_PROJECT.getProjectId(), EMPTY_RPC_OPTIONS)) .andThrow(new ResourceManagerException(500, "Internal Error")) .andReturn(PARTIAL_PROJECT.toPb()); EasyMock.replay(resourceManagerRpcMock); - Project returnedProject = resourceManagerMock.get(PARTIAL_PROJECT.projectId()); + Project returnedProject = resourceManagerMock.get(PARTIAL_PROJECT.getProjectId()); assertEquals( new Project(resourceManagerMock, new ProjectInfo.BuilderImpl(PARTIAL_PROJECT)), returnedProject); @@ -414,14 +414,14 @@ public void testNonRetryableException() { .serviceRpcFactory(rpcFactoryMock) .build() .service(); - EasyMock.expect(resourceManagerRpcMock.get(PARTIAL_PROJECT.projectId(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(resourceManagerRpcMock.get(PARTIAL_PROJECT.getProjectId(), EMPTY_RPC_OPTIONS)) .andThrow(new ResourceManagerException( - 403, "Project " + PARTIAL_PROJECT.projectId() + " not found.")) + 403, "Project " + PARTIAL_PROJECT.getProjectId() + " not found.")) .once(); EasyMock.replay(resourceManagerRpcMock); thrown.expect(ResourceManagerException.class); - thrown.expectMessage("Project " + PARTIAL_PROJECT.projectId() + " not found."); - resourceManagerMock.get(PARTIAL_PROJECT.projectId()); + thrown.expectMessage("Project " + PARTIAL_PROJECT.getProjectId() + " not found."); + resourceManagerMock.get(PARTIAL_PROJECT.getProjectId()); } @Test @@ -434,11 +434,11 @@ public void testRuntimeException() { ResourceManager resourceManagerMock = ResourceManagerOptions.builder().serviceRpcFactory(rpcFactoryMock).build().service(); String exceptionMessage = "Artificial runtime exception"; - EasyMock.expect(resourceManagerRpcMock.get(PARTIAL_PROJECT.projectId(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(resourceManagerRpcMock.get(PARTIAL_PROJECT.getProjectId(), EMPTY_RPC_OPTIONS)) .andThrow(new RuntimeException(exceptionMessage)); EasyMock.replay(resourceManagerRpcMock); thrown.expect(ResourceManagerException.class); thrown.expectMessage(exceptionMessage); - resourceManagerMock.get(PARTIAL_PROJECT.projectId()); + resourceManagerMock.get(PARTIAL_PROJECT.getProjectId()); } } diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/SerializationTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/SerializationTest.java index a650441b06e0..60f312c81813 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/SerializationTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/SerializationTest.java @@ -28,13 +28,13 @@ public class SerializationTest extends BaseSerializationTest { private static final ResourceManager RESOURCE_MANAGER = ResourceManagerOptions.defaultInstance().service(); - private static final ProjectInfo PARTIAL_PROJECT_INFO = ProjectInfo.builder("id1").build(); - private static final ProjectInfo FULL_PROJECT_INFO = ProjectInfo.builder("id") - .name("name") - .labels(ImmutableMap.of("key", "value")) - .projectNumber(123L) - .state(ProjectInfo.State.ACTIVE) - .createTimeMillis(1234L) + private static final ProjectInfo PARTIAL_PROJECT_INFO = ProjectInfo.newBuilder("id1").build(); + private static final ProjectInfo FULL_PROJECT_INFO = ProjectInfo.newBuilder("id") + .setName("name") + .setLabels(ImmutableMap.of("key", "value")) + .setProjectNumber(123L) + .setState(ProjectInfo.State.ACTIVE) + .setCreateTimeMillis(1234L) .build(); private static final Project PROJECT = new Project(RESOURCE_MANAGER, new ProjectInfo.BuilderImpl(FULL_PROJECT_INFO)); diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelperTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelperTest.java index cfe475cb038b..9089a093082e 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelperTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelperTest.java @@ -55,7 +55,7 @@ public class LocalResourceManagerHelperTest { private static final LocalResourceManagerHelper RESOURCE_MANAGER_HELPER = LocalResourceManagerHelper.create(); private static final ResourceManagerRpc rpc = - new DefaultResourceManagerRpc(RESOURCE_MANAGER_HELPER.options()); + new DefaultResourceManagerRpc(RESOURCE_MANAGER_HELPER.getOptions()); private static final com.google.api.services.cloudresourcemanager.model.Project PARTIAL_PROJECT = new com.google.api.services.cloudresourcemanager.model.Project().setProjectId( "partial-project"); From c6ec140fb0bc9be4c01776edb2157f554c64621b Mon Sep 17 00:00:00 2001 From: meltsufin Date: Sun, 23 Oct 2016 13:23:40 -0400 Subject: [PATCH 17/32] Fix google-cloud-logging groupId in readme (#1330) --- google-cloud-logging/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/google-cloud-logging/README.md b/google-cloud-logging/README.md index 90e302dc5157..30bdb05f87d3 100644 --- a/google-cloud-logging/README.md +++ b/google-cloud-logging/README.md @@ -24,7 +24,7 @@ Standard. `google-cloud-logging` will work on App Engine Flexible. Add this to your pom.xml file ```xml - com.google.gcloud + com.google.cloud google-cloud-logging 0.4.0 From 953dd6f706a0824527058a63c9467a56216314c1 Mon Sep 17 00:00:00 2001 From: JP Martin Date: Mon, 24 Oct 2016 04:41:17 -0700 Subject: [PATCH 18/32] Shade everything but us in the shaded nio jar (#1327) --- google-cloud-contrib/google-cloud-nio/pom.xml | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/google-cloud-contrib/google-cloud-nio/pom.xml b/google-cloud-contrib/google-cloud-nio/pom.xml index 84604fd2daa1..982f22aea9a1 100644 --- a/google-cloud-contrib/google-cloud-nio/pom.xml +++ b/google-cloud-contrib/google-cloud-nio/pom.xml @@ -111,6 +111,18 @@ org shaded.cloud-nio.org + + io + shaded.cloud-nio.io + + + javax + shaded.cloud-nio.javax + + + okio + shaded.cloud-nio.okio + google shaded.cloud-nio.google From fff9a445248c4ea9cf779ef686e1aec27aa2c289 Mon Sep 17 00:00:00 2001 From: JP Martin Date: Mon, 24 Oct 2016 23:54:16 -0700 Subject: [PATCH 19/32] Remove unused dependencies from contrib, NIO and NIO examples (#1333) --- .../google-cloud-nio-examples/README.md | 2 +- .../google-cloud-nio-examples/pom.xml | 51 +------------------ .../cloud/nio/examples/ListFilesystems.java | 6 --- google-cloud-contrib/google-cloud-nio/pom.xml | 3 +- google-cloud-contrib/pom.xml | 5 -- 5 files changed, 4 insertions(+), 63 deletions(-) diff --git a/google-cloud-contrib/google-cloud-nio-examples/README.md b/google-cloud-contrib/google-cloud-nio-examples/README.md index 0810669588b3..29cbf0978dbb 100644 --- a/google-cloud-contrib/google-cloud-nio-examples/README.md +++ b/google-cloud-contrib/google-cloud-nio-examples/README.md @@ -16,7 +16,7 @@ To run this example: 3. Compile the JAR with: ``` - mvn package -DskipTests -Dmaven.javadoc.skip=true -Dmaven.source.skip=true + mvn package -DskipTests -Dmaven.javadoc.skip=true -Dmaven.source.skip=true ``` 4. Run the sample with: diff --git a/google-cloud-contrib/google-cloud-nio-examples/pom.xml b/google-cloud-contrib/google-cloud-nio-examples/pom.xml index 469774e01e84..799ec387710b 100644 --- a/google-cloud-contrib/google-cloud-nio-examples/pom.xml +++ b/google-cloud-contrib/google-cloud-nio-examples/pom.xml @@ -22,56 +22,7 @@ google-cloud-storage ${project.version} - - com.google.guava - guava - 19.0 - - - com.google.code.findbugs - jsr305 - 2.0.1 - - - javax.inject - javax.inject - 1 - - - com.google.auto.service - auto-service - 1.0-rc2 - provided - - - com.google.auto.value - auto-value - 1.1 - provided - - - junit - junit - 4.12 - test - - - com.google.guava - guava-testlib - 19.0 - test - - - com.google.truth - truth - 0.27 - test - - - org.mockito - mockito-core - 1.9.5 - + org.apache.maven.plugins maven-assembly-plugin diff --git a/google-cloud-contrib/google-cloud-nio-examples/src/main/java/com/google/cloud/nio/examples/ListFilesystems.java b/google-cloud-contrib/google-cloud-nio-examples/src/main/java/com/google/cloud/nio/examples/ListFilesystems.java index b03dc13763d1..c81a2367cf06 100644 --- a/google-cloud-contrib/google-cloud-nio-examples/src/main/java/com/google/cloud/nio/examples/ListFilesystems.java +++ b/google-cloud-contrib/google-cloud-nio-examples/src/main/java/com/google/cloud/nio/examples/ListFilesystems.java @@ -17,12 +17,6 @@ package com.google.cloud.nio.examples; import java.io.IOException; -import java.net.URI; -import java.nio.file.FileSystem; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; import java.nio.file.spi.FileSystemProvider; /** diff --git a/google-cloud-contrib/google-cloud-nio/pom.xml b/google-cloud-contrib/google-cloud-nio/pom.xml index 982f22aea9a1..c4fe132764f5 100644 --- a/google-cloud-contrib/google-cloud-nio/pom.xml +++ b/google-cloud-contrib/google-cloud-nio/pom.xml @@ -19,7 +19,7 @@ ${project.groupId} - google-cloud + google-cloud-storage ${project.version} @@ -71,6 +71,7 @@ org.mockito mockito-core 1.9.5 + test diff --git a/google-cloud-contrib/pom.xml b/google-cloud-contrib/pom.xml index 5f3e9912047a..45a4fce5072b 100644 --- a/google-cloud-contrib/pom.xml +++ b/google-cloud-contrib/pom.xml @@ -21,11 +21,6 @@ google-cloud-nio-examples - - ${project.groupId} - google-cloud - ${project.version} - From 54ac5fe749e4e7875eaf4382590467769fcbfc38 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Tue, 25 Oct 2016 11:56:44 +0200 Subject: [PATCH 20/32] Rename setters/getters/builders for BigQuery classes to meet proto conventions (#1310) * Rename setters/getters/builders for BigQuery classes to meet proto conventions * Update BigQuery snippets to use renamed getters/setters/builders * Make deprecated methods call renamed ones * Remove useless parentheses from FieldValue --- README.md | 2 +- TESTING.md | 4 +- google-cloud-bigquery/README.md | 14 +- .../java/com/google/cloud/bigquery/Acl.java | 74 ++- .../com/google/cloud/bigquery/BigQuery.java | 24 +- .../google/cloud/bigquery/BigQueryError.java | 29 +- .../cloud/bigquery/BigQueryException.java | 11 +- .../google/cloud/bigquery/BigQueryImpl.java | 88 +-- .../cloud/bigquery/CopyJobConfiguration.java | 106 ++- .../com/google/cloud/bigquery/CsvOptions.java | 138 +++- .../com/google/cloud/bigquery/Dataset.java | 99 ++- .../com/google/cloud/bigquery/DatasetId.java | 18 +- .../google/cloud/bigquery/DatasetInfo.java | 263 +++++++- .../bigquery/ExternalTableDefinition.java | 173 ++++- .../bigquery/ExtractJobConfiguration.java | 132 +++- .../java/com/google/cloud/bigquery/Field.java | 132 +++- .../com/google/cloud/bigquery/FieldValue.java | 148 ++++- .../google/cloud/bigquery/FormatOptions.java | 12 +- .../cloud/bigquery/InsertAllRequest.java | 213 +++++- .../cloud/bigquery/InsertAllResponse.java | 21 +- .../java/com/google/cloud/bigquery/Job.java | 68 +- .../cloud/bigquery/JobConfiguration.java | 10 +- .../java/com/google/cloud/bigquery/JobId.java | 18 +- .../com/google/cloud/bigquery/JobInfo.java | 142 +++- .../google/cloud/bigquery/JobStatistics.java | 150 ++++- .../com/google/cloud/bigquery/JobStatus.java | 34 + .../cloud/bigquery/LoadConfiguration.java | 131 ++++ .../cloud/bigquery/LoadJobConfiguration.java | 203 +++++- .../com/google/cloud/bigquery/Option.java | 4 +- .../cloud/bigquery/QueryJobConfiguration.java | 247 ++++++- .../google/cloud/bigquery/QueryRequest.java | 189 +++++- .../google/cloud/bigquery/QueryResponse.java | 53 +- .../google/cloud/bigquery/QueryResult.java | 43 +- .../com/google/cloud/bigquery/QueryStage.java | 185 +++++- .../com/google/cloud/bigquery/Schema.java | 47 +- .../bigquery/StandardTableDefinition.java | 116 +++- .../java/com/google/cloud/bigquery/Table.java | 108 ++- .../cloud/bigquery/TableDefinition.java | 30 +- .../com/google/cloud/bigquery/TableId.java | 26 +- .../com/google/cloud/bigquery/TableInfo.java | 185 +++++- .../cloud/bigquery/TimePartitioning.java | 18 + .../cloud/bigquery/UserDefinedFunction.java | 28 +- .../google/cloud/bigquery/ViewDefinition.java | 94 ++- .../bigquery/WriteChannelConfiguration.java | 154 ++++- .../testing/RemoteBigQueryHelper.java | 10 +- .../cloud/bigquery/testing/package-info.java | 4 +- .../com/google/cloud/bigquery/AclTest.java | 62 ++ .../cloud/bigquery/BigQueryErrorTest.java | 24 +- .../cloud/bigquery/BigQueryExceptionTest.java | 7 + .../cloud/bigquery/BigQueryImplTest.java | 245 +++---- .../bigquery/CopyJobConfigurationTest.java | 72 +- .../google/cloud/bigquery/CsvOptionsTest.java | 49 +- .../google/cloud/bigquery/DatasetIdTest.java | 12 +- .../cloud/bigquery/DatasetInfoTest.java | 185 ++++-- .../google/cloud/bigquery/DatasetTest.java | 125 ++-- .../bigquery/ExternalTableDefinitionTest.java | 67 +- .../bigquery/ExtractJobConfigurationTest.java | 91 ++- .../com/google/cloud/bigquery/FieldTest.java | 76 ++- .../google/cloud/bigquery/FieldValueTest.java | 32 + .../cloud/bigquery/FormatOptionsTest.java | 16 +- .../cloud/bigquery/InsertAllRequestTest.java | 307 ++++++--- .../cloud/bigquery/InsertAllResponseTest.java | 11 +- .../com/google/cloud/bigquery/JobIdTest.java | 12 +- .../google/cloud/bigquery/JobInfoTest.java | 452 +++++++------ .../cloud/bigquery/JobStatisticsTest.java | 177 +++-- .../google/cloud/bigquery/JobStatusTest.java | 21 +- .../com/google/cloud/bigquery/JobTest.java | 157 +++-- .../bigquery/LoadJobConfigurationTest.java | 101 +-- .../com/google/cloud/bigquery/OptionTest.java | 8 +- .../bigquery/QueryJobConfigurationTest.java | 89 ++- .../cloud/bigquery/QueryRequestTest.java | 55 +- .../cloud/bigquery/QueryResponseTest.java | 62 +- .../cloud/bigquery/QueryResultTest.java | 48 +- .../google/cloud/bigquery/QueryStageTest.java | 83 ++- .../com/google/cloud/bigquery/SchemaTest.java | 37 +- .../cloud/bigquery/SerializationTest.java | 204 +++--- .../bigquery/StandardTableDefinitionTest.java | 96 +-- .../google/cloud/bigquery/TableIdTest.java | 14 +- .../google/cloud/bigquery/TableInfoTest.java | 272 ++++---- .../com/google/cloud/bigquery/TableTest.java | 95 ++- .../cloud/bigquery/TimePartitioningTest.java | 13 +- .../bigquery/UserDefinedFunctionTest.java | 8 + .../cloud/bigquery/ViewDefinitionTest.java | 58 +- .../WriteChannelConfigurationTest.java | 119 +++- .../cloud/bigquery/it/ITBigQueryTest.java | 626 +++++++++--------- .../testing/RemoteBigQueryHelperTest.java | 3 +- .../examples/bigquery/BigQueryExample.java | 22 +- .../bigquery/snippets/BigQuerySnippets.java | 24 +- .../snippets/CreateTableAndLoadData.java | 2 +- .../bigquery/snippets/DatasetSnippets.java | 8 +- .../snippets/InsertDataAndQueryTable.java | 14 +- .../bigquery/snippets/JobSnippets.java | 12 +- .../bigquery/snippets/TableSnippets.java | 14 +- .../bigquery/snippets/ITBigQuerySnippets.java | 63 +- .../bigquery/snippets/ITDatasetSnippets.java | 34 +- .../bigquery/snippets/ITJobSnippets.java | 37 +- .../bigquery/snippets/ITTableSnippets.java | 20 +- 97 files changed, 6248 insertions(+), 2191 deletions(-) diff --git a/README.md b/README.md index 2a09189e7879..0a0d208b028c 100644 --- a/README.md +++ b/README.md @@ -186,7 +186,7 @@ if (table == null) { System.out.println("Loading data into table " + tableId); Job loadJob = table.load(FormatOptions.csv(), "gs://bucket/path"); loadJob = loadJob.waitFor(); -if (loadJob.status().error() != null) { +if (loadJob.getStatus().getError() != null) { System.out.println("Job completed with errors"); } else { System.out.println("Job succeeded"); diff --git a/TESTING.md b/TESTING.md index cc7dce9f1462..b6a3b68082bb 100644 --- a/TESTING.md +++ b/TESTING.md @@ -27,9 +27,9 @@ Here is an example that uses the `RemoteBigQueryHelper` to create a dataset. ```java RemoteBigQueryHelper bigqueryHelper = RemoteBigQueryHelper.create(PROJECT_ID, new FileInputStream("/path/to/my/JSON/key.json")); - BigQuery bigquery = bigqueryHelper.options().service(); + BigQuery bigquery = bigqueryHelper.getOptions().service(); String dataset = RemoteBigQueryHelper.generateDatasetName(); - bigquery.create(DatasetInfo.builder(dataset).build()); + bigquery.create(DatasetInfo.newBuilder(dataset).build()); ``` 4. Run your tests. diff --git a/google-cloud-bigquery/README.md b/google-cloud-bigquery/README.md index 55027e561081..0dec46bdb8e0 100644 --- a/google-cloud-bigquery/README.md +++ b/google-cloud-bigquery/README.md @@ -103,7 +103,7 @@ Then, to create the dataset, use the following code: ```java // Create a dataset String datasetId = "my_dataset_id"; -bigquery.create(DatasetInfo.builder(datasetId).build()); +bigquery.create(DatasetInfo.newBuilder(datasetId).build()); ``` #### Creating a table @@ -153,7 +153,7 @@ Map secondRow = new HashMap<>(); firstRow.put("StringField", "value1"); secondRow.put("StringField", "value2"); // Create an insert request -InsertAllRequest insertRequest = InsertAllRequest.builder(tableId) +InsertAllRequest insertRequest = InsertAllRequest.newBuilder(tableId) .addRow(firstRow) .addRow(secondRow) .build(); @@ -183,18 +183,18 @@ Then add the following code to run the query and wait for the result: ```java // Create a query request QueryRequest queryRequest = - QueryRequest.builder("SELECT * FROM my_dataset_id.my_table_id") - .maxWaitTime(60000L) - .pageSize(1000L) + QueryRequest.newBuilder("SELECT * FROM my_dataset_id.my_table_id") + .setMaxWaitTime(60000L) + .setPageSize(1000L) .build(); // Request query to be executed and wait for results QueryResponse queryResponse = bigquery.query(queryRequest); while (!queryResponse.jobComplete()) { Thread.sleep(1000L); - queryResponse = bigquery.getQueryResults(queryResponse.jobId()); + queryResponse = bigquery.getQueryResults(queryResponse.getJobId()); } // Read rows -Iterator> rowIterator = queryResponse.result().iterateAll(); +Iterator> rowIterator = queryResponse.getResult().iterateAll(); System.out.println("Table rows:"); while (rowIterator.hasNext()) { System.out.println(rowIterator.next()); diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Acl.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Acl.java index 376b090973a5..c1d0fcb410d2 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Acl.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Acl.java @@ -80,7 +80,12 @@ public enum Type { this.type = type; } + @Deprecated public Type type() { + return getType(); + } + + public Type getType() { return type; } @@ -129,7 +134,15 @@ public Domain(String domain) { /** * Returns the domain name. */ + @Deprecated public String domain() { + return getDomain(); + } + + /** + * Returns the domain name. + */ + public String getDomain() { return domain; } @@ -142,13 +155,13 @@ public boolean equals(Object obj) { return false; } Domain domainEntity = (Domain) obj; - return Objects.equals(type(), domainEntity.type()) - && Objects.equals(domain, domainEntity.domain()); + return Objects.equals(getType(), domainEntity.getType()) + && Objects.equals(domain, domainEntity.getDomain()); } @Override public int hashCode() { - return Objects.hash(type(), domain); + return Objects.hash(getType(), domain); } @Override @@ -193,7 +206,17 @@ public Group(String identifier) { * * special group identifier or a group email. */ + @Deprecated public String identifier() { + return getIdentifier(); + } + + /** + * Returns group's identifier, can be either a + * + * special group identifier or a group email. + */ + public String getIdentifier() { return identifier; } @@ -206,12 +229,13 @@ public boolean equals(Object obj) { return false; } Group group = (Group) obj; - return Objects.equals(type(), group.type()) && Objects.equals(identifier, group.identifier); + return Objects.equals(getType(), group.getType()) + && Objects.equals(identifier, group.identifier); } @Override public int hashCode() { - return Objects.hash(type(), identifier); + return Objects.hash(getType(), identifier); } @Override @@ -285,7 +309,15 @@ public User(String email) { /** * Returns user's email. */ + @Deprecated public String email() { + return getEmail(); + } + + /** + * Returns user's email. + */ + public String getEmail() { return email; } @@ -298,12 +330,12 @@ public boolean equals(Object obj) { return false; } User user = (User) obj; - return Objects.equals(type(), user.type()) && Objects.equals(email, user.email); + return Objects.equals(getType(), user.getType()) && Objects.equals(email, user.email); } @Override public int hashCode() { - return Objects.hash(type(), email); + return Objects.hash(getType(), email); } @Override @@ -340,7 +372,15 @@ public View(TableId id) { /** * Returns table's identity. */ + @Deprecated public TableId id() { + return getId(); + } + + /** + * Returns table's identity. + */ + public TableId getId() { return id; } @@ -353,12 +393,12 @@ public boolean equals(Object obj) { return false; } View view = (View) obj; - return Objects.equals(type(), view.type()) && Objects.equals(id, view.id); + return Objects.equals(getType(), view.getType()) && Objects.equals(id, view.id); } @Override public int hashCode() { - return Objects.hash(type(), id); + return Objects.hash(getType(), id); } @Override @@ -380,14 +420,30 @@ private Acl(Entity entity, Role role) { /** * Returns the entity for this ACL. */ + @Deprecated public Entity entity() { + return getEntity(); + } + + /** + * Returns the entity for this ACL. + */ + public Entity getEntity() { return entity; } /** * Returns the role specified by this ACL. */ + @Deprecated public Role role() { + return getRole(); + } + + /** + * Returns the role specified by this ACL. + */ + public Role getRole() { return role; } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQuery.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQuery.java index 1ce896f27c05..d7a53401aeb7 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQuery.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQuery.java @@ -443,7 +443,7 @@ public static QueryResultsOption maxWaitTime(long maxWaitTime) { *

 {@code
    * String datasetName = "my_dataset_name";
    * Dataset dataset = null;
-   * DatasetInfo datasetInfo = DatasetInfo.builder(datasetName).build();
+   * DatasetInfo datasetInfo = DatasetInfo.newBuilder(datasetName).build();
    * try {
    *   // the dataset was created
    *   dataset = bigquery.create(datasetInfo);
@@ -470,7 +470,7 @@ public static QueryResultsOption maxWaitTime(long maxWaitTime) {
    * // Table schema definition
    * Schema schema = Schema.of(field);
    * TableDefinition tableDefinition = StandardTableDefinition.of(schema);
-   * TableInfo tableInfo = TableInfo.builder(tableId, tableDefinition).build();
+   * TableInfo tableInfo = TableInfo.newBuilder(tableId, tableDefinition).build();
    * Table table = bigquery.create(tableInfo);
    * }
* @@ -659,7 +659,7 @@ public static QueryResultsOption maxWaitTime(long maxWaitTime) { * String datasetName = "my_dataset_name"; * String newFriendlyName = "some_new_friendly_name"; * Dataset oldDataset = bigquery.getDataset(datasetName); - * DatasetInfo datasetInfo = oldDataset.toBuilder().friendlyName(newFriendlyName).build(); + * DatasetInfo datasetInfo = oldDataset.toBuilder().setFriendlyName(newFriendlyName).build(); * Dataset newDataset = bigquery.update(datasetInfo); * } * @@ -676,7 +676,7 @@ public static QueryResultsOption maxWaitTime(long maxWaitTime) { * String tableName = "my_table_name"; * String newFriendlyName = "new_friendly_name"; * Table oldTable = bigquery.getTable(datasetName, tableName); - * TableInfo tableInfo = oldTable.toBuilder().friendlyName(newFriendlyName).build(); + * TableInfo tableInfo = oldTable.toBuilder().setFriendlyName(newFriendlyName).build(); * Table newTable = bigquery.update(tableInfo); * } * @@ -773,13 +773,13 @@ public static QueryResultsOption maxWaitTime(long maxWaitTime) { * rowContent.put("booleanField", true); * // Bytes are passed in base64 * rowContent.put("bytesField", "DQ4KDQ=="); - * InsertAllResponse response = bigquery.insertAll(InsertAllRequest.builder(tableId) + * InsertAllResponse response = bigquery.insertAll(InsertAllRequest.newBuilder(tableId) * .addRow("rowId", rowContent) * // More rows can be added in the same RPC by invoking .addRow() on the builder * .build()); * if (response.hasErrors()) { * // If any of the insertions failed, this lets you inspect the errors - * for (Entry> entry : response.insertErrors().entrySet()) { + * for (Entry> entry : response.getInsertErrors().entrySet()) { * // inspect row error * } * } @@ -937,12 +937,12 @@ Page> listTableData(String datasetId, String tableId, * // Wait for things to finish * while (!response.jobCompleted()) { * Thread.sleep(1000); - * response = bigquery.getQueryResults(response.jobId()); + * response = bigquery.getQueryResults(response.getJobId()); * } * if (response.hasErrors()) { * // handle errors * } - * QueryResult result = response.result(); + * QueryResult result = response.getResult(); * Iterator> rowIterator = result.iterateAll(); * while (rowIterator.hasNext()) { * List row = rowIterator.next(); @@ -965,12 +965,12 @@ Page> listTableData(String datasetId, String tableId, * // Wait for things to finish * while (!response.jobCompleted()) { * Thread.sleep(1000); - * response = bigquery.getQueryResults(response.jobId()); + * response = bigquery.getQueryResults(response.getJobId()); * } * if (response.hasErrors()) { * // handle errors * } - * QueryResult result = response.result(); + * QueryResult result = response.getResult(); * Iterator> rowIterator = result.iterateAll(); * while (rowIterator.hasNext()) { * List row = rowIterator.next(); @@ -993,7 +993,9 @@ Page> listTableData(String datasetId, String tableId, * String csvData = "StringValue1\nStringValue2\n"; * TableId tableId = TableId.of(datasetName, tableName); * WriteChannelConfiguration writeChannelConfiguration = - * WriteChannelConfiguration.builder(tableId).formatOptions(FormatOptions.csv()).build(); + * WriteChannelConfiguration.newBuilder(tableId) + * .setFormatOptions(FormatOptions.csv()) + * .build(); * BaseWriteChannel writer = * bigquery.writer(writeChannelConfiguration); * // Write data to writer diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryError.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryError.java index b243cf8b1f99..17a5913425ba 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryError.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryError.java @@ -76,25 +76,52 @@ public BigQueryError(String reason, String location, String message) { * @see Troubleshooting * Errors */ + @Deprecated public String reason() { + return getReason(); + } + + /** + * Returns short error code that summarizes the error. + * + * @see Troubleshooting + * Errors + */ + public String getReason() { return reason; } /** * Returns where the error occurred, if present. */ + @Deprecated public String location() { + return getLocation(); + } + + /** + * Returns where the error occurred, if present. + */ + public String getLocation() { return location; } - String debugInfo() { + String getDebugInfo() { return debugInfo; } /** * Returns a human-readable description of the error. */ + @Deprecated public String message() { + return getMessage(); + } + + /** + * Returns a human-readable description of the error. + */ + public String getMessage() { return message; } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryException.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryException.java index 0b0c7d3152e3..230527116517 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryException.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryException.java @@ -53,7 +53,7 @@ public BigQueryException(int code, String message, Throwable cause) { } public BigQueryException(int code, String message, BigQueryError error) { - super(code, message, error != null ? error.reason() : null, true); + super(code, message, error != null ? error.getReason() : null, true); this.error = error; } @@ -70,7 +70,16 @@ public BigQueryException(IOException exception) { * Returns the {@link BigQueryError} that caused this exception. Returns {@code null} if none * exists. */ + @Deprecated public BigQueryError error() { + return getError(); + } + + /** + * Returns the {@link BigQueryError} that caused this exception. Returns {@code null} if none + * exists. + */ + public BigQueryError getError() { return error; } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryImpl.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryImpl.java index be460a1ad0e6..da8897dfd6cb 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryImpl.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryImpl.java @@ -143,7 +143,7 @@ private static class QueryResultsPageFetcherImpl @Override public QueryResult nextPage() { - return getQueryResults(job, serviceOptions, requestOptions).result(); + return getQueryResults(job, serviceOptions, requestOptions).getResult(); } } @@ -223,7 +223,7 @@ public Dataset getDataset(final DatasetId datasetId, DatasetOption... options) { @Override public com.google.api.services.bigquery.model.Dataset call() { return bigQueryRpc.getDataset( - completeDatasetId.project(), completeDatasetId.dataset(), optionsMap); + completeDatasetId.getProject(), completeDatasetId.getDataset(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Dataset.fromPb(this, answer); @@ -282,7 +282,7 @@ public boolean delete(DatasetId datasetId, DatasetDeleteOption... options) { @Override public Boolean call() { return bigQueryRpc.deleteDataset( - completeDatasetId.project(), completeDatasetId.dataset(), optionsMap); + completeDatasetId.getProject(), completeDatasetId.getDataset(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); } catch (RetryHelper.RetryHelperException e) { @@ -302,8 +302,8 @@ public boolean delete(TableId tableId) { return runWithRetries(new Callable() { @Override public Boolean call() { - return bigQueryRpc.deleteTable( - completeTableId.project(), completeTableId.dataset(), completeTableId.table()); + return bigQueryRpc.deleteTable(completeTableId.getProject(), completeTableId.getDataset(), + completeTableId.getTable()); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); } catch (RetryHelper.RetryHelperException e) { @@ -361,8 +361,8 @@ public Table getTable(TableId tableId, TableOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.bigquery.model.Table call() { - return bigQueryRpc.getTable(completeTableId.project(), completeTableId.dataset(), - completeTableId.table(), optionsMap); + return bigQueryRpc.getTable(completeTableId.getProject(), + completeTableId.getDataset(), completeTableId.getTable(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Table.fromPb(this, answer); @@ -393,7 +393,7 @@ private static Page listTables(final DatasetId datasetId, public BigQueryRpc.Tuple> call() { return serviceOptions.rpc().listTables( - datasetId.project(), datasetId.dataset(), optionsMap); + datasetId.getProject(), datasetId.getDataset(), optionsMap); } }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); String cursor = result.x(); @@ -413,20 +413,21 @@ public Table apply(com.google.api.services.bigquery.model.Table table) { @Override public InsertAllResponse insertAll(InsertAllRequest request) { - final TableId tableId = request.table().setProjectId(options().projectId()); + final TableId tableId = request.getTable().setProjectId(options().projectId()); final TableDataInsertAllRequest requestPb = new TableDataInsertAllRequest(); requestPb.setIgnoreUnknownValues(request.ignoreUnknownValues()); requestPb.setSkipInvalidRows(request.skipInvalidRows()); - requestPb.setTemplateSuffix(request.templateSuffix()); - List rowsPb = Lists.transform(request.rows(), new Function() { + requestPb.setTemplateSuffix(request.getTemplateSuffix()); + List rowsPb = Lists.transform(request.getRows(), new Function() { @Override public Rows apply(RowToInsert rowToInsert) { - return new Rows().setInsertId(rowToInsert.id()).setJson(rowToInsert.content()); + return new Rows().setInsertId(rowToInsert.getId()).setJson(rowToInsert.getContent()); } }); requestPb.setRows(rowsPb); return InsertAllResponse.fromPb( - bigQueryRpc.insertAll(tableId.project(), tableId.dataset(), tableId.table(), requestPb)); + bigQueryRpc.insertAll(tableId.getProject(), tableId.getDataset(), tableId.getTable(), + requestPb)); } @Override @@ -449,8 +450,8 @@ private static Page> listTableData(final TableId tableId, @Override public BigQueryRpc.Tuple> call() { return serviceOptions.rpc() - .listTableData(completeTableId.project(), completeTableId.dataset(), - completeTableId.table(), optionsMap); + .listTableData(completeTableId.getProject(), completeTableId.getDataset(), + completeTableId.getTable(), optionsMap); } }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); String cursor = result.x(); @@ -486,7 +487,8 @@ public Job getJob(JobId jobId, JobOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.bigquery.model.Job call() { - return bigQueryRpc.getJob(completeJobId.project(), completeJobId.job(), optionsMap); + return bigQueryRpc.getJob(completeJobId.getProject(), completeJobId.getJob(), + optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Job.fromPb(this, answer); @@ -534,7 +536,7 @@ public boolean cancel(JobId jobId) { return runWithRetries(new Callable() { @Override public Boolean call() { - return bigQueryRpc.cancel(completeJobId.project(), completeJobId.job()); + return bigQueryRpc.cancel(completeJobId.getProject(), completeJobId.getJob()); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); } catch (RetryHelper.RetryHelperException e) { @@ -552,27 +554,27 @@ public com.google.api.services.bigquery.model.QueryResponse call() { return bigQueryRpc.query(request.setProjectId(options().projectId()).toPb()); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); - QueryResponse.Builder builder = QueryResponse.builder(); + QueryResponse.Builder builder = QueryResponse.newBuilder(); JobId completeJobId = JobId.fromPb(results.getJobReference()); - builder.jobId(completeJobId); - builder.jobCompleted(results.getJobComplete()); + builder.setJobId(completeJobId); + builder.setJobCompleted(results.getJobComplete()); List rowsPb = results.getRows(); if (results.getJobComplete()) { - builder.jobCompleted(true); + builder.setJobCompleted(true); QueryResult.Builder resultBuilder = transformQueryResults(completeJobId, rowsPb, results.getPageToken(), options(), ImmutableMap.of()); - resultBuilder.totalBytesProcessed(results.getTotalBytesProcessed()); - resultBuilder.cacheHit(results.getCacheHit()); + resultBuilder.setTotalBytesProcessed(results.getTotalBytesProcessed()); + resultBuilder.setCacheHit(results.getCacheHit()); if (results.getSchema() != null) { - resultBuilder.schema(Schema.fromPb(results.getSchema())); + resultBuilder.setSchema(Schema.fromPb(results.getSchema())); } if (results.getTotalRows() != null) { - resultBuilder.totalRows(results.getTotalRows().longValue()); + resultBuilder.setTotalRows(results.getTotalRows().longValue()); } - builder.result(resultBuilder.build()); + builder.setResult(resultBuilder.build()); } if (results.getErrors() != null) { - builder.executionErrors( + builder.setExecutionErrors( Lists.transform(results.getErrors(), BigQueryError.FROM_PB_FUNCTION)); } return builder.build(); @@ -596,29 +598,29 @@ private static QueryResponse getQueryResults(JobId jobId, @Override public GetQueryResultsResponse call() { return serviceOptions.rpc().getQueryResults( - completeJobId.project(), completeJobId.job(), optionsMap); + completeJobId.getProject(), completeJobId.getJob(), optionsMap); } }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); - QueryResponse.Builder builder = QueryResponse.builder(); - builder.jobId(JobId.fromPb(results.getJobReference())); - builder.etag(results.getEtag()); - builder.jobCompleted(results.getJobComplete()); + QueryResponse.Builder builder = QueryResponse.newBuilder(); + builder.setJobId(JobId.fromPb(results.getJobReference())); + builder.setEtag(results.getEtag()); + builder.setJobCompleted(results.getJobComplete()); List rowsPb = results.getRows(); if (results.getJobComplete()) { QueryResult.Builder resultBuilder = transformQueryResults(completeJobId, rowsPb, results.getPageToken(), serviceOptions, ImmutableMap.of()); - resultBuilder.totalBytesProcessed(results.getTotalBytesProcessed()); - resultBuilder.cacheHit(results.getCacheHit()); + resultBuilder.setTotalBytesProcessed(results.getTotalBytesProcessed()); + resultBuilder.setCacheHit(results.getCacheHit()); if (results.getSchema() != null) { - resultBuilder.schema(Schema.fromPb(results.getSchema())); + resultBuilder.setSchema(Schema.fromPb(results.getSchema())); } if (results.getTotalRows() != null) { - resultBuilder.totalRows(results.getTotalRows().longValue()); + resultBuilder.setTotalRows(results.getTotalRows().longValue()); } - builder.result(resultBuilder.build()); + builder.setResult(resultBuilder.build()); } if (results.getErrors() != null) { - builder.executionErrors( + builder.setExecutionErrors( Lists.transform(results.getErrors(), BigQueryError.FROM_PB_FUNCTION)); } return builder.build(); @@ -631,10 +633,10 @@ private static QueryResult.Builder transformQueryResults(JobId jobId, List
optionsMap) { QueryResultsPageFetcherImpl nextPageFetcher = new QueryResultsPageFetcherImpl(jobId, serviceOptions, cursor, optionsMap); - return QueryResult.builder() - .pageFetcher(nextPageFetcher) - .cursor(cursor) - .results(transformTableData(rowsPb)); + return QueryResult.newBuilder() + .setPageFetcher(nextPageFetcher) + .setCursor(cursor) + .setResults(transformTableData(rowsPb)); } @Override @@ -646,7 +648,7 @@ public TableDataWriteChannel writer(WriteChannelConfiguration writeChannelConfig private Map optionMap(Option... options) { Map optionMap = Maps.newEnumMap(BigQueryRpc.Option.class); for (Option option : options) { - Object prev = optionMap.put(option.rpcOption(), option.value()); + Object prev = optionMap.put(option.getRpcOption(), option.getValue()); checkArgument(prev == null, "Duplicate option %s", option); } return optionMap; diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/CopyJobConfiguration.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/CopyJobConfiguration.java index e455416bea7b..ce6cf2011bed 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/CopyJobConfiguration.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/CopyJobConfiguration.java @@ -83,7 +83,15 @@ private Builder(com.google.api.services.bigquery.model.JobConfiguration configur /** * Sets the source tables to copy. */ + @Deprecated public Builder sourceTables(List sourceTables) { + return setSourceTables(sourceTables); + } + + /** + * Sets the source tables to copy. + */ + public Builder setSourceTables(List sourceTables) { this.sourceTables = sourceTables != null ? ImmutableList.copyOf(sourceTables) : null; return this; } @@ -91,7 +99,15 @@ public Builder sourceTables(List sourceTables) { /** * Sets the destination table of the copy job. */ + @Deprecated public Builder destinationTable(TableId destinationTable) { + return setDestinationTable(destinationTable); + } + + /** + * Sets the destination table of the copy job. + */ + public Builder setDestinationTable(TableId destinationTable) { this.destinationTable = destinationTable; return this; } @@ -102,7 +118,18 @@ public Builder destinationTable(TableId destinationTable) { * @see * Create Disposition */ + @Deprecated public Builder createDisposition(JobInfo.CreateDisposition createDisposition) { + return setCreateDisposition(createDisposition); + } + + /** + * Sets whether the job is allowed to create new tables. + * + * @see + * Create Disposition + */ + public Builder setCreateDisposition(JobInfo.CreateDisposition createDisposition) { this.createDisposition = createDisposition; return this; } @@ -113,7 +140,18 @@ public Builder createDisposition(JobInfo.CreateDisposition createDisposition) { * @see * Write Disposition */ + @Deprecated public Builder writeDisposition(JobInfo.WriteDisposition writeDisposition) { + return setWriteDisposition(writeDisposition); + } + + /** + * Sets the action that should occur if the destination table already exists. + * + * @see + * Write Disposition + */ + public Builder setWriteDisposition(JobInfo.WriteDisposition writeDisposition) { this.writeDisposition = writeDisposition; return this; } @@ -134,14 +172,30 @@ private CopyJobConfiguration(Builder builder) { /** * Returns the source tables to copy. */ + @Deprecated public List sourceTables() { + return getSourceTables(); + } + + /** + * Returns the source tables to copy. + */ + public List getSourceTables() { return sourceTables; } /** * Returns the destination table to load the data into. */ + @Deprecated public TableId destinationTable() { + return getDestinationTable(); + } + + /** + * Returns the destination table to load the data into. + */ + public TableId getDestinationTable() { return destinationTable; } @@ -151,7 +205,18 @@ public TableId destinationTable() { * @see * Create Disposition */ + @Deprecated public JobInfo.CreateDisposition createDisposition() { + return this.getCreateDisposition(); + } + + /** + * Returns whether the job is allowed to create new tables. + * + * @see + * Create Disposition + */ + public JobInfo.CreateDisposition getCreateDisposition() { return this.createDisposition; } @@ -161,7 +226,18 @@ public JobInfo.CreateDisposition createDisposition() { * @see * Write Disposition */ + @Deprecated public JobInfo.WriteDisposition writeDisposition() { + return getWriteDisposition(); + } + + /** + * Returns the action that should occur if the destination table already exists. + * + * @see + * Write Disposition + */ + public JobInfo.WriteDisposition getWriteDisposition() { return writeDisposition; } @@ -195,14 +271,14 @@ public int hashCode() { @Override CopyJobConfiguration setProjectId(final String projectId) { Builder builder = toBuilder(); - builder.sourceTables( - Lists.transform(sourceTables(), new Function() { + builder.setSourceTables( + Lists.transform(getSourceTables(), new Function() { @Override public TableId apply(TableId tableId) { return tableId.setProjectId(projectId); } })); - builder.destinationTable(destinationTable().setProjectId(projectId)); + builder.setDestinationTable(getDestinationTable().setProjectId(projectId)); return builder.build(); } @@ -227,29 +303,45 @@ com.google.api.services.bigquery.model.JobConfiguration toPb() { /** * Creates a builder for a BigQuery Copy Job configuration given destination and source table. */ + @Deprecated public static Builder builder(TableId destinationTable, TableId sourceTable) { - return builder(destinationTable, ImmutableList.of(checkNotNull(sourceTable))); + return newBuilder(destinationTable, sourceTable); + } + + /** + * Creates a builder for a BigQuery Copy Job configuration given destination and source table. + */ + public static Builder newBuilder(TableId destinationTable, TableId sourceTable) { + return newBuilder(destinationTable, ImmutableList.of(checkNotNull(sourceTable))); } /** * Creates a builder for a BigQuery Copy Job configuration given destination and source tables. */ + @Deprecated public static Builder builder(TableId destinationTable, List sourceTables) { - return new Builder().destinationTable(destinationTable).sourceTables(sourceTables); + return newBuilder(destinationTable, sourceTables); + } + + /** + * Creates a builder for a BigQuery Copy Job configuration given destination and source tables. + */ + public static Builder newBuilder(TableId destinationTable, List sourceTables) { + return new Builder().setDestinationTable(destinationTable).setSourceTables(sourceTables); } /** * Returns a BigQuery Copy Job configuration for the given destination and source table. */ public static CopyJobConfiguration of(TableId destinationTable, TableId sourceTable) { - return builder(destinationTable, sourceTable).build(); + return newBuilder(destinationTable, sourceTable).build(); } /** * Returns a BigQuery Copy Job configuration for the given destination and source tables. */ public static CopyJobConfiguration of(TableId destinationTable, List sourceTables) { - return builder(destinationTable, sourceTables).build(); + return newBuilder(destinationTable, sourceTables).build(); } @SuppressWarnings("unchecked") diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/CsvOptions.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/CsvOptions.java index 4273740f91d2..8cb56d61549f 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/CsvOptions.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/CsvOptions.java @@ -63,7 +63,19 @@ private Builder(CsvOptions csvOptions) { * bad records, an invalid error is returned in the job result. By default, rows with missing * trailing columns are considered bad records. */ + @Deprecated public Builder allowJaggedRows(boolean allowJaggedRows) { + return setAllowJaggedRows(allowJaggedRows); + } + + /** + * Set whether BigQuery should accept rows that are missing trailing optional columns. If + * {@code true}, BigQuery treats missing trailing columns as null values. If {@code false}, + * records with missing trailing columns are treated as bad records, and if there are too many + * bad records, an invalid error is returned in the job result. By default, rows with missing + * trailing columns are considered bad records. + */ + public Builder setAllowJaggedRows(boolean allowJaggedRows) { this.allowJaggedRows = allowJaggedRows; return this; } @@ -72,7 +84,16 @@ public Builder allowJaggedRows(boolean allowJaggedRows) { * Sets whether BigQuery should allow quoted data sections that contain newline characters in a * CSV file. By default quoted newline are not allowed. */ + @Deprecated public Builder allowQuotedNewLines(boolean allowQuotedNewLines) { + return setAllowQuotedNewLines(allowQuotedNewLines); + } + + /** + * Sets whether BigQuery should allow quoted data sections that contain newline characters in a + * CSV file. By default quoted newline are not allowed. + */ + public Builder setAllowQuotedNewLines(boolean allowQuotedNewLines) { this.allowQuotedNewLines = allowQuotedNewLines; return this; } @@ -82,7 +103,17 @@ public Builder allowQuotedNewLines(boolean allowQuotedNewLines) { * default value is UTF-8. BigQuery decodes the data after the raw, binary data has been split * using the values set in {@link #quote(String)} and {@link #fieldDelimiter(String)}. */ + @Deprecated public Builder encoding(String encoding) { + return setEncoding(encoding); + } + + /** + * Sets the character encoding of the data. The supported values are UTF-8 or ISO-8859-1. The + * default value is UTF-8. BigQuery decodes the data after the raw, binary data has been split + * using the values set in {@link #quote(String)} and {@link #fieldDelimiter(String)}. + */ + public Builder setEncoding(String encoding) { this.encoding = encoding; return this; } @@ -92,7 +123,17 @@ public Builder encoding(String encoding) { * default value is UTF-8. BigQuery decodes the data after the raw, binary data has been split * using the values set in {@link #quote(String)} and {@link #fieldDelimiter(String)}. */ + @Deprecated public Builder encoding(Charset encoding) { + return setEncoding(encoding); + } + + /** + * Sets the character encoding of the data. The supported values are UTF-8 or ISO-8859-1. The + * default value is UTF-8. BigQuery decodes the data after the raw, binary data has been split + * using the values set in {@link #quote(String)} and {@link #fieldDelimiter(String)}. + */ + public Builder setEncoding(Charset encoding) { this.encoding = encoding.name(); return this; } @@ -103,7 +144,18 @@ public Builder encoding(Charset encoding) { * binary state. BigQuery also supports the escape sequence "\t" to specify a tab separator. * The default value is a comma (','). */ + @Deprecated public Builder fieldDelimiter(String fieldDelimiter) { + return setFieldDelimiter(fieldDelimiter); + } + + /** + * Sets the separator for fields in a CSV file. BigQuery converts the string to ISO-8859-1 + * encoding, and then uses the first byte of the encoded string to split the data in its raw, + * binary state. BigQuery also supports the escape sequence "\t" to specify a tab separator. + * The default value is a comma (','). + */ + public Builder setFieldDelimiter(String fieldDelimiter) { this.fieldDelimiter = fieldDelimiter; return this; } @@ -116,7 +168,20 @@ public Builder fieldDelimiter(String fieldDelimiter) { * contains quoted newline characters, you must also set {@link #allowQuotedNewLines(boolean)} * property to {@code true}. */ + @Deprecated public Builder quote(String quote) { + return setQuote(quote); + } + + /** + * Sets the value that is used to quote data sections in a CSV file. BigQuery converts the + * string to ISO-8859-1 encoding, and then uses the first byte of the encoded string to split + * the data in its raw, binary state. The default value is a double-quote ('"'). If your data + * does not contain quoted sections, set the property value to an empty string. If your data + * contains quoted newline characters, you must also set {@link #allowQuotedNewLines(boolean)} + * property to {@code true}. + */ + public Builder setQuote(String quote) { this.quote = quote; return this; } @@ -126,7 +191,17 @@ public Builder quote(String quote) { * data. The default value is 0. This property is useful if you have header rows in the file * that should be skipped. */ + @Deprecated public Builder skipLeadingRows(long skipLeadingRows) { + return setSkipLeadingRows(skipLeadingRows); + } + + /** + * Sets the number of rows at the top of a CSV file that BigQuery will skip when reading the + * data. The default value is 0. This property is useful if you have header rows in the file + * that should be skipped. + */ + public Builder setSkipLeadingRows(long skipLeadingRows) { this.skipLeadingRows = skipLeadingRows; return this; } @@ -171,23 +246,49 @@ public Boolean allowQuotedNewLines() { /** * Returns the character encoding of the data. The supported values are UTF-8 or ISO-8859-1. If * not set, UTF-8 is used. BigQuery decodes the data after the raw, binary data has been split - * using the values set in {@link #quote()} and {@link #fieldDelimiter()}. + * using the values set in {@link #getQuote()} and {@link #getFieldDelimiter()}. */ + @Deprecated public String encoding() { + return getEncoding(); + } + + /** + * Returns the character encoding of the data. The supported values are UTF-8 or ISO-8859-1. If + * not set, UTF-8 is used. BigQuery decodes the data after the raw, binary data has been split + * using the values set in {@link #getQuote()} and {@link #getFieldDelimiter()}. + */ + public String getEncoding() { return encoding; } /** * Returns the separator for fields in a CSV file. */ + @Deprecated public String fieldDelimiter() { + return getFieldDelimiter(); + } + + /** + * Returns the separator for fields in a CSV file. + */ + public String getFieldDelimiter() { return fieldDelimiter; } /** * Returns the value that is used to quote data sections in a CSV file. */ + @Deprecated public String quote() { + return getQuote(); + } + + /** + * Returns the value that is used to quote data sections in a CSV file. + */ + public String getQuote() { return quote; } @@ -195,7 +296,16 @@ public String quote() { * Returns the number of rows at the top of a CSV file that BigQuery will skip when reading the * data. */ + @Deprecated public Long skipLeadingRows() { + return getSkipLeadingRows(); + } + + /** + * Returns the number of rows at the top of a CSV file that BigQuery will skip when reading the + * data. + */ + public Long getSkipLeadingRows() { return skipLeadingRows; } @@ -209,7 +319,7 @@ public Builder toBuilder() { @Override public String toString() { return MoreObjects.toStringHelper(this) - .add("type", type()) + .add("type", getType()) .add("allowJaggedRows", allowJaggedRows) .add("allowQuotedNewLines", allowQuotedNewLines) .add("encoding", encoding) @@ -221,7 +331,7 @@ public String toString() { @Override public int hashCode() { - return Objects.hash(type(), allowJaggedRows, allowQuotedNewLines, encoding, fieldDelimiter, + return Objects.hash(getType(), allowJaggedRows, allowQuotedNewLines, encoding, fieldDelimiter, quote, skipLeadingRows); } @@ -247,29 +357,37 @@ com.google.api.services.bigquery.model.CsvOptions toPb() { /** * Returns a builder for a CsvOptions object. */ + @Deprecated public static Builder builder() { + return newBuilder(); + } + + /** + * Returns a builder for a CsvOptions object. + */ + public static Builder newBuilder() { return new Builder(); } static CsvOptions fromPb(com.google.api.services.bigquery.model.CsvOptions csvOptions) { - Builder builder = builder(); + Builder builder = newBuilder(); if (csvOptions.getAllowJaggedRows() != null) { - builder.allowJaggedRows(csvOptions.getAllowJaggedRows()); + builder.setAllowJaggedRows(csvOptions.getAllowJaggedRows()); } if (csvOptions.getAllowQuotedNewlines() != null) { - builder.allowQuotedNewLines(csvOptions.getAllowQuotedNewlines()); + builder.setAllowQuotedNewLines(csvOptions.getAllowQuotedNewlines()); } if (csvOptions.getEncoding() != null) { - builder.encoding(csvOptions.getEncoding()); + builder.setEncoding(csvOptions.getEncoding()); } if (csvOptions.getFieldDelimiter() != null) { - builder.fieldDelimiter(csvOptions.getFieldDelimiter()); + builder.setFieldDelimiter(csvOptions.getFieldDelimiter()); } if (csvOptions.getQuote() != null) { - builder.quote(csvOptions.getQuote()); + builder.setQuote(csvOptions.getQuote()); } if (csvOptions.getSkipLeadingRows() != null) { - builder.skipLeadingRows(csvOptions.getSkipLeadingRows()); + builder.setSkipLeadingRows(csvOptions.getSkipLeadingRows()); } return builder.build(); } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Dataset.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Dataset.java index 2e95b0ac24b1..dc81fa5f1a45 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Dataset.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Dataset.java @@ -56,7 +56,7 @@ public static final class Builder extends DatasetInfo.Builder { Builder(BigQuery bigquery, DatasetId datasetId) { this.bigquery = bigquery; this.infoBuilder = new DatasetInfo.BuilderImpl(); - this.infoBuilder.datasetId(datasetId); + this.infoBuilder.setDatasetId(datasetId); } Builder(Dataset dataset) { @@ -65,68 +65,104 @@ public static final class Builder extends DatasetInfo.Builder { } @Override + @Deprecated public Builder datasetId(DatasetId datasetId) { - infoBuilder.datasetId(datasetId); + return setDatasetId(datasetId); + } + + @Override + public Builder setDatasetId(DatasetId datasetId) { + infoBuilder.setDatasetId(datasetId); return this; } @Override + @Deprecated public Builder acl(List acl) { - infoBuilder.acl(acl); + return setAcl(acl); + } + + @Override + public Builder setAcl(List acl) { + infoBuilder.setAcl(acl); return this; } @Override - Builder creationTime(Long creationTime) { - infoBuilder.creationTime(creationTime); + Builder setCreationTime(Long creationTime) { + infoBuilder.setCreationTime(creationTime); return this; } @Override + @Deprecated public Builder defaultTableLifetime(Long defaultTableLifetime) { - infoBuilder.defaultTableLifetime(defaultTableLifetime); + return setDefaultTableLifetime(defaultTableLifetime); + } + + @Override + public Builder setDefaultTableLifetime(Long defaultTableLifetime) { + infoBuilder.setDefaultTableLifetime(defaultTableLifetime); return this; } @Override + @Deprecated public Builder description(String description) { - infoBuilder.description(description); + return setDescription(description); + } + + @Override + public Builder setDescription(String description) { + infoBuilder.setDescription(description); return this; } @Override - Builder etag(String etag) { - infoBuilder.etag(etag); + Builder setEtag(String etag) { + infoBuilder.setEtag(etag); return this; } @Override + @Deprecated public Builder friendlyName(String friendlyName) { - infoBuilder.friendlyName(friendlyName); + return setFriendlyName(friendlyName); + } + + @Override + public Builder setFriendlyName(String friendlyName) { + infoBuilder.setFriendlyName(friendlyName); return this; } @Override - Builder generatedId(String generatedId) { - infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + infoBuilder.setGeneratedId(generatedId); return this; } @Override - Builder lastModified(Long lastModified) { - infoBuilder.lastModified(lastModified); + Builder setLastModified(Long lastModified) { + infoBuilder.setLastModified(lastModified); return this; } @Override + @Deprecated public Builder location(String location) { - infoBuilder.location(location); + return setLocation(location); + } + + @Override + public Builder setLocation(String location) { + infoBuilder.setLocation(location); return this; } @Override - Builder selfLink(String selfLink) { - infoBuilder.selfLink(selfLink); + Builder setSelfLink(String selfLink) { + infoBuilder.setSelfLink(selfLink); return this; } @@ -159,7 +195,7 @@ public Dataset build() { * @throws BigQueryException upon failure */ public boolean exists() { - return bigquery.getDataset(datasetId(), DatasetOption.fields()) != null; + return bigquery.getDataset(getDatasetId(), DatasetOption.fields()) != null; } /** @@ -179,7 +215,7 @@ public boolean exists() { * @throws BigQueryException upon failure */ public Dataset reload(DatasetOption... options) { - return bigquery.getDataset(datasetId().dataset(), options); + return bigquery.getDataset(getDatasetId().getDataset(), options); } /** @@ -190,7 +226,7 @@ public Dataset reload(DatasetOption... options) { *
 {@code
    * String friendlyName = "my_friendly_name";
    * Builder builder = dataset.toBuilder();
-   * builder.friendlyName(friendlyName);
+   * builder.setFriendlyName(friendlyName);
    * Dataset updatedDataset = builder.build().update();
    * }
* @@ -219,7 +255,7 @@ public Dataset update(DatasetOption... options) { * @throws BigQueryException upon failure */ public boolean delete(DatasetDeleteOption... options) { - return bigquery.delete(datasetId(), options); + return bigquery.delete(getDatasetId(), options); } /** @@ -239,7 +275,7 @@ public boolean delete(DatasetDeleteOption... options) { * @throws BigQueryException upon failure */ public Page
list(TableListOption... options) { - return bigquery.listTables(datasetId(), options); + return bigquery.listTables(getDatasetId(), options); } /** @@ -256,7 +292,7 @@ public Page
list(TableListOption... options) { * @throws BigQueryException upon failure */ public Table get(String tableId, TableOption... options) { - return bigquery.getTable(TableId.of(datasetId().dataset(), tableId), options); + return bigquery.getTable(TableId.of(getDatasetId().getDataset(), tableId), options); } /** @@ -267,9 +303,9 @@ public Table get(String tableId, TableOption... options) { * String tableName = “my_table”; * String fieldName = “my_field”; * Schema schema = Schema.of(Field.of(fieldName, Type.string())); - * StandardTableDefinition definition = StandardTableDefinition.builder() - * .schema(schema) - * .timePartitioning(TimePartitioning.of(TimePartitioning.Type.DAY)) + * StandardTableDefinition definition = StandardTableDefinition.newBuilder() + * .setSchema(schema) + * .setTimePartitioning(TimePartitioning.of(TimePartitioning.Type.DAY)) * .build(); * Table table = dataset.create(tableName, definition); * } @@ -281,14 +317,23 @@ public Table get(String tableId, TableOption... options) { * @throws BigQueryException upon failure */ public Table create(String tableId, TableDefinition definition, TableOption... options) { - TableInfo tableInfo = TableInfo.of(TableId.of(datasetId().dataset(), tableId), definition); + TableInfo tableInfo = + TableInfo.of(TableId.of(getDatasetId().getDataset(), tableId), definition); return bigquery.create(tableInfo, options); } /** * Returns the dataset's {@code BigQuery} object used to issue requests. */ + @Deprecated public BigQuery bigquery() { + return getBigquery(); + } + + /** + * Returns the dataset's {@code BigQuery} object used to issue requests. + */ + public BigQuery getBigquery() { return bigquery; } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/DatasetId.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/DatasetId.java index a6f2762da9cd..44b1d69ea3d7 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/DatasetId.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/DatasetId.java @@ -36,14 +36,30 @@ public final class DatasetId implements Serializable { /** * Returns project's user-defined id. */ + @Deprecated public String project() { + return getProject(); + } + + /** + * Returns project's user-defined id. + */ + public String getProject() { return project; } /** * Returns dataset's user-defined id. */ + @Deprecated public String dataset() { + return getDataset(); + } + + /** + * Returns dataset's user-defined id. + */ + public String getDataset() { return dataset; } @@ -84,7 +100,7 @@ public String toString() { } DatasetId setProjectId(String projectId) { - return project() != null ? this : DatasetId.of(projectId, dataset()); + return getProject() != null ? this : DatasetId.of(projectId, getDataset()); } DatasetReference toPb() { diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/DatasetInfo.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/DatasetInfo.java index 0ea3f9a36147..457b04e6eced 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/DatasetInfo.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/DatasetInfo.java @@ -77,16 +77,30 @@ public abstract static class Builder { /** * Sets the dataset identity. */ + @Deprecated public abstract Builder datasetId(DatasetId datasetId); + /** + * Sets the dataset identity. + */ + public abstract Builder setDatasetId(DatasetId datasetId); + /** * Sets the dataset's access control configuration. * * @see Access Control */ + @Deprecated public abstract Builder acl(List acl); - abstract Builder creationTime(Long creationTime); + /** + * Sets the dataset's access control configuration. + * + * @see Access Control + */ + public abstract Builder setAcl(List acl); + + abstract Builder setCreationTime(Long creationTime); /** * Sets the default lifetime of all tables in the dataset, in milliseconds. The minimum value is @@ -99,23 +113,49 @@ public abstract static class Builder { * expiration time indicated by this property. This property is experimental and might be * subject to change or removed. */ + @Deprecated public abstract Builder defaultTableLifetime(Long defaultTableLifetime); + /** + * Sets the default lifetime of all tables in the dataset, in milliseconds. The minimum value is + * 3600000 milliseconds (one hour). Once this property is set, all newly-created tables in the + * dataset will have an expirationTime property set to the creation time plus the value in this + * property, and changing the value will only affect new tables, not existing ones. When the + * expirationTime for a given table is reached, that table will be deleted automatically. If a + * table's expirationTime is modified or removed before the table expires, or if you provide an + * explicit expirationTime when creating a table, that value takes precedence over the default + * expiration time indicated by this property. This property is experimental and might be + * subject to change or removed. + */ + public abstract Builder setDefaultTableLifetime(Long defaultTableLifetime); + /** * Sets a user-friendly description for the dataset. */ + @Deprecated public abstract Builder description(String description); - abstract Builder etag(String etag); + /** + * Sets a user-friendly description for the dataset. + */ + public abstract Builder setDescription(String description); + + abstract Builder setEtag(String etag); /** * Sets a user-friendly name for the dataset. */ + @Deprecated public abstract Builder friendlyName(String friendlyName); - abstract Builder generatedId(String generatedId); + /** + * Sets a user-friendly name for the dataset. + */ + public abstract Builder setFriendlyName(String friendlyName); - abstract Builder lastModified(Long lastModified); + abstract Builder setGeneratedId(String generatedId); + + abstract Builder setLastModified(Long lastModified); /** * Sets the geographic location where the dataset should reside. This property is experimental @@ -124,9 +164,19 @@ public abstract static class Builder { * @see Dataset * Location */ + @Deprecated public abstract Builder location(String location); - abstract Builder selfLink(String selfLink); + /** + * Sets the geographic location where the dataset should reside. This property is experimental + * and might be subject to change or removed. + * + * @see Dataset + * Location + */ + public abstract Builder setLocation(String location); + + abstract Builder setSelfLink(String selfLink); /** * Creates a {@code DatasetInfo} object. @@ -188,68 +238,104 @@ public Acl apply(Dataset.Access accessPb) { } @Override + @Deprecated public Builder datasetId(DatasetId datasetId) { + return setDatasetId(datasetId); + } + + @Override + public Builder setDatasetId(DatasetId datasetId) { this.datasetId = checkNotNull(datasetId); return this; } @Override + @Deprecated public Builder acl(List acl) { + return setAcl(acl); + } + + @Override + public Builder setAcl(List acl) { this.acl = acl != null ? ImmutableList.copyOf(acl) : null; return this; } @Override - Builder creationTime(Long creationTime) { + Builder setCreationTime(Long creationTime) { this.creationTime = creationTime; return this; } @Override + @Deprecated public Builder defaultTableLifetime(Long defaultTableLifetime) { + return setDefaultTableLifetime(defaultTableLifetime); + } + + @Override + public Builder setDefaultTableLifetime(Long defaultTableLifetime) { this.defaultTableLifetime = firstNonNull(defaultTableLifetime, Data.nullOf(Long.class)); return this; } @Override + @Deprecated public Builder description(String description) { + return setDescription(description); + } + + @Override + public Builder setDescription(String description) { this.description = firstNonNull(description, Data.nullOf(String.class)); return this; } @Override - Builder etag(String etag) { + Builder setEtag(String etag) { this.etag = etag; return this; } @Override + @Deprecated public Builder friendlyName(String friendlyName) { + return setFriendlyName(friendlyName); + } + + @Override + public Builder setFriendlyName(String friendlyName) { this.friendlyName = firstNonNull(friendlyName, Data.nullOf(String.class)); return this; } @Override - Builder generatedId(String generatedId) { + Builder setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } @Override - Builder lastModified(Long lastModified) { + Builder setLastModified(Long lastModified) { this.lastModified = lastModified; return this; } @Override + @Deprecated public Builder location(String location) { + return setLocation(location); + } + + @Override + public Builder setLocation(String location) { this.location = firstNonNull(location, Data.nullOf(String.class)); return this; } @Override - Builder selfLink(String selfLink) { + Builder setSelfLink(String selfLink) { this.selfLink = selfLink; return this; } @@ -277,7 +363,15 @@ public DatasetInfo build() { /** * Returns the dataset identity. */ + @Deprecated public DatasetId datasetId() { + return getDatasetId(); + } + + /** + * Returns the dataset identity. + */ + public DatasetId getDatasetId() { return datasetId; } @@ -286,14 +380,32 @@ public DatasetId datasetId() { * * @see Access Control */ + @Deprecated public List acl() { + return getAcl(); + } + + /** + * Returns the dataset's access control configuration. + * + * @see Access Control + */ + public List getAcl() { return acl; } /** * Returns the time when this dataset was created, in milliseconds since the epoch. */ + @Deprecated public Long creationTime() { + return getCreationTime(); + } + + /** + * Returns the time when this dataset was created, in milliseconds since the epoch. + */ + public Long getCreationTime() { return creationTime; } @@ -306,35 +418,81 @@ public Long creationTime() { * table expires, or if you provide an explicit expirationTime when creating a table, that value * takes precedence over the default expiration time indicated by this property. */ + @Deprecated public Long defaultTableLifetime() { + return getDefaultTableLifetime(); + } + + /** + * Returns the default lifetime of all tables in the dataset, in milliseconds. Once this property + * is set, all newly-created tables in the dataset will have an expirationTime property set to the + * creation time plus the value in this property, and changing the value will only affect new + * tables, not existing ones. When the expirationTime for a given table is reached, that table + * will be deleted automatically. If a table's expirationTime is modified or removed before the + * table expires, or if you provide an explicit expirationTime when creating a table, that value + * takes precedence over the default expiration time indicated by this property. + */ + public Long getDefaultTableLifetime() { return defaultTableLifetime; } /** * Returns a user-friendly description for the dataset. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns a user-friendly description for the dataset. + */ + public String getDescription() { return description; } /** * Returns the hash of the dataset resource. */ + @Deprecated public String etag() { + return getEtag(); + } + + /** + * Returns the hash of the dataset resource. + */ + public String getEtag() { return etag; } /** * Returns a user-friendly name for the dataset. */ + @Deprecated public String friendlyName() { + return getFriendlyName(); + } + + /** + * Returns a user-friendly name for the dataset. + */ + public String getFriendlyName() { return friendlyName; } /** * Returns the service-generated id for the dataset. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated id for the dataset. + */ + public String getGeneratedId() { return generatedId; } @@ -342,7 +500,16 @@ public String generatedId() { * Returns the time when this dataset or any of its tables was last modified, in milliseconds * since the epoch. */ + @Deprecated public Long lastModified() { + return getLastModified(); + } + + /** + * Returns the time when this dataset or any of its tables was last modified, in milliseconds + * since the epoch. + */ + public Long getLastModified() { return lastModified; } @@ -352,7 +519,18 @@ public Long lastModified() { * @see * Dataset Location */ + @Deprecated public String location() { + return getLocation(); + } + + /** + * Returns the geographic location where the dataset should reside. + * + * @see + * Dataset Location + */ + public String getLocation() { return location; } @@ -360,7 +538,16 @@ public String location() { * Returns an URL that can be used to access the resource again. The returned URL can be used for * get or update requests. */ + @Deprecated public String selfLink() { + return getSelfLink(); + } + + /** + * Returns an URL that can be used to access the resource again. The returned URL can be used for + * get or update requests. + */ + public String getSelfLink() { return selfLink; } @@ -403,11 +590,11 @@ public boolean equals(Object obj) { DatasetInfo setProjectId(String projectId) { Builder builder = toBuilder(); - builder.datasetId(datasetId().setProjectId(projectId)); - if (acl() != null) { - List acls = Lists.newArrayListWithCapacity(acl().size()); - for (Acl acl : acl()) { - if (acl.entity().type() == Acl.Entity.Type.VIEW) { + builder.setDatasetId(getDatasetId().setProjectId(projectId)); + if (getAcl() != null) { + List acls = Lists.newArrayListWithCapacity(getAcl().size()); + for (Acl acl : getAcl()) { + if (acl.getEntity().getType() == Acl.Entity.Type.VIEW) { Dataset.Access accessPb = acl.toPb(); TableReference viewReferencePb = accessPb.getView(); if (viewReferencePb.getProjectId() == null) { @@ -418,7 +605,7 @@ DatasetInfo setProjectId(String projectId) { acls.add(acl); } } - builder.acl(acls); + builder.setAcl(acls); } return builder.build(); } @@ -449,36 +636,60 @@ public Dataset.Access apply(Acl acl) { /** * Returns a builder for a {@code DatasetInfo} object given it's identity. */ + @Deprecated public static Builder builder(DatasetId datasetId) { - return new BuilderImpl().datasetId(datasetId); + return newBuilder(datasetId); + } + + /** + * Returns a builder for a {@code DatasetInfo} object given it's identity. + */ + public static Builder newBuilder(DatasetId datasetId) { + return new BuilderImpl().setDatasetId(datasetId); } /** * Returns a builder for a {@code DatasetInfo} object given it's user-defined id. */ + @Deprecated public static Builder builder(String datasetId) { - return builder(DatasetId.of(datasetId)); + return newBuilder(datasetId); } /** - * Returns a {@code DatasetInfo} object given it's identity. + * Returns a builder for a {@code DatasetInfo} object given it's user-defined id. */ - public static DatasetInfo of(DatasetId datasetId) { - return builder(datasetId).build(); + public static Builder newBuilder(String datasetId) { + return newBuilder(DatasetId.of(datasetId)); } /** - * Returns a {@code DatasetInfo} object given it's user-defined id. + * Returns a builder for the DatasetInfo object given it's user-defined project and dataset ids. */ - public static DatasetInfo of(String datasetId) { - return builder(datasetId).build(); + @Deprecated + public static Builder builder(String projectId, String datasetId) { + return newBuilder(projectId, datasetId); } /** * Returns a builder for the DatasetInfo object given it's user-defined project and dataset ids. */ - public static Builder builder(String projectId, String datasetId) { - return builder(DatasetId.of(projectId, datasetId)); + public static Builder newBuilder(String projectId, String datasetId) { + return newBuilder(DatasetId.of(projectId, datasetId)); + } + + /** + * Returns a {@code DatasetInfo} object given it's identity. + */ + public static DatasetInfo of(DatasetId datasetId) { + return newBuilder(datasetId).build(); + } + + /** + * Returns a {@code DatasetInfo} object given it's user-defined id. + */ + public static DatasetInfo of(String datasetId) { + return newBuilder(datasetId).build(); } static DatasetInfo fromPb(Dataset datasetPb) { diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExternalTableDefinition.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExternalTableDefinition.java index af17c281f7f1..22f3cde885d9 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExternalTableDefinition.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExternalTableDefinition.java @@ -112,7 +112,20 @@ private Builder(Table tablePb) { * * @see Quota */ + @Deprecated public Builder sourceUris(List sourceUris) { + return setSourceUris(sourceUris); + } + + /** + * Sets the fully-qualified URIs that point to your data in Google Cloud Storage (e.g. + * gs://bucket/path). Each URI can contain one '*' wildcard character that must come after the + * bucket's name. Size limits related to load jobs apply to external data sources, plus an + * additional limit of 10 GB maximum size across all URIs. + * + * @see Quota + */ + public Builder setSourceUris(List sourceUris) { this.sourceUris = ImmutableList.copyOf(checkNotNull(sourceUris)); return this; } @@ -124,7 +137,19 @@ public Builder sourceUris(List sourceUris) { * * Source Format */ + @Deprecated public Builder formatOptions(FormatOptions formatOptions) { + return setFormatOptions(formatOptions); + } + + /** + * Sets the source format, and possibly some parsing options, of the external data. Supported + * formats are {@code CSV} and {@code NEWLINE_DELIMITED_JSON}. + * + * + * Source Format + */ + public Builder setFormatOptions(FormatOptions formatOptions) { this.formatOptions = checkNotNull(formatOptions); return this; } @@ -134,7 +159,17 @@ public Builder formatOptions(FormatOptions formatOptions) { * number of bad records exceeds this value, an invalid error is returned in the job result. * The default value is 0, which requires that all records are valid. */ + @Deprecated public Builder maxBadRecords(Integer maxBadRecords) { + return setMaxBadRecords(maxBadRecords); + } + + /** + * Sets the maximum number of bad records that BigQuery can ignore when reading data. If the + * number of bad records exceeds this value, an invalid error is returned in the job result. + * The default value is 0, which requires that all records are valid. + */ + public Builder setMaxBadRecords(Integer maxBadRecords) { this.maxBadRecords = maxBadRecords; return this; } @@ -149,7 +184,22 @@ public Builder maxBadRecords(Integer maxBadRecords) { * @see * Ignore Unknown Values */ + @Deprecated public Builder ignoreUnknownValues(Boolean ignoreUnknownValues) { + return setIgnoreUnknownValues(ignoreUnknownValues); + } + + /** + * Sets whether BigQuery should allow extra values that are not represented in the table schema. + * If true, the extra values are ignored. If false, records with extra columns are treated as + * bad records, and if there are too many bad records, an invalid error is returned in the job + * result. The default value is false. The value set with {@link #formatOptions(FormatOptions)} + * property determines what BigQuery treats as an extra value. + * + * @see + * Ignore Unknown Values + */ + public Builder setIgnoreUnknownValues(Boolean ignoreUnknownValues) { this.ignoreUnknownValues = ignoreUnknownValues; return this; } @@ -160,7 +210,18 @@ public Builder ignoreUnknownValues(Boolean ignoreUnknownValues) { * @see * Compression */ + @Deprecated public Builder compression(String compression) { + return setCompression(compression); + } + + /** + * Sets compression type of the data source. By default no compression is assumed. + * + * @see + * Compression + */ + public Builder setCompression(String compression) { this.compression = compression; return this; } @@ -189,7 +250,18 @@ private ExternalTableDefinition(Builder builder) { * @see * Compression */ + @Deprecated public String compression() { + return getCompression(); + } + + /** + * Returns the compression type of the data source. + * + * @see + * Compression + */ + public String getCompression() { return compression; } @@ -211,7 +283,16 @@ public Boolean ignoreUnknownValues() { * Returns the maximum number of bad records that BigQuery can ignore when reading data. If the * number of bad records exceeds this value, an invalid error is returned in the job result. */ + @Deprecated public Integer maxBadRecords() { + return getMaxBadRecords(); + } + + /** + * Returns the maximum number of bad records that BigQuery can ignore when reading data. If the + * number of bad records exceeds this value, an invalid error is returned in the job result. + */ + public Integer getMaxBadRecords() { return maxBadRecords; } @@ -223,7 +304,20 @@ public Integer maxBadRecords() { * * @see Quota */ + @Deprecated public List sourceUris() { + return getSourceUris(); + } + + /** + * Returns the fully-qualified URIs that point to your data in Google Cloud Storage. Each URI can + * contain one '*' wildcard character that must come after the bucket's name. Size limits + * related to load jobs apply to external data sources, plus an additional limit of 10 GB + * maximum size across all URIs. + * + * @see Quota + */ + public List getSourceUris() { return sourceUris; } @@ -232,7 +326,17 @@ public List sourceUris() { * formats are {@code CSV} and {@code NEWLINE_DELIMITED_JSON}. */ @SuppressWarnings("unchecked") + @Deprecated public F formatOptions() { + return getFormatOptions(); + } + + /** + * Returns the source format, and possibly some parsing options, of the external data. Supported + * formats are {@code CSV} and {@code NEWLINE_DELIMITED_JSON}. + */ + @SuppressWarnings("unchecked") + public F getFormatOptions() { return (F) formatOptions; } @@ -287,16 +391,16 @@ com.google.api.services.bigquery.model.ExternalDataConfiguration toExternalDataC if (maxBadRecords != null) { externalConfigurationPb.setMaxBadRecords(maxBadRecords); } - if (schema() != null) { - externalConfigurationPb.setSchema(schema().toPb()); + if (getSchema() != null) { + externalConfigurationPb.setSchema(getSchema().toPb()); } if (formatOptions != null) { - externalConfigurationPb.setSourceFormat(formatOptions.type()); + externalConfigurationPb.setSourceFormat(formatOptions.getType()); } if (sourceUris != null) { externalConfigurationPb.setSourceUris(sourceUris); } - if (formatOptions != null && FormatOptions.CSV.equals(formatOptions.type())) { + if (formatOptions != null && FormatOptions.CSV.equals(formatOptions.getType())) { externalConfigurationPb.setCsvOptions(((CsvOptions) formatOptions).toPb()); } return externalConfigurationPb; @@ -317,8 +421,28 @@ com.google.api.services.bigquery.model.ExternalDataConfiguration toExternalDataC * @see * Source Format */ + @Deprecated public static Builder builder(List sourceUris, Schema schema, FormatOptions format) { - return new Builder().sourceUris(sourceUris).schema(schema).formatOptions(format); + return newBuilder(sourceUris, schema, format); + } + + /** + * Creates a builder for an ExternalTableDefinition object. + * + * @param sourceUris the fully-qualified URIs that point to your data in Google Cloud Storage. + * Each URI can contain one '*' wildcard character that must come after the bucket's name. + * Size limits related to load jobs apply to external data sources, plus an additional limit + * of 10 GB maximum size across all URIs. + * @param schema the schema for the external data + * @param format the source format of the external data + * @return a builder for an ExternalTableDefinition object given source URIs, schema and format + * + * @see Quota + * @see + * Source Format + */ + public static Builder newBuilder(List sourceUris, Schema schema, FormatOptions format) { + return new Builder().setSourceUris(sourceUris).setSchema(schema).setFormatOptions(format); } /** @@ -335,8 +459,27 @@ public static Builder builder(List sourceUris, Schema schema, FormatOpti * @see * Source Format */ + @Deprecated public static Builder builder(String sourceUri, Schema schema, FormatOptions format) { - return builder(ImmutableList.of(sourceUri), schema, format); + return newBuilder(sourceUri, schema, format); + } + + /** + * Creates a builder for an ExternalTableDefinition object. + * + * @param sourceUri a fully-qualified URI that points to your data in Google Cloud Storage. The + * URI can contain one '*' wildcard character that must come after the bucket's name. Size + * limits related to load jobs apply to external data sources. + * @param schema the schema for the external data + * @param format the source format of the external data + * @return a builder for an ExternalTableDefinition object given source URI, schema and format + * + * @see Quota + * @see + * Source Format + */ + public static Builder newBuilder(String sourceUri, Schema schema, FormatOptions format) { + return newBuilder(ImmutableList.of(sourceUri), schema, format); } /** @@ -356,7 +499,7 @@ public static Builder builder(String sourceUri, Schema schema, FormatOptions for */ public static ExternalTableDefinition of(List sourceUris, Schema schema, FormatOptions format) { - return builder(sourceUris, schema, format).build(); + return newBuilder(sourceUris, schema, format).build(); } /** @@ -374,7 +517,7 @@ public static ExternalTableDefinition of(List sourceUris, Schema schema, * Source Format */ public static ExternalTableDefinition of(String sourceUri, Schema schema, FormatOptions format) { - return builder(sourceUri, schema, format).build(); + return newBuilder(sourceUri, schema, format).build(); } @SuppressWarnings("unchecked") @@ -386,25 +529,25 @@ static ExternalTableDefinition fromExternalDataConfiguration( ExternalDataConfiguration externalDataConfiguration) { Builder builder = new Builder(); if (externalDataConfiguration.getSourceUris() != null) { - builder.sourceUris(externalDataConfiguration.getSourceUris()); + builder.setSourceUris(externalDataConfiguration.getSourceUris()); } if (externalDataConfiguration.getSchema() != null) { - builder.schema(Schema.fromPb(externalDataConfiguration.getSchema())); + builder.setSchema(Schema.fromPb(externalDataConfiguration.getSchema())); } if (externalDataConfiguration.getSourceFormat() != null) { - builder.formatOptions(FormatOptions.of(externalDataConfiguration.getSourceFormat())); + builder.setFormatOptions(FormatOptions.of(externalDataConfiguration.getSourceFormat())); } if (externalDataConfiguration.getCompression() != null) { - builder.compression(externalDataConfiguration.getCompression()); + builder.setCompression(externalDataConfiguration.getCompression()); } if (externalDataConfiguration.getIgnoreUnknownValues() != null) { - builder.ignoreUnknownValues(externalDataConfiguration.getIgnoreUnknownValues()); + builder.setIgnoreUnknownValues(externalDataConfiguration.getIgnoreUnknownValues()); } if (externalDataConfiguration.getCsvOptions() != null) { - builder.formatOptions(CsvOptions.fromPb(externalDataConfiguration.getCsvOptions())); + builder.setFormatOptions(CsvOptions.fromPb(externalDataConfiguration.getCsvOptions())); } if (externalDataConfiguration.getMaxBadRecords() != null) { - builder.maxBadRecords(externalDataConfiguration.getMaxBadRecords()); + builder.setMaxBadRecords(externalDataConfiguration.getMaxBadRecords()); } return builder.build(); } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExtractJobConfiguration.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExtractJobConfiguration.java index 3dccddcae764..a77c512a7681 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExtractJobConfiguration.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ExtractJobConfiguration.java @@ -79,7 +79,15 @@ private Builder(com.google.api.services.bigquery.model.JobConfiguration configur /** * Sets the table to export. */ + @Deprecated public Builder sourceTable(TableId sourceTable) { + return setSourceTable(sourceTable); + } + + /** + * Sets the table to export. + */ + public Builder setSourceTable(TableId sourceTable) { this.sourceTable = sourceTable; return this; } @@ -88,7 +96,16 @@ public Builder sourceTable(TableId sourceTable) { * Sets the list of fully-qualified Google Cloud Storage URIs (e.g. gs://bucket/path) where the * extracted table should be written. */ + @Deprecated public Builder destinationUris(List destinationUris) { + return setDestinationUris(destinationUris); + } + + /** + * Sets the list of fully-qualified Google Cloud Storage URIs (e.g. gs://bucket/path) where the + * extracted table should be written. + */ + public Builder setDestinationUris(List destinationUris) { this.destinationUris = destinationUris != null ? ImmutableList.copyOf(destinationUris) : null; return this; } @@ -96,7 +113,15 @@ public Builder destinationUris(List destinationUris) { /** * Sets whether to print out a header row in the results. By default an header is printed. */ + @Deprecated public Builder printHeader(Boolean printHeader) { + return setPrintHeader(printHeader); + } + + /** + * Sets whether to print out a header row in the results. By default an header is printed. + */ + public Builder setPrintHeader(Boolean printHeader) { this.printHeader = printHeader; return this; } @@ -104,7 +129,15 @@ public Builder printHeader(Boolean printHeader) { /** * Sets the delimiter to use between fields in the exported data. By default "," is used. */ + @Deprecated public Builder fieldDelimiter(String fieldDelimiter) { + return setFieldDelimiter(fieldDelimiter); + } + + /** + * Sets the delimiter to use between fields in the exported data. By default "," is used. + */ + public Builder setFieldDelimiter(String fieldDelimiter) { this.fieldDelimiter = fieldDelimiter; return this; } @@ -115,7 +148,18 @@ public Builder fieldDelimiter(String fieldDelimiter) { * * Destination Format */ + @Deprecated public Builder format(String format) { + return setFormat(format); + } + + /** + * Sets the exported file format. If not set table is exported in CSV format. + * + * + * Destination Format + */ + public Builder setFormat(String format) { this.format = format; return this; } @@ -127,7 +171,19 @@ public Builder format(String format) { * * Compression */ + @Deprecated public Builder compression(String compression) { + return setCompression(compression); + } + + /** + * Sets the compression value to use for exported files. If not set exported files are not + * compressed. + * + * + * Compression + */ + public Builder setCompression(String compression) { this.compression = compression; return this; } @@ -150,7 +206,15 @@ private ExtractJobConfiguration(Builder builder) { /** * Returns the table to export. */ + @Deprecated public TableId sourceTable() { + return getSourceTable(); + } + + /** + * Returns the table to export. + */ + public TableId getSourceTable() { return sourceTable; } @@ -161,7 +225,19 @@ public TableId sourceTable() { * @see * Exporting Data Into One or More Files */ + @Deprecated public List destinationUris() { + return getDestinationUris(); + } + + /** + * Returns the list of fully-qualified Google Cloud Storage URIs where the extracted table should + * be written. + * + * @see + * Exporting Data Into One or More Files + */ + public List getDestinationUris() { return destinationUris; } @@ -175,21 +251,45 @@ public Boolean printHeader() { /** * Returns the delimiter used between fields in the exported data. */ + @Deprecated public String fieldDelimiter() { + return getFieldDelimiter(); + } + + /** + * Returns the delimiter used between fields in the exported data. + */ + public String getFieldDelimiter() { return fieldDelimiter; } /** * Returns the exported files format. */ + @Deprecated public String format() { + return getFormat(); + } + + /** + * Returns the exported files format. + */ + public String getFormat() { return format; } /** * Returns the compression value of exported files. */ + @Deprecated public String compression() { + return getCompression(); + } + + /** + * Returns the compression value of exported files. + */ + public String getCompression() { return compression; } @@ -224,7 +324,7 @@ public int hashCode() { @Override ExtractJobConfiguration setProjectId(String projectId) { - return toBuilder().sourceTable(sourceTable().setProjectId(projectId)).build(); + return toBuilder().setSourceTable(getSourceTable().setProjectId(projectId)).build(); } @Override @@ -244,30 +344,48 @@ com.google.api.services.bigquery.model.JobConfiguration toPb() { * Creates a builder for a BigQuery Extract Job configuration given source table and destination * URI. */ + @Deprecated public static Builder builder(TableId sourceTable, String destinationUri) { - return builder(sourceTable, ImmutableList.of(checkNotNull(destinationUri))); + return newBuilder(sourceTable, destinationUri); + } + + /** + * Creates a builder for a BigQuery Extract Job configuration given source table and destination + * URI. + */ + public static Builder newBuilder(TableId sourceTable, String destinationUri) { + return newBuilder(sourceTable, ImmutableList.of(checkNotNull(destinationUri))); } /** * Creates a builder for a BigQuery Extract Job configuration given source table and destination * URIs. */ + @Deprecated public static Builder builder(TableId sourceTable, List destinationUris) { - return new Builder().sourceTable(sourceTable).destinationUris(destinationUris); + return newBuilder(sourceTable, destinationUris); + } + + /** + * Creates a builder for a BigQuery Extract Job configuration given source table and destination + * URIs. + */ + public static Builder newBuilder(TableId sourceTable, List destinationUris) { + return new Builder().setSourceTable(sourceTable).setDestinationUris(destinationUris); } /** * Returns a BigQuery Extract Job configuration for the given source table and destination URI. */ public static ExtractJobConfiguration of(TableId sourceTable, String destinationUri) { - return builder(sourceTable, destinationUri).build(); + return newBuilder(sourceTable, destinationUri).build(); } /** * Returns a BigQuery Extract Job configuration for the given source table and destination URIs. */ public static ExtractJobConfiguration of(TableId sourceTable, List destinationUris) { - return builder(sourceTable, destinationUris).build(); + return newBuilder(sourceTable, destinationUris).build(); } /** @@ -276,7 +394,7 @@ public static ExtractJobConfiguration of(TableId sourceTable, List desti */ public static ExtractJobConfiguration of(TableId sourceTable, String destinationUri, String format) { - return builder(sourceTable, destinationUri).format(format).build(); + return newBuilder(sourceTable, destinationUri).setFormat(format).build(); } /** @@ -285,7 +403,7 @@ public static ExtractJobConfiguration of(TableId sourceTable, String destination */ public static ExtractJobConfiguration of(TableId sourceTable, List destinationUris, String format) { - return builder(sourceTable, destinationUris).format(format).build(); + return newBuilder(sourceTable, destinationUris).setFormat(format).build(); } @SuppressWarnings("unchecked") diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Field.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Field.java index 874049aa033a..1549f7bc9be4 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Field.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Field.java @@ -96,7 +96,18 @@ private Type(Value value, List fields) { * @see * Data Types */ + @Deprecated public Value value() { + return getValue(); + } + + /** + * Returns the value identifier. + * + * @see + * Data Types + */ + public Value getValue() { return value; } @@ -104,7 +115,16 @@ public Value value() { * Returns the list of sub-fields if {@link #value()} is set to {@link Value#RECORD}. Returns * {@code null} otherwise. */ + @Deprecated public List fields() { + return getFields(); + } + + /** + * Returns the list of sub-fields if {@link #value()} is set to {@link Value#RECORD}. Returns + * {@code null} otherwise. + */ + public List getFields() { return fields; } @@ -218,7 +238,17 @@ private Builder(Field field) { * underscores (_), and must start with a letter or underscore. The maximum length is 128 * characters. */ + @Deprecated public Builder name(String name) { + return setName(name); + } + + /** + * Sets the field name. The name must contain only letters (a-z, A-Z), numbers (0-9), or + * underscores (_), and must start with a letter or underscore. The maximum length is 128 + * characters. + */ + public Builder setName(String name) { this.name = checkNotNull(name); return this; } @@ -229,7 +259,18 @@ public Builder name(String name) { * @see * Data Types */ + @Deprecated public Builder type(Type type) { + return setType(type); + } + + /** + * Sets the value of the field. + * + * @see + * Data Types + */ + public Builder setType(Type type) { this.type = checkNotNull(type); return this; } @@ -237,7 +278,15 @@ public Builder type(Type type) { /** * Sets the mode of the field. When not specified {@link Mode#NULLABLE} is used. */ + @Deprecated public Builder mode(Mode mode) { + return setMode(mode); + } + + /** + * Sets the mode of the field. When not specified {@link Mode#NULLABLE} is used. + */ + public Builder setMode(Mode mode) { this.mode = mode != null ? mode.name() : Data.nullOf(String.class); return this; } @@ -245,7 +294,15 @@ public Builder mode(Mode mode) { /** * Sets the field description. The maximum length is 16K characters. */ + @Deprecated public Builder description(String description) { + return setDescription(description); + } + + /** + * Sets the field description. The maximum length is 16K characters. + */ + public Builder setDescription(String description) { this.description = firstNonNull(description, Data.nullOf(String.class)); return this; } @@ -268,7 +325,15 @@ private Field(Builder builder) { /** * Returns the field name. */ + @Deprecated public String name() { + return getName(); + } + + /** + * Returns the field name. + */ + public String getName() { return name; } @@ -278,21 +343,48 @@ public String name() { * @see * Data Types */ + @Deprecated public Type type() { + return getType(); + } + + /** + * Returns the field value. + * + * @see + * Data Types + */ + public Type getType() { return type; } /** * Returns the field mode. By default {@link Mode#NULLABLE} is used. */ + @Deprecated public Mode mode() { + return getMode(); + } + + /** + * Returns the field mode. By default {@link Mode#NULLABLE} is used. + */ + public Mode getMode() { return mode != null ? Mode.valueOf(mode) : null; } /** * Returns the field description. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns the field description. + */ + public String getDescription() { return Data.isNull(description) ? null : description; } @@ -300,8 +392,17 @@ public String description() { * Returns the list of sub-fields if {@link #type()} is a {@link Type.Value#RECORD}. Returns * {@code null} otherwise. */ + @Deprecated public List fields() { - return type.fields(); + return getFields(); + } + + /** + * Returns the list of sub-fields if {@link #type()} is a {@link Type.Value#RECORD}. Returns + * {@code null} otherwise. + */ + public List getFields() { + return type.getFields(); } /** @@ -334,15 +435,15 @@ public boolean equals(Object obj) { TableFieldSchema toPb() { TableFieldSchema fieldSchemaPb = new TableFieldSchema(); fieldSchemaPb.setName(name); - fieldSchemaPb.setType(type.value().name()); + fieldSchemaPb.setType(type.getValue().name()); if (mode != null) { fieldSchemaPb.setMode(mode); } if (description != null) { fieldSchemaPb.setDescription(description); } - if (fields() != null) { - List fieldsPb = Lists.transform(fields(), TO_PB_FUNCTION); + if (getFields() != null) { + List fieldsPb = Lists.transform(getFields(), TO_PB_FUNCTION); fieldSchemaPb.setFields(fieldsPb); } return fieldSchemaPb; @@ -352,30 +453,39 @@ TableFieldSchema toPb() { * Returns a Field object with given name and value. */ public static Field of(String name, Type type) { - return builder(name, type).build(); + return newBuilder(name, type).build(); } /** * Returns a builder for a Field object with given name and value. */ + @Deprecated public static Builder builder(String name, Type type) { - return new Builder().name(name).type(type); + return newBuilder(name, type); + } + + /** + * Returns a builder for a Field object with given name and value. + */ + public static Builder newBuilder(String name, Type type) { + return new Builder().setName(name).setType(type); } static Field fromPb(TableFieldSchema fieldSchemaPb) { Builder fieldBuilder = new Builder(); - fieldBuilder.name(fieldSchemaPb.getName()); + fieldBuilder.setName(fieldSchemaPb.getName()); Type.Value enumValue = Type.Value.valueOf(fieldSchemaPb.getType()); if (fieldSchemaPb.getMode() != null) { - fieldBuilder.mode(Mode.valueOf(fieldSchemaPb.getMode())); + fieldBuilder.setMode(Mode.valueOf(fieldSchemaPb.getMode())); } if (fieldSchemaPb.getDescription() != null) { - fieldBuilder.description(fieldSchemaPb.getDescription()); + fieldBuilder.setDescription(fieldSchemaPb.getDescription()); } if (fieldSchemaPb.getFields() != null) { - fieldBuilder.type(Type.record(Lists.transform(fieldSchemaPb.getFields(), FROM_PB_FUNCTION))); + fieldBuilder.setType( + Type.record(Lists.transform(fieldSchemaPb.getFields(), FROM_PB_FUNCTION))); } else { - fieldBuilder.type(new Type(enumValue)); + fieldBuilder.setType(new Type(enumValue)); } return fieldBuilder.build(); } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/FieldValue.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/FieldValue.java index 1eb3115a3644..1e5c00b0b753 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/FieldValue.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/FieldValue.java @@ -88,7 +88,23 @@ public enum Attribute { * {@link Attribute#RECORD} if the corresponding field is a * {@link Field.Type#record(Field...)} type. */ + @Deprecated public Attribute attribute() { + return getAttribute(); + } + + /** + * Returns the attribute of this Field Value. + * + * @return {@link Attribute#PRIMITIVE} if the field is a primitive type + * ({@link Field.Type#bytes()}, {@link Field.Type#bool()}, {@link Field.Type#string()}, + * {@link Field.Type#floatingPoint()}, {@link Field.Type#integer()}, + * {@link Field.Type#timestamp()}) or is {@code null}. Returns {@link Attribute#REPEATED} if + * the corresponding field has ({@link Field.Mode#REPEATED}) mode. Returns + * {@link Attribute#RECORD} if the corresponding field is a + * {@link Field.Type#record(Field...)} type. + */ + public Attribute getAttribute() { return attribute; } @@ -103,7 +119,16 @@ public boolean isNull() { * Returns this field's value as an {@link Object}. If {@link #isNull()} is {@code true} this * method returns {@code null}. */ + @Deprecated public Object value() { + return getValue(); + } + + /** + * Returns this field's value as an {@link Object}. If {@link #isNull()} is {@code true} this + * method returns {@code null}. + */ + public Object getValue() { return value; } @@ -117,7 +142,22 @@ public Object value() { * @throws NullPointerException if {@link #isNull()} returns {@code true} */ @SuppressWarnings("unchecked") + @Deprecated public String stringValue() { + return getStringValue(); + } + + /** + * Returns this field's value as a {@link String}. This method should only be used if the + * corresponding field has primitive type ({@link Field.Type#bytes()}, {@link Field.Type#bool()}, + * {@link Field.Type#string()}, {@link Field.Type#floatingPoint()}, {@link Field.Type#integer()}, + * {@link Field.Type#timestamp()}). + * + * @throws ClassCastException if the field is not a primitive type + * @throws NullPointerException if {@link #isNull()} returns {@code true} + */ + @SuppressWarnings("unchecked") + public String getStringValue() { checkNotNull(value); return (String) value; } @@ -130,9 +170,22 @@ public String stringValue() { * @throws NullPointerException if {@link #isNull()} returns {@code true} * @throws IllegalStateException if the field value is not encoded in base64 */ + @Deprecated public byte[] bytesValue() { + return getBytesValue(); + } + + /** + * Returns this field's value as a byte array. This method should only be used if the + * corresponding field has primitive type ({@link Field.Type#bytes()}. + * + * @throws ClassCastException if the field is not a primitive type + * @throws NullPointerException if {@link #isNull()} returns {@code true} + * @throws IllegalStateException if the field value is not encoded in base64 + */ + public byte[] getBytesValue() { try { - return BaseEncoding.base64().decode(stringValue()); + return BaseEncoding.base64().decode(getStringValue()); } catch (IllegalArgumentException ex) { throw new IllegalStateException(ex); } @@ -147,8 +200,22 @@ public byte[] bytesValue() { * @throws NullPointerException if {@link #isNull()} returns {@code true} */ @SuppressWarnings("unchecked") + @Deprecated public long longValue() { - return Long.parseLong(stringValue()); + return getLongValue(); + } + + /** + * Returns this field's value as a {@code long}. This method should only be used if the + * corresponding field has {@link Field.Type#integer()} type. + * + * @throws ClassCastException if the field is not a primitive type + * @throws NumberFormatException if the field's value could not be converted to {@link Integer} + * @throws NullPointerException if {@link #isNull()} returns {@code true} + */ + @SuppressWarnings("unchecked") + public long getLongValue() { + return Long.parseLong(getStringValue()); } /** @@ -160,8 +227,22 @@ public long longValue() { * @throws NullPointerException if {@link #isNull()} returns {@code true} */ @SuppressWarnings("unchecked") + @Deprecated public double doubleValue() { - return Double.parseDouble(stringValue()); + return getDoubleValue(); + } + + /** + * Returns this field's value as a {@link Double}. This method should only be used if the + * corresponding field has {@link Field.Type#floatingPoint()} type. + * + * @throws ClassCastException if the field is not a primitive type + * @throws NumberFormatException if the field's value could not be converted to {@link Double} + * @throws NullPointerException if {@link #isNull()} returns {@code true} + */ + @SuppressWarnings("unchecked") + public double getDoubleValue() { + return Double.parseDouble(getStringValue()); } /** @@ -173,8 +254,22 @@ public double doubleValue() { * @throws NullPointerException if {@link #isNull()} returns {@code true} */ @SuppressWarnings("unchecked") + @Deprecated public boolean booleanValue() { - String stringValue = stringValue(); + return getBooleanValue(); + } + + /** + * Returns this field's value as a {@link Boolean}. This method should only be used if the + * corresponding field has {@link Field.Type#bool()} type. + * + * @throws ClassCastException if the field is not a primitive type + * @throws IllegalStateException if the field's value could not be converted to {@link Boolean} + * @throws NullPointerException if {@link #isNull()} returns {@code true} + */ + @SuppressWarnings("unchecked") + public boolean getBooleanValue() { + String stringValue = getStringValue(); checkState(stringValue.equalsIgnoreCase("true") || stringValue.equalsIgnoreCase("false"), "Field value is not of boolean type"); return Boolean.parseBoolean(stringValue); @@ -190,10 +285,25 @@ public boolean booleanValue() { * @throws NullPointerException if {@link #isNull()} returns {@code true} */ @SuppressWarnings("unchecked") + @Deprecated public long timestampValue() { + return getTimestampValue(); + } + + /** + * Returns this field's value as a {@code long}, representing a timestamp in microseconds since + * epoch (UNIX time). This method should only be used if the corresponding field has + * {@link Field.Type#timestamp()} type. + * + * @throws ClassCastException if the field is not a primitive type + * @throws NumberFormatException if the field's value could not be converted to {@link Long} + * @throws NullPointerException if {@link #isNull()} returns {@code true} + */ + @SuppressWarnings("unchecked") + public long getTimestampValue() { // timestamps are encoded in the format 1408452095.22 where the integer part is seconds since // epoch (e.g. 1408452095.22 == 2014-08-19 07:41:35.220 -05:00) - return new Double(((Double.valueOf(stringValue())) * MICROSECONDS)).longValue(); + return new Double(Double.valueOf(getStringValue()) * MICROSECONDS).longValue(); } /** @@ -205,7 +315,21 @@ public long timestampValue() { * @throws NullPointerException if {@link #isNull()} returns {@code true} */ @SuppressWarnings("unchecked") + @Deprecated public List repeatedValue() { + return getRepeatedValue(); + } + + /** + * Returns this field's value as a list of {@link FieldValue}. This method should only be used if + * the corresponding field has {@link Field.Mode#REPEATED} mode (i.e. {@link #attribute()} is + * {@link Attribute#REPEATED}). + * + * @throws ClassCastException if the field has not {@link Field.Mode#REPEATED} mode + * @throws NullPointerException if {@link #isNull()} returns {@code true} + */ + @SuppressWarnings("unchecked") + public List getRepeatedValue() { checkNotNull(value); return (List) value; } @@ -219,7 +343,21 @@ public List repeatedValue() { * @throws NullPointerException if {@link #isNull()} returns {@code true} */ @SuppressWarnings("unchecked") + @Deprecated public List recordValue() { + return getRecordValue(); + } + + /** + * Returns this field's value as a list of {@link FieldValue}. This method should only be used if + * the corresponding field has {@link Field.Type#record(Field...)} type (i.e. {@link #attribute()} + * is {@link Attribute#RECORD}). + * + * @throws ClassCastException if the field is not a {@link Field.Type#record(Field...)} type + * @throws NullPointerException if {@link #isNull()} returns {@code true} + */ + @SuppressWarnings("unchecked") + public List getRecordValue() { checkNotNull(value); return (List) value; } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/FormatOptions.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/FormatOptions.java index 4267d5384147..ef451e844a3e 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/FormatOptions.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/FormatOptions.java @@ -43,7 +43,15 @@ public class FormatOptions implements Serializable { /** * Returns the external data format, as a string. */ + @Deprecated public String type() { + return getType(); + } + + /** + * Returns the external data format, as a string. + */ + public String getType() { return type; } @@ -62,14 +70,14 @@ public boolean equals(Object obj) { return obj == this || obj != null && obj.getClass().equals(FormatOptions.class) - && Objects.equals(type, ((FormatOptions) obj).type()); + && Objects.equals(type, ((FormatOptions) obj).getType()); } /** * Default options for CSV format. */ public static CsvOptions csv() { - return CsvOptions.builder().build(); + return CsvOptions.newBuilder().build(); } /** diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/InsertAllRequest.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/InsertAllRequest.java index 1ff4e9d788c7..0c46fd09bcf7 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/InsertAllRequest.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/InsertAllRequest.java @@ -84,14 +84,30 @@ public static class RowToInsert implements Serializable { /** * Returns the id associated with the row. Returns {@code null} if not set. */ + @Deprecated public String id() { + return getId(); + } + + /** + * Returns the id associated with the row. Returns {@code null} if not set. + */ + public String getId() { return id; } /** * Returns the actual content of the row, as a map. */ + @Deprecated public Map content() { + return getContent(); + } + + /** + * Returns the actual content of the row, as a map. + */ + public Map getContent() { return content; } @@ -153,7 +169,15 @@ private Builder() {} /** * Sets the destination table for rows insert request. */ + @Deprecated public Builder table(TableId table) { + return setTable(table); + } + + /** + * Sets the destination table for rows insert request. + */ + public Builder setTable(TableId table) { this.table = checkNotNull(table); return this; } @@ -161,7 +185,15 @@ public Builder table(TableId table) { /** * Sets the rows to insert as a list of {@link RowToInsert} objects. */ + @Deprecated public Builder rows(Iterable rows) { + return setRows(rows); + } + + /** + * Sets the rows to insert as a list of {@link RowToInsert} objects. + */ + public Builder setRows(Iterable rows) { this.rows = Lists.newLinkedList(checkNotNull(rows)); return this; } @@ -228,7 +260,16 @@ public Builder addRow(Map content) { * Sets whether to insert all valid rows of a request, even if invalid rows exist. If not set * the entire insert request will fail if it contains an invalid row. */ + @Deprecated public Builder skipInvalidRows(boolean skipInvalidRows) { + return setSkipInvalidRows(skipInvalidRows); + } + + /** + * Sets whether to insert all valid rows of a request, even if invalid rows exist. If not set + * the entire insert request will fail if it contains an invalid row. + */ + public Builder setSkipInvalidRows(boolean skipInvalidRows) { this.skipInvalidRows = skipInvalidRows; return this; } @@ -237,7 +278,16 @@ public Builder skipInvalidRows(boolean skipInvalidRows) { * Sets whether to accept rows that contain values that do not match the schema. The unknown * values are ignored. If not set, rows with unknown values are considered to be invalid. */ + @Deprecated public Builder ignoreUnknownValues(boolean ignoreUnknownValues) { + return setIgnoreUnknownValues(ignoreUnknownValues); + } + + /** + * Sets whether to accept rows that contain values that do not match the schema. The unknown + * values are ignored. If not set, rows with unknown values are considered to be invalid. + */ + public Builder setIgnoreUnknownValues(boolean ignoreUnknownValues) { this.ignoreUnknownValues = ignoreUnknownValues; return this; } @@ -260,11 +310,37 @@ public Builder ignoreUnknownValues(boolean ignoreUnknownValues) { * href="https://cloud.google.com/bigquery/streaming-data-into-bigquery#template-tables"> * Template Tables */ + @Deprecated public Builder templateSuffix(String templateSuffix) { + return setTemplateSuffix(templateSuffix); + } + + /** + * If specified, the destination table is treated as a base template. Rows are inserted into an + * instance table named "{destination}{templateSuffix}". BigQuery will manage the creation of + * the instance table, using the schema of the base template table. Table creation might take + * some time. To obtain table's information after {@link BigQuery#insertAll(InsertAllRequest)} + * is called use: + *
 {@code
+     * String suffixTableId = ...;
+     * TableInfo suffixTable = bigquery.getTable(DATASET, suffixTableId);
+     * while (suffixTable == null) {
+     *   Thread.sleep(1000L);
+     *   suffixTable = bigquery.getTable(DATASET, suffixTableId);
+     * }}
+ * + * @see + * Template Tables + */ + public Builder setTemplateSuffix(String templateSuffix) { this.templateSuffix = templateSuffix; return this; } + /** + * Creates an {@code InsertAllRequest} object. + */ public InsertAllRequest build() { return new InsertAllRequest(this); } @@ -281,14 +357,30 @@ private InsertAllRequest(Builder builder) { /** * Returns the destination table for rows insert request. */ + @Deprecated public TableId table() { + return getTable(); + } + + /** + * Returns the destination table for rows insert request. + */ + public TableId getTable() { return table; } /** * Returns the rows to be inserted. */ + @Deprecated public List rows() { + return getRows(); + } + + /** + * Returns the rows to be inserted. + */ + public List getRows() { return rows; } @@ -326,112 +418,205 @@ public Boolean skipInvalidRows() { * href="https://cloud.google.com/bigquery/streaming-data-into-bigquery#template-tables"> * Template Tables */ + @Deprecated public String templateSuffix() { + return getTemplateSuffix(); + } + + /** + * If specified, the destination table is treated as a base template. Rows are inserted into an + * instance table named "{destination}{templateSuffix}". BigQuery will manage the creation of the + * instance table, using the schema of the base template table. Table creation might take some + * time. To obtain table's information after {@link BigQuery#insertAll(InsertAllRequest)} is + * called use: + *
 {@code
+   * String suffixTableId = ...;
+   * TableInfo suffixTable = bigquery.getTable(DATASET, suffixTableId);
+   * while (suffixTable == null) {
+   *   Thread.sleep(1000L);
+   *   suffixTable = bigquery.getTable(DATASET, suffixTableId);
+   * }}
+ * + * @see + * Template Tables + */ + public String getTemplateSuffix() { return templateSuffix; } /** * Returns a builder for an {@code InsertAllRequest} object given the destination table. */ + @Deprecated public static Builder builder(TableId table) { - return new Builder().table(table); + return newBuilder(table); + } + + /** + * Returns a builder for an {@code InsertAllRequest} object given the destination table. + */ + public static Builder newBuilder(TableId table) { + return new Builder().setTable(table); } /** * Returns a builder for an {@code InsertAllRequest} object given the destination table and the * rows to insert. */ + @Deprecated public static Builder builder(TableId table, Iterable rows) { - return builder(table).rows(rows); + return newBuilder(table, rows); + } + + /** + * Returns a builder for an {@code InsertAllRequest} object given the destination table and the + * rows to insert. + */ + public static Builder newBuilder(TableId table, Iterable rows) { + return newBuilder(table).setRows(rows); } /** * Returns a builder for an {@code InsertAllRequest} object given the destination table and the * rows to insert. */ + @Deprecated public static Builder builder(TableId table, RowToInsert... rows) { - return builder(table, ImmutableList.copyOf(rows)); + return newBuilder(table, rows); + } + + /** + * Returns a builder for an {@code InsertAllRequest} object given the destination table and the + * rows to insert. + */ + public static Builder newBuilder(TableId table, RowToInsert... rows) { + return newBuilder(table, ImmutableList.copyOf(rows)); } /** * Returns a builder for an {@code InsertAllRequest} object given the destination table. */ + @Deprecated public static Builder builder(String datasetId, String tableId) { - return new Builder().table(TableId.of(datasetId, tableId)); + return newBuilder(datasetId, tableId); + } + + /** + * Returns a builder for an {@code InsertAllRequest} object given the destination table. + */ + public static Builder newBuilder(String datasetId, String tableId) { + return new Builder().setTable(TableId.of(datasetId, tableId)); } /** * Returns a builder for an {@code InsertAllRequest} object given the destination table and the * rows to insert. */ + @Deprecated public static Builder builder(String datasetId, String tableId, Iterable rows) { - return builder(TableId.of(datasetId, tableId), rows); + return newBuilder(datasetId, tableId, rows); } /** * Returns a builder for an {@code InsertAllRequest} object given the destination table and the * rows to insert. */ + public static Builder newBuilder(String datasetId, String tableId, Iterable rows) { + return newBuilder(TableId.of(datasetId, tableId), rows); + } + + /** + * Returns a builder for an {@code InsertAllRequest} object given the destination table and the + * rows to insert. + */ + @Deprecated public static Builder builder(String datasetId, String tableId, RowToInsert... rows) { - return builder(TableId.of(datasetId, tableId), rows); + return newBuilder(datasetId, tableId, rows); + } + + /** + * Returns a builder for an {@code InsertAllRequest} object given the destination table and the + * rows to insert. + */ + public static Builder newBuilder(String datasetId, String tableId, RowToInsert... rows) { + return newBuilder(TableId.of(datasetId, tableId), rows); } /** * Returns a builder for an {@code InsertAllRequest} object given the destination table and the * rows to insert. */ + @Deprecated public static Builder builder(TableInfo tableInfo, Iterable rows) { - return builder(tableInfo.tableId(), rows); + return newBuilder(tableInfo, rows); + } + + /** + * Returns a builder for an {@code InsertAllRequest} object given the destination table and the + * rows to insert. + */ + public static Builder newBuilder(TableInfo tableInfo, Iterable rows) { + return newBuilder(tableInfo.getTableId(), rows); } /** * Returns a builder for an {@code InsertAllRequest} object given the destination table and the * rows to insert. */ + @Deprecated public static Builder builder(TableInfo tableInfo, RowToInsert... rows) { - return builder(tableInfo.tableId(), rows); + return newBuilder(tableInfo, rows); + } + + /** + * Returns a builder for an {@code InsertAllRequest} object given the destination table and the + * rows to insert. + */ + public static Builder newBuilder(TableInfo tableInfo, RowToInsert... rows) { + return newBuilder(tableInfo.getTableId(), rows); } /** * Returns a {@code InsertAllRequest} object given the destination table and the rows to insert. */ public static InsertAllRequest of(TableId tableId, Iterable rows) { - return builder(tableId, rows).build(); + return newBuilder(tableId, rows).build(); } /** * Returns a {@code InsertAllRequest} object given the destination table and the rows to insert. */ public static InsertAllRequest of(TableId tableId, RowToInsert... rows) { - return builder(tableId, rows).build(); + return newBuilder(tableId, rows).build(); } /** * Returns a {@code InsertAllRequest} object given the destination table and the rows to insert. */ public static InsertAllRequest of(String datasetId, String tableId, Iterable rows) { - return builder(datasetId, tableId, rows).build(); + return newBuilder(datasetId, tableId, rows).build(); } /** * Returns a {@code InsertAllRequest} object given the destination table and the rows to insert. */ public static InsertAllRequest of(String datasetId, String tableId, RowToInsert... rows) { - return builder(datasetId, tableId, rows).build(); + return newBuilder(datasetId, tableId, rows).build(); } /** * Returns a {@code InsertAllRequest} object given the destination table and the rows to insert. */ public static InsertAllRequest of(TableInfo tableInfo, Iterable rows) { - return builder(tableInfo.tableId(), rows).build(); + return newBuilder(tableInfo.getTableId(), rows).build(); } /** * Returns a {@code InsertAllRequest} object given the destination table and the rows to insert. */ public static InsertAllRequest of(TableInfo tableInfo, RowToInsert... rows) { - return builder(tableInfo.tableId(), rows).build(); + return newBuilder(tableInfo.getTableId(), rows).build(); } @Override diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/InsertAllResponse.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/InsertAllResponse.java index a145d1037bf7..c74893bb4c08 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/InsertAllResponse.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/InsertAllResponse.java @@ -35,8 +35,8 @@ /** * Google Cloud BigQuery insert all response. Objects of this class possibly contain errors for an * {@link InsertAllRequest}. If a row failed to be inserted, the non-empty list of errors associated - * to that row's index can be obtained with {@link InsertAllResponse#errorsFor(long)}. - * {@link InsertAllResponse#insertErrors()} can be used to return all errors caused by a + * to that row's index can be obtained with {@link InsertAllResponse#getErrorsFor(long)}. + * {@link InsertAllResponse#getInsertErrors()} can be used to return all errors caused by a * {@link InsertAllRequest} as a map. */ public class InsertAllResponse implements Serializable { @@ -54,14 +54,31 @@ public class InsertAllResponse implements Serializable { * Returns all insertion errors as a map whose keys are indexes of rows that failed to insert. * Each failed row index is associated with a non-empty list of {@link BigQueryError}. */ + @Deprecated public Map> insertErrors() { + return getInsertErrors(); + } + + /** + * Returns all insertion errors as a map whose keys are indexes of rows that failed to insert. + * Each failed row index is associated with a non-empty list of {@link BigQueryError}. + */ + public Map> getInsertErrors() { return insertErrors; } /** * Returns errors for the provided row index. If no error exists returns {@code null}. */ + @Deprecated public List errorsFor(long index) { + return getErrorsFor(index); + } + + /** + * Returns errors for the provided row index. If no error exists returns {@code null}. + */ + public List getErrorsFor(long index) { return insertErrors.get(index); } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Job.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Job.java index f8065497904d..41d21d7229e0 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Job.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Job.java @@ -56,7 +56,7 @@ public static final class Builder extends JobInfo.Builder { Builder(BigQuery bigquery, JobConfiguration configuration) { this.bigquery = bigquery; this.infoBuilder = new JobInfo.BuilderImpl(); - this.infoBuilder.configuration(configuration); + this.infoBuilder.setConfiguration(configuration); } Builder(Job job) { @@ -65,50 +65,62 @@ public static final class Builder extends JobInfo.Builder { } @Override - Builder etag(String etag) { - infoBuilder.etag(etag); + Builder setEtag(String etag) { + infoBuilder.setEtag(etag); return this; } @Override - Builder generatedId(String generatedId) { - infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + infoBuilder.setGeneratedId(generatedId); return this; } @Override + @Deprecated public Builder jobId(JobId jobId) { - infoBuilder.jobId(jobId); + return setJobId(jobId); + } + + @Override + public Builder setJobId(JobId jobId) { + infoBuilder.setJobId(jobId); return this; } @Override - Builder selfLink(String selfLink) { - infoBuilder.selfLink(selfLink); + Builder setSelfLink(String selfLink) { + infoBuilder.setSelfLink(selfLink); return this; } @Override - Builder status(JobStatus status) { - infoBuilder.status(status); + Builder setStatus(JobStatus status) { + infoBuilder.setStatus(status); return this; } @Override - Builder statistics(JobStatistics statistics) { - infoBuilder.statistics(statistics); + Builder setStatistics(JobStatistics statistics) { + infoBuilder.setStatistics(statistics); return this; } @Override - Builder userEmail(String userEmail) { - infoBuilder.userEmail(userEmail); + Builder setUserEmail(String userEmail) { + infoBuilder.setUserEmail(userEmail); return this; } @Override + @Deprecated public Builder configuration(JobConfiguration configuration) { - infoBuilder.configuration(configuration); + return setConfiguration(configuration); + } + + @Override + public Builder setConfiguration(JobConfiguration configuration) { + infoBuilder.setConfiguration(configuration); return this; } @@ -138,7 +150,7 @@ public Job build() { * @throws BigQueryException upon failure */ public boolean exists() { - return bigquery.getJob(jobId(), JobOption.fields()) != null; + return bigquery.getJob(getJobId(), JobOption.fields()) != null; } /** @@ -157,8 +169,8 @@ public boolean exists() { * @throws BigQueryException upon failure */ public boolean isDone() { - Job job = bigquery.getJob(jobId(), JobOption.fields(BigQuery.JobField.STATUS)); - return job == null || job.status().state() == JobStatus.State.DONE; + Job job = bigquery.getJob(getJobId(), JobOption.fields(BigQuery.JobField.STATUS)); + return job == null || job.getStatus().getState() == JobStatus.State.DONE; } /** @@ -173,7 +185,7 @@ public boolean isDone() { * Job completedJob = job.waitFor(); * if (completedJob == null) { * // job no longer exists - * } else if (completedJob.status().error() != null) { + * } else if (completedJob.getStatus().getError() != null) { * // job failed, handle error * } else { * // job completed successfully @@ -188,7 +200,7 @@ public boolean isDone() { * WaitForOption.timeout(60, TimeUnit.SECONDS)); * if (completedJob == null) { * // job no longer exists - * } else if (completedJob.status().error() != null) { + * } else if (completedJob.getStatus().getError() != null) { * // job failed, handle error * } else { * // job completed successfully @@ -223,7 +235,7 @@ public Job waitFor(WaitForOption... waitOptions) throws InterruptedException, Ti * *

Example of reloading all fields until job status is DONE. *

 {@code
-   * while (job.status().state() != JobStatus.State.DONE) {
+   * while (job.getStatus().getState() != JobStatus.State.DONE) {
    *   Thread.sleep(1000L);
    *   job = job.reload();
    * }
@@ -231,7 +243,7 @@ public Job waitFor(WaitForOption... waitOptions) throws InterruptedException, Ti
    *
    * 

Example of reloading status field until job status is DONE. *

 {@code
-   * while (job.status().state() != JobStatus.State.DONE) {
+   * while (job.getStatus().getState() != JobStatus.State.DONE) {
    *   Thread.sleep(1000L);
    *   job = job.reload(BigQuery.JobOption.fields(BigQuery.JobField.STATUS));
    * }
@@ -242,7 +254,7 @@ public Job waitFor(WaitForOption... waitOptions) throws InterruptedException, Ti
    * @throws BigQueryException upon failure
    */
   public Job reload(JobOption... options) {
-    return bigquery.getJob(jobId(), options);
+    return bigquery.getJob(getJobId(), options);
   }
 
   /**
@@ -262,13 +274,21 @@ public Job reload(JobOption... options) {
    * @throws BigQueryException upon failure
    */
   public boolean cancel() {
-    return bigquery.cancel(jobId());
+    return bigquery.cancel(getJobId());
   }
 
   /**
    * Returns the job's {@code BigQuery} object used to issue requests.
    */
+  @Deprecated
   public BigQuery bigquery() {
+    return getBigquery();
+  }
+
+  /**
+   * Returns the job's {@code BigQuery} object used to issue requests.
+   */
+  public BigQuery getBigquery() {
     return bigquery;
   }
 
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobConfiguration.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobConfiguration.java
index 85653e357a96..0328369290c8 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobConfiguration.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobConfiguration.java
@@ -78,7 +78,7 @@ B self() {
       return (B) this;
     }
 
-    B type(Type type) {
+    B setType(Type type) {
       this.type = checkNotNull(type);
       return self();
     }
@@ -96,7 +96,15 @@ B type(Type type) {
   /**
    * Returns the type of the job configuration.
    */
+  @Deprecated
   public Type type() {
+    return getType();
+  }
+
+  /**
+   * Returns the type of the job configuration.
+   */
+  public Type getType() {
     return type;
   }
 
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobId.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobId.java
index 9b7749059281..b4cd928ec3a9 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobId.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobId.java
@@ -36,14 +36,30 @@ public final class JobId implements Serializable {
   /**
    * Returns project's user-defined id.
    */
+  @Deprecated
   public String project() {
+    return getProject();
+  }
+
+  /**
+   * Returns project's user-defined id.
+   */
+  public String getProject() {
     return project;
   }
 
   /**
    * Returns the job's user-defined id.
    */
+  @Deprecated
   public String job() {
+    return getJob();
+  }
+
+  /**
+   * Returns the job's user-defined id.
+   */
+  public String getJob() {
     return job;
   }
 
@@ -84,7 +100,7 @@ public String toString() {
   }
 
   JobId setProjectId(String projectId) {
-    return project() != null ? this : JobId.of(projectId, job());
+    return getProject() != null ? this : JobId.of(projectId, getJob());
   }
 
   JobReference toPb() {
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobInfo.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobInfo.java
index 862bc62ac3bd..3661955ce970 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobInfo.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobInfo.java
@@ -93,22 +93,28 @@ public enum WriteDisposition {
    */
   public abstract static class Builder {
 
-    abstract Builder etag(String etag);
+    abstract Builder setEtag(String etag);
 
-    abstract Builder generatedId(String generatedId);
+    abstract Builder setGeneratedId(String generatedId);
 
     /**
      * Sets the job identity.
      */
+    @Deprecated
     public abstract Builder jobId(JobId jobId);
 
-    abstract Builder selfLink(String selfLink);
+    /**
+     * Sets the job identity.
+     */
+    public abstract Builder setJobId(JobId jobId);
 
-    abstract Builder status(JobStatus status);
+    abstract Builder setSelfLink(String selfLink);
 
-    abstract Builder statistics(JobStatistics statistics);
+    abstract Builder setStatus(JobStatus status);
 
-    abstract Builder userEmail(String userEmail);
+    abstract Builder setStatistics(JobStatistics statistics);
+
+    abstract Builder setUserEmail(String userEmail);
 
     /**
      * Sets a configuration for the {@code JobInfo} object. Use {@link CopyJobConfiguration} for a
@@ -117,8 +123,18 @@ public abstract static class Builder {
      * from Google Cloud Storage into a table. Use {@link QueryJobConfiguration} for a job that runs
      * a query.
      */
+    @Deprecated
     public abstract Builder configuration(JobConfiguration configuration);
 
+    /**
+     * Sets a configuration for the {@code JobInfo} object. Use {@link CopyJobConfiguration} for a
+     * job that copies an existing table. Use {@link ExtractJobConfiguration} for a job that exports
+     * a table to Google Cloud Storage. Use {@link LoadJobConfiguration} for a job that loads data
+     * from Google Cloud Storage into a table. Use {@link QueryJobConfiguration} for a job that runs
+     * a query.
+     */
+    public abstract Builder setConfiguration(JobConfiguration configuration);
+
     /**
      * Creates a {@code JobInfo} object.
      */
@@ -167,49 +183,61 @@ static final class BuilderImpl extends Builder {
     }
 
     @Override
-    Builder etag(String etag) {
+    Builder setEtag(String etag) {
       this.etag = etag;
       return this;
     }
 
     @Override
-    Builder generatedId(String generatedId) {
+    Builder setGeneratedId(String generatedId) {
       this.generatedId = generatedId;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder jobId(JobId jobId) {
+      return setJobId(jobId);
+    }
+
+    @Override
+    public Builder setJobId(JobId jobId) {
       this.jobId = jobId;
       return this;
     }
 
     @Override
-    Builder selfLink(String selfLink) {
+    Builder setSelfLink(String selfLink) {
       this.selfLink = selfLink;
       return this;
     }
 
     @Override
-    Builder status(JobStatus status) {
+    Builder setStatus(JobStatus status) {
       this.status = status;
       return this;
     }
 
     @Override
-    Builder statistics(JobStatistics statistics) {
+    Builder setStatistics(JobStatistics statistics) {
       this.statistics = statistics;
       return this;
     }
 
     @Override
-    Builder userEmail(String userEmail) {
+    Builder setUserEmail(String userEmail) {
       this.userEmail = userEmail;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder configuration(JobConfiguration configuration) {
+      return setConfiguration(configuration);
+    }
+
+    @Override
+    public Builder setConfiguration(JobConfiguration configuration) {
       this.configuration = configuration;
       return this;
     }
@@ -234,21 +262,45 @@ public JobInfo build() {
   /**
    * Returns the hash of the job resource.
    */
+  @Deprecated
   public String etag() {
+    return getEtag();
+  }
+
+  /**
+   * Returns the hash of the job resource.
+   */
+  public String getEtag() {
     return etag;
   }
 
   /**
    * Returns the service-generated id for the job.
    */
+  @Deprecated
   public String generatedId() {
+    return getGeneratedId();
+  }
+
+  /**
+   * Returns the service-generated id for the job.
+   */
+  public String getGeneratedId() {
     return generatedId;
   }
 
   /**
    * Returns the job identity.
    */
+  @Deprecated
   public JobId jobId() {
+    return getJobId();
+  }
+
+  /**
+   * Returns the job identity.
+   */
+  public JobId getJobId() {
     return jobId;
   }
 
@@ -256,7 +308,16 @@ public JobId jobId() {
    * Returns an URL that can be used to access the resource again. The returned URL can be used for
    * GET requests.
    */
+  @Deprecated
   public String selfLink() {
+    return getSelfLink();
+  }
+
+  /**
+   * Returns an URL that can be used to access the resource again. The returned URL can be used for
+   * GET requests.
+   */
+  public String getSelfLink() {
     return selfLink;
   }
 
@@ -264,7 +325,16 @@ public String selfLink() {
    * Returns the status of this job. Examine this value when polling an asynchronous job to see if
    * the job is complete.
    */
+  @Deprecated
   public JobStatus status() {
+    return getStatus();
+  }
+
+  /**
+   * Returns the status of this job. Examine this value when polling an asynchronous job to see if
+   * the job is complete.
+   */
+  public JobStatus getStatus() {
     return status;
   }
 
@@ -272,14 +342,31 @@ public JobStatus status() {
    * Returns information about the job, including starting time and ending time of the job.
    */
   @SuppressWarnings("unchecked")
+  @Deprecated
   public  S statistics() {
+    return getStatistics();
+  }
+
+  /**
+   * Returns information about the job, including starting time and ending time of the job.
+   */
+  @SuppressWarnings("unchecked")
+  public  S getStatistics() {
     return (S) statistics;
   }
 
   /**
    * Returns the email address of the user who ran the job.
    */
+  @Deprecated
   public String userEmail() {
+    return getUserEmail();
+  }
+
+  /**
+   * Returns the email address of the user who ran the job.
+   */
+  public String getUserEmail() {
     return userEmail;
   }
 
@@ -287,7 +374,16 @@ public String userEmail() {
    * Returns the job's configuration.
    */
   @SuppressWarnings("unchecked")
+  @Deprecated
   public  C configuration() {
+    return getConfiguration();
+  }
+
+  /**
+   * Returns the job's configuration.
+   */
+  @SuppressWarnings("unchecked")
+  public  C getConfiguration() {
     return (C) configuration;
   }
 
@@ -328,9 +424,9 @@ public boolean equals(Object obj) {
   JobInfo setProjectId(String projectId) {
     Builder builder = toBuilder();
     if (jobId != null) {
-      builder.jobId(jobId.setProjectId(projectId));
+      builder.setJobId(jobId.setProjectId(projectId));
     }
-    return builder.configuration(configuration.setProjectId(projectId)).build();
+    return builder.setConfiguration(configuration.setProjectId(projectId)).build();
   }
 
   Job toPb() {
@@ -359,8 +455,20 @@ Job toPb() {
    * {@link LoadJobConfiguration} for a job that loads data from Google Cloud Storage into a table.
    * Use {@link QueryJobConfiguration} for a job that runs a query.
    */
+  @Deprecated
   public static Builder builder(JobConfiguration configuration) {
-    return new BuilderImpl().configuration(configuration);
+    return newBuilder(configuration);
+  }
+
+  /**
+   * Returns a builder for a {@code JobInfo} object given the job configuration. Use
+   * {@link CopyJobConfiguration} for a job that copies an existing table. Use
+   * {@link ExtractJobConfiguration} for a job that exports a table to Google Cloud Storage. Use
+   * {@link LoadJobConfiguration} for a job that loads data from Google Cloud Storage into a table.
+   * Use {@link QueryJobConfiguration} for a job that runs a query.
+   */
+  public static Builder newBuilder(JobConfiguration configuration) {
+    return new BuilderImpl().setConfiguration(configuration);
   }
 
   /**
@@ -371,7 +479,7 @@ public static Builder builder(JobConfiguration configuration) {
    * runs a query.
    */
   public static JobInfo of(JobConfiguration configuration) {
-    return builder(configuration).build();
+    return newBuilder(configuration).build();
   }
 
   /**
@@ -382,7 +490,7 @@ public static JobInfo of(JobConfiguration configuration) {
    * Use {@link QueryJobConfiguration} for a job that runs a query.
    */
   public static JobInfo of(JobId jobId, JobConfiguration configuration) {
-    return builder(configuration).jobId(jobId).build();
+    return newBuilder(configuration).setJobId(jobId).build();
   }
 
   static JobInfo fromPb(Job jobPb) {
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobStatistics.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobStatistics.java
index 84f882fb2c53..8d4af771e216 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobStatistics.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobStatistics.java
@@ -76,7 +76,7 @@ public final int hashCode() {
       return baseHashCode();
     }
 
-    static Builder builder() {
+    static Builder newBuilder() {
       return new Builder();
     }
 
@@ -107,7 +107,7 @@ private Builder(com.google.api.services.bigquery.model.JobStatistics statisticsP
         this.destinationUriFileCounts = statisticsPb.getExtract().getDestinationUriFileCounts();
       }
 
-      Builder destinationUriFileCounts(List destinationUriFileCounts) {
+      Builder setDestinationUriFileCounts(List destinationUriFileCounts) {
         this.destinationUriFileCounts = destinationUriFileCounts;
         return self();
       }
@@ -128,7 +128,17 @@ private ExtractStatistics(Builder builder) {
      * These values will be in the same order as the URIs specified by
      * {@link ExtractJobConfiguration#destinationUris()}.
      */
+    @Deprecated
     public List destinationUriFileCounts() {
+      return getDestinationUriFileCounts();
+    }
+
+    /**
+     * Returns the number of files per destination URI or URI pattern specified in the extract job.
+     * These values will be in the same order as the URIs specified by
+     * {@link ExtractJobConfiguration#destinationUris()}.
+     */
+    public List getDestinationUriFileCounts() {
       return destinationUriFileCounts;
     }
 
@@ -157,7 +167,7 @@ com.google.api.services.bigquery.model.JobStatistics toPb() {
           new JobStatistics4().setDestinationUriFileCounts(destinationUriFileCounts));
     }
 
-    static Builder builder() {
+    static Builder newBuilder() {
       return new Builder();
     }
 
@@ -197,22 +207,22 @@ private Builder(com.google.api.services.bigquery.model.JobStatistics statisticsP
         this.outputRows = statisticsPb.getLoad().getOutputRows();
       }
 
-      Builder inputBytes(Long inputBytes) {
+      Builder setInputBytes(Long inputBytes) {
         this.inputBytes = inputBytes;
         return self();
       }
 
-      Builder inputFiles(Long inputFiles) {
+      Builder setInputFiles(Long inputFiles) {
         this.inputFiles = inputFiles;
         return self();
       }
 
-      Builder outputBytes(Long outputBytes) {
+      Builder setOutputBytes(Long outputBytes) {
         this.outputBytes = outputBytes;
         return self();
       }
 
-      Builder outputRows(Long outputRows) {
+      Builder setOutputRows(Long outputRows) {
         this.outputRows = outputRows;
         return self();
       }
@@ -235,28 +245,60 @@ private LoadStatistics(Builder builder) {
     /**
      * Returns the number of bytes of source data in a load job.
      */
+    @Deprecated
     public Long inputBytes() {
+      return getInputBytes();
+    }
+
+    /**
+     * Returns the number of bytes of source data in a load job.
+     */
+    public Long getInputBytes() {
       return inputBytes;
     }
 
     /**
      * Returns the number of source files in a load job.
      */
+    @Deprecated
     public Long inputFiles() {
+      return getInputFiles();
+    }
+
+    /**
+     * Returns the number of source files in a load job.
+     */
+    public Long getInputFiles() {
       return inputFiles;
     }
 
     /**
      * Returns the size of the data loaded by a load job so far, in bytes.
      */
+    @Deprecated
     public Long outputBytes() {
+      return getOutputBytes();
+    }
+
+    /**
+     * Returns the size of the data loaded by a load job so far, in bytes.
+     */
+    public Long getOutputBytes() {
       return outputBytes;
     }
 
     /**
      * Returns the number of rows loaded by a load job so far.
      */
+    @Deprecated
     public Long outputRows() {
+      return getOutputRows();
+    }
+
+    /**
+     * Returns the number of rows loaded by a load job so far.
+     */
+    public Long getOutputRows() {
       return outputRows;
     }
 
@@ -292,7 +334,7 @@ com.google.api.services.bigquery.model.JobStatistics toPb() {
       return super.toPb().setLoad(loadStatisticsPb);
     }
 
-    static Builder builder() {
+    static Builder newBuilder() {
       return new Builder();
     }
 
@@ -337,27 +379,27 @@ private Builder(com.google.api.services.bigquery.model.JobStatistics statisticsP
         }
       }
 
-      Builder billingTier(Integer billingTier) {
+      Builder setBillingTier(Integer billingTier) {
         this.billingTier = billingTier;
         return self();
       }
 
-      Builder cacheHit(Boolean cacheHit) {
+      Builder setCacheHit(Boolean cacheHit) {
         this.cacheHit = cacheHit;
         return self();
       }
 
-      Builder totalBytesBilled(Long totalBytesBilled) {
+      Builder setTotalBytesBilled(Long totalBytesBilled) {
         this.totalBytesBilled = totalBytesBilled;
         return self();
       }
 
-      Builder totalBytesProcessed(Long totalBytesProcessed) {
+      Builder setTotalBytesProcessed(Long totalBytesProcessed) {
         this.totalBytesProcessed = totalBytesProcessed;
         return self();
       }
 
-      Builder queryPlan(List queryPlan) {
+      Builder setQueryPlan(List queryPlan) {
         this.queryPlan = queryPlan;
         return self();
       }
@@ -380,7 +422,15 @@ private QueryStatistics(Builder builder) {
     /**
      * Returns the billing tier for the job.
      */
+    @Deprecated
     public Integer billingTier() {
+      return getBillingTier();
+    }
+
+    /**
+     * Returns the billing tier for the job.
+     */
+    public Integer getBillingTier() {
       return billingTier;
     }
 
@@ -390,21 +440,48 @@ public Integer billingTier() {
      * @see 
      *     Query Caching
      */
+    @Deprecated
     public Boolean cacheHit() {
+      return getCacheHit();
+    }
+
+    /**
+     * Returns whether the query result was fetched from the query cache.
+     *
+     * @see 
+     *     Query Caching
+     */
+    public Boolean getCacheHit() {
       return cacheHit;
     }
 
     /**
      * Returns the total number of bytes billed for the job.
      */
+    @Deprecated
     public Long totalBytesBilled() {
+      return getTotalBytesBilled();
+    }
+
+    /**
+     * Returns the total number of bytes billed for the job.
+     */
+    public Long getTotalBytesBilled() {
       return totalBytesBilled;
     }
 
     /**
      * Returns the total number of bytes processed by the job.
      */
+    @Deprecated
     public Long totalBytesProcessed() {
+      return getTotalBytesProcessed();
+    }
+
+    /**
+     * Returns the total number of bytes processed by the job.
+     */
+    public Long getTotalBytesProcessed() {
       return totalBytesProcessed;
     }
 
@@ -416,7 +493,20 @@ public Long totalBytesProcessed() {
      *
      * @see Query Plan
      */
+    @Deprecated
     public List queryPlan() {
+      return getQueryPlan();
+    }
+
+    /**
+     * Returns the query plan as a list of stages or {@code null} if a query plan is not available.
+     * Each stage involves a number of steps that read from data sources, perform a series of
+     * transformations on the input, and emit an output to a future stage (or the final result). The
+     * query plan is available for a completed query job and is retained for 7 days.
+     *
+     * @see Query Plan
+     */
+    public List getQueryPlan() {
       return queryPlan;
     }
 
@@ -457,7 +547,7 @@ com.google.api.services.bigquery.model.JobStatistics toPb() {
       return super.toPb().setQuery(queryStatisticsPb);
     }
 
-    static Builder builder() {
+    static Builder newBuilder() {
       return new Builder();
     }
 
@@ -487,17 +577,17 @@ protected B self() {
       return (B) this;
     }
 
-    B creationTime(Long creationTime) {
+    B setCreationTimestamp(Long creationTime) {
       this.creationTime = creationTime;
       return self();
     }
 
-    B endTime(Long endTime) {
+    B setEndTime(Long endTime) {
       this.endTime = endTime;
       return self();
     }
 
-    B startTime(Long startTime) {
+    B setStartTime(Long startTime) {
       this.startTime = startTime;
       return self();
     }
@@ -514,7 +604,15 @@ protected JobStatistics(Builder builder) {
   /**
    * Returns the creation time of the job in milliseconds since epoch.
    */
+  @Deprecated
   public Long creationTime() {
+    return getCreationTime();
+  }
+
+  /**
+   * Returns the creation time of the job in milliseconds since epoch.
+   */
+  public Long getCreationTime() {
     return creationTime;
   }
 
@@ -522,7 +620,16 @@ public Long creationTime() {
    * Returns the end time of the job in milliseconds since epoch. Returns {@code null} if the
    * job has not finished yet.
    */
+  @Deprecated
   public Long endTime() {
+    return getEndTime();
+  }
+
+  /**
+   * Returns the end time of the job in milliseconds since epoch. Returns {@code null} if the
+   * job has not finished yet.
+   */
+  public Long getEndTime() {
     return endTime;
   }
 
@@ -530,7 +637,16 @@ public Long endTime() {
    * Returns the start time of the job in milliseconds since epoch. Returns {@code null} if the
    * job has not started yet.
    */
+  @Deprecated
   public Long startTime() {
+    return getStartTime();
+  }
+
+  /**
+   * Returns the start time of the job in milliseconds since epoch. Returns {@code null} if the
+   * job has not started yet.
+   */
+  public Long getStartTime() {
     return startTime;
   }
 
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobStatus.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobStatus.java
index b2bfe99a503d..f149959839f5 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobStatus.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/JobStatus.java
@@ -74,7 +74,17 @@ public enum State {
    * {@link State#RUNNING} is being executed. A {@link State#DONE} job has completed either
    * succeeding or failing. If failed {@link #error()} will be non-null.
    */
+  @Deprecated
   public State state() {
+    return getState();
+  }
+
+  /**
+   * Returns the state of the job. A {@link State#PENDING} job is waiting to be executed. A
+   * {@link State#RUNNING} is being executed. A {@link State#DONE} job has completed either
+   * succeeding or failing. If failed {@link #error()} will be non-null.
+   */
+  public State getState() {
     return state;
   }
 
@@ -85,7 +95,19 @@ public State state() {
    * @see 
    *     Troubleshooting Errors
    */
+  @Deprecated
   public BigQueryError error() {
+    return getError();
+  }
+
+  /**
+   * Returns the final error result of the job. If present, indicates that the job has completed
+   * and was unsuccessful.
+   *
+   * @see 
+   *     Troubleshooting Errors
+   */
+  public BigQueryError getError() {
     return error;
   }
 
@@ -96,7 +118,19 @@ public BigQueryError error() {
    * @see 
    *     Troubleshooting Errors
    */
+  @Deprecated
   public List executionErrors() {
+    return getExecutionErrors();
+  }
+
+  /**
+   * Returns all errors encountered during the running of the job. Errors here do not necessarily
+   * mean that the job has completed or was unsuccessful.
+   *
+   * @see 
+   *     Troubleshooting Errors
+   */
+  public List getExecutionErrors() {
     return executionErrors;
   }
 
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/LoadConfiguration.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/LoadConfiguration.java
index 99baa2a7086f..3ec80c4097a5 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/LoadConfiguration.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/LoadConfiguration.java
@@ -35,24 +35,48 @@ interface Builder {
     /**
      * Sets the destination table to load the data into.
      */
+    @Deprecated
     Builder destinationTable(TableId destinationTable);
 
+    /**
+     * Sets the destination table to load the data into.
+     */
+    Builder setDestinationTable(TableId destinationTable);
+
     /**
      * Sets whether the job is allowed to create new tables.
      *
      * @see 
      *     Create Disposition
      */
+    @Deprecated
     Builder createDisposition(CreateDisposition createDisposition);
 
+    /**
+     * Sets whether the job is allowed to create new tables.
+     *
+     * @see 
+     *     Create Disposition
+     */
+    Builder setCreateDisposition(CreateDisposition createDisposition);
+
     /**
      * Sets the action that should occur if the destination table already exists.
      *
      * @see 
      *     Write Disposition
      */
+    @Deprecated
     Builder writeDisposition(WriteDisposition writeDisposition);
 
+    /**
+     * Sets the action that should occur if the destination table already exists.
+     *
+     * @see 
+     *     Write Disposition
+     */
+    Builder setWriteDisposition(WriteDisposition writeDisposition);
+
     /**
      * Sets the source format, and possibly some parsing options, of the external data. Supported
      * formats are {@code CSV}, {@code NEWLINE_DELIMITED_JSON} and {@code DATASTORE_BACKUP}. If not
@@ -61,30 +85,66 @@ interface Builder {
      * 
      *     Source Format
      */
+    @Deprecated
     Builder formatOptions(FormatOptions formatOptions);
 
+    /**
+     * Sets the source format, and possibly some parsing options, of the external data. Supported
+     * formats are {@code CSV}, {@code NEWLINE_DELIMITED_JSON} and {@code DATASTORE_BACKUP}. If not
+     * specified, {@code CSV} format is assumed.
+     *
+     * 
+     *     Source Format
+     */
+    Builder setFormatOptions(FormatOptions formatOptions);
+
     /**
      * Sets the maximum number of bad records that BigQuery can ignore when running the job. If the
      * number of bad records exceeds this value, an invalid error is returned in the job result.
      * By default no bad record is ignored.
      */
+    @Deprecated
     Builder maxBadRecords(Integer maxBadRecords);
 
+    /**
+     * Sets the maximum number of bad records that BigQuery can ignore when running the job. If the
+     * number of bad records exceeds this value, an invalid error is returned in the job result.
+     * By default no bad record is ignored.
+     */
+    Builder setMaxBadRecords(Integer maxBadRecords);
+
     /**
      * Sets the schema for the destination table. The schema can be omitted if the destination table
      * already exists, or if you're loading data from a Google Cloud Datastore backup (i.e.
      * {@code DATASTORE_BACKUP} format option).
      */
+    @Deprecated
     Builder schema(Schema schema);
 
+    /**
+     * Sets the schema for the destination table. The schema can be omitted if the destination table
+     * already exists, or if you're loading data from a Google Cloud Datastore backup (i.e.
+     * {@code DATASTORE_BACKUP} format option).
+     */
+    Builder setSchema(Schema schema);
+
     /**
      * Sets whether BigQuery should allow extra values that are not represented in the table schema.
      * If {@code true}, the extra values are ignored. If {@code false}, records with extra columns
      * are treated as bad records, and if there are too many bad records, an invalid error is
      * returned in the job result. By default unknown values are not allowed.
      */
+    @Deprecated
     Builder ignoreUnknownValues(Boolean ignoreUnknownValues);
 
+    /**
+     * Sets whether BigQuery should allow extra values that are not represented in the table schema.
+     * If {@code true}, the extra values are ignored. If {@code false}, records with extra columns
+     * are treated as bad records, and if there are too many bad records, an invalid error is
+     * returned in the job result. By default unknown values are not allowed.
+     */
+    Builder setIgnoreUnknownValues(Boolean ignoreUnknownValues);
+
     /**
      * Sets which entity properties to load into BigQuery from a Cloud Datastore backup. This field
      * is only used if the source format is set to {@code DATASTORE_BACKUP}. Property names are case
@@ -92,55 +152,116 @@ interface Builder {
      * all properties. If any named property isn't found in the Cloud Datastore backup, an invalid
      * error is returned in the job result.
      */
+    @Deprecated
     Builder projectionFields(List projectionFields);
 
+    /**
+     * Sets which entity properties to load into BigQuery from a Cloud Datastore backup. This field
+     * is only used if the source format is set to {@code DATASTORE_BACKUP}. Property names are case
+     * sensitive and must be top-level properties. If no properties are specified, BigQuery loads
+     * all properties. If any named property isn't found in the Cloud Datastore backup, an invalid
+     * error is returned in the job result.
+     */
+    Builder setProjectionFields(List projectionFields);
+
     LoadConfiguration build();
   }
 
   /**
    * Returns the destination table to load the data into.
    */
+  @Deprecated
   TableId destinationTable();
 
+  /**
+   * Returns the destination table to load the data into.
+   */
+  TableId getDestinationTable();
+
   /**
    * Returns whether the job is allowed to create new tables.
    *
    * @see 
    *     Create Disposition
    */
+  @Deprecated
   CreateDisposition createDisposition();
 
+  /**
+   * Returns whether the job is allowed to create new tables.
+   *
+   * @see 
+   *     Create Disposition
+   */
+  CreateDisposition getCreateDisposition();
+
   /**
    * Returns the action that should occur if the destination table already exists.
    *
    * @see 
    *     Write Disposition
    */
+  @Deprecated
   WriteDisposition writeDisposition();
 
+  /**
+   * Returns the action that should occur if the destination table already exists.
+   *
+   * @see 
+   *     Write Disposition
+   */
+  WriteDisposition getWriteDisposition();
+
   /**
    * Returns additional properties used to parse CSV data (used when {@link #format()} is set
    * to CSV). Returns {@code null} if not set.
    */
+  @Deprecated
   CsvOptions csvOptions();
 
+  /**
+   * Returns additional properties used to parse CSV data (used when {@link #format()} is set
+   * to CSV). Returns {@code null} if not set.
+   */
+  CsvOptions getCsvOptions();
+
   /**
    * Returns the maximum number of bad records that BigQuery can ignore when running the job. If the
    * number of bad records exceeds this value, an invalid error is returned in the job result.
    * By default no bad record is ignored.
    */
+  @Deprecated
   Integer maxBadRecords();
 
+  /**
+   * Returns the maximum number of bad records that BigQuery can ignore when running the job. If the
+   * number of bad records exceeds this value, an invalid error is returned in the job result.
+   * By default no bad record is ignored.
+   */
+  Integer getMaxBadRecords();
+
   /**
    * Returns the schema for the destination table, if set. Returns {@code null} otherwise.
    */
+  @Deprecated
   Schema schema();
 
+  /**
+   * Returns the schema for the destination table, if set. Returns {@code null} otherwise.
+   */
+  Schema getSchema();
+
   /**
    * Returns the format of the data files.
    */
+  @Deprecated
   String format();
 
+  /**
+   * Returns the format of the data files.
+   */
+  String getFormat();
+
   /**
    * Returns whether BigQuery should allow extra values that are not represented in the table
    * schema. If {@code true}, the extra values are ignored. If {@code true}, records with extra
@@ -156,8 +277,18 @@ interface Builder {
    * all properties. If any named property isn't found in the Cloud Datastore backup, an invalid
    * error is returned in the job result.
    */
+  @Deprecated
   List projectionFields();
 
+  /**
+   * Returns which entity properties to load into BigQuery from a Cloud Datastore backup. This field
+   * is only used if the source format is set to {@code DATASTORE_BACKUP}. Property names are case
+   * sensitive and must be top-level properties. If no properties are specified, BigQuery loads
+   * all properties. If any named property isn't found in the Cloud Datastore backup, an invalid
+   * error is returned in the job result.
+   */
+  List getProjectionFields();
+
   /**
    * Returns a builder for the load configuration object.
    */
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/LoadJobConfiguration.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/LoadJobConfiguration.java
index ba55d9f67414..bdff1756586a 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/LoadJobConfiguration.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/LoadJobConfiguration.java
@@ -97,18 +97,18 @@ private Builder(com.google.api.services.bigquery.model.JobConfiguration configur
           || loadConfigurationPb.getFieldDelimiter() != null
           || loadConfigurationPb.getQuote() != null
           || loadConfigurationPb.getSkipLeadingRows() != null) {
-        CsvOptions.Builder builder = CsvOptions.builder()
-            .encoding(loadConfigurationPb.getEncoding())
-            .fieldDelimiter(loadConfigurationPb.getFieldDelimiter())
-            .quote(loadConfigurationPb.getQuote());
+        CsvOptions.Builder builder = CsvOptions.newBuilder()
+            .setEncoding(loadConfigurationPb.getEncoding())
+            .setFieldDelimiter(loadConfigurationPb.getFieldDelimiter())
+            .setQuote(loadConfigurationPb.getQuote());
         if (loadConfigurationPb.getAllowJaggedRows() != null) {
-          builder.allowJaggedRows(loadConfigurationPb.getAllowJaggedRows());
+          builder.setAllowJaggedRows(loadConfigurationPb.getAllowJaggedRows());
         }
         if (loadConfigurationPb.getAllowQuotedNewlines() != null) {
-          builder.allowQuotedNewLines(loadConfigurationPb.getAllowQuotedNewlines());
+          builder.setAllowQuotedNewLines(loadConfigurationPb.getAllowQuotedNewlines());
         }
         if (loadConfigurationPb.getSkipLeadingRows() != null) {
-          builder.skipLeadingRows(loadConfigurationPb.getSkipLeadingRows());
+          builder.setSkipLeadingRows(loadConfigurationPb.getSkipLeadingRows());
         }
         this.formatOptions = builder.build();
       }
@@ -124,49 +124,97 @@ private Builder(com.google.api.services.bigquery.model.JobConfiguration configur
     }
 
     @Override
+    @Deprecated
     public Builder destinationTable(TableId destinationTable) {
+      return setDestinationTable(destinationTable);
+    }
+
+    @Override
+    public Builder setDestinationTable(TableId destinationTable) {
       this.destinationTable = destinationTable;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder createDisposition(JobInfo.CreateDisposition createDisposition) {
+      return setCreateDisposition(createDisposition);
+    }
+
+    @Override
+    public Builder setCreateDisposition(JobInfo.CreateDisposition createDisposition) {
       this.createDisposition = createDisposition;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder writeDisposition(JobInfo.WriteDisposition writeDisposition) {
+      return setWriteDisposition(writeDisposition);
+    }
+
+    @Override
+    public Builder setWriteDisposition(JobInfo.WriteDisposition writeDisposition) {
       this.writeDisposition = writeDisposition;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder formatOptions(FormatOptions formatOptions) {
+      return setFormatOptions(formatOptions);
+    }
+
+    @Override
+    public Builder setFormatOptions(FormatOptions formatOptions) {
       this.formatOptions = formatOptions;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder maxBadRecords(Integer maxBadRecords) {
+      return setMaxBadRecords(maxBadRecords);
+    }
+
+    @Override
+    public Builder setMaxBadRecords(Integer maxBadRecords) {
       this.maxBadRecords = maxBadRecords;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder schema(Schema schema) {
+      return setSchema(schema);
+    }
+
+    @Override
+    public Builder setSchema(Schema schema) {
       this.schema = schema;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder ignoreUnknownValues(Boolean ignoreUnknownValues) {
+      return setIgnoreUnknownValues(ignoreUnknownValues);
+    }
+
+    @Override
+    public Builder setIgnoreUnknownValues(Boolean ignoreUnknownValues) {
       this.ignoreUnknownValues = ignoreUnknownValues;
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder projectionFields(List projectionFields) {
+      return setProjectionFields(projectionFields);
+    }
+
+    @Override
+    public Builder setProjectionFields(List projectionFields) {
       this.projectionFields =
           projectionFields != null ? ImmutableList.copyOf(projectionFields) : null;
       return this;
@@ -177,7 +225,17 @@ public Builder projectionFields(List projectionFields) {
      * gs://bucket/path). Each URI can contain one '*' wildcard character and it must come after the
      * 'bucket' name.
      */
+    @Deprecated
     public Builder sourceUris(List sourceUris) {
+      return setSourceUris(sourceUris);
+    }
+
+    /**
+     * Sets the fully-qualified URIs that point to source data in Google Cloud Storage (e.g.
+     * gs://bucket/path). Each URI can contain one '*' wildcard character and it must come after the
+     * 'bucket' name.
+     */
+    public Builder setSourceUris(List sourceUris) {
       this.sourceUris = ImmutableList.copyOf(checkNotNull(sourceUris));
       return this;
     }
@@ -202,38 +260,80 @@ private LoadJobConfiguration(Builder builder) {
   }
 
   @Override
+  @Deprecated
   public TableId destinationTable() {
+    return getDestinationTable();
+  }
+
+  @Override
+  public TableId getDestinationTable() {
     return destinationTable;
   }
 
   @Override
+  @Deprecated
   public JobInfo.CreateDisposition createDisposition() {
+    return this.getCreateDisposition();
+  }
+
+  @Override
+  public JobInfo.CreateDisposition getCreateDisposition() {
     return this.createDisposition;
   }
 
   @Override
+  @Deprecated
   public JobInfo.WriteDisposition writeDisposition() {
+    return getWriteDisposition();
+  }
+
+  @Override
+  public JobInfo.WriteDisposition getWriteDisposition() {
     return writeDisposition;
   }
 
   @Override
+  @Deprecated
   public CsvOptions csvOptions() {
+    return getCsvOptions();
+  }
+
+  @Override
+  public CsvOptions getCsvOptions() {
     return formatOptions instanceof CsvOptions ? (CsvOptions) formatOptions : null;
   }
 
   @Override
+  @Deprecated
+  public String format() {
+    return getFormat();
+  }
+
+  @Override
+  public String getFormat() {
+    return formatOptions != null ? formatOptions.getType() : null;
+  }
+
+  @Override
+  @Deprecated
   public Integer maxBadRecords() {
+    return getMaxBadRecords();
+  }
+
+  @Override
+  public Integer getMaxBadRecords() {
     return maxBadRecords;
   }
 
   @Override
+  @Deprecated
   public Schema schema() {
-    return schema;
+    return getSchema();
   }
 
   @Override
-  public String format() {
-    return formatOptions != null ? formatOptions.type() : null;
+  public Schema getSchema() {
+    return schema;
   }
 
   @Override
@@ -242,7 +342,13 @@ public Boolean ignoreUnknownValues() {
   }
 
   @Override
+  @Deprecated
   public List projectionFields() {
+    return getProjectionFields();
+  }
+
+  @Override
+  public List getProjectionFields() {
     return projectionFields;
   }
 
@@ -251,7 +357,17 @@ public List projectionFields() {
    * gs://bucket/path). Each URI can contain one '*' wildcard character and it must come after the
    * 'bucket' name.
    */
+  @Deprecated
   public List sourceUris() {
+    return getSourceUris();
+  }
+
+  /**
+   * Returns the fully-qualified URIs that point to source data in Google Cloud Storage (e.g.
+   * gs://bucket/path). Each URI can contain one '*' wildcard character and it must come after the
+   * 'bucket' name.
+   */
+  public List getSourceUris() {
     return sourceUris;
   }
 
@@ -288,7 +404,7 @@ public int hashCode() {
 
   @Override
   LoadJobConfiguration setProjectId(String projectId) {
-    return toBuilder().destinationTable(destinationTable().setProjectId(projectId)).build();
+    return toBuilder().setDestinationTable(getDestinationTable().setProjectId(projectId)).build();
   }
 
   @Override
@@ -301,23 +417,23 @@ com.google.api.services.bigquery.model.JobConfiguration toPb() {
     if (writeDisposition != null) {
       loadConfigurationPb.setWriteDisposition(writeDisposition.toString());
     }
-    if (csvOptions() != null) {
-      CsvOptions csvOptions = csvOptions();
-      loadConfigurationPb.setFieldDelimiter(csvOptions.fieldDelimiter())
+    if (getCsvOptions() != null) {
+      CsvOptions csvOptions = getCsvOptions();
+      loadConfigurationPb.setFieldDelimiter(csvOptions.getFieldDelimiter())
           .setAllowJaggedRows(csvOptions.allowJaggedRows())
           .setAllowQuotedNewlines(csvOptions.allowQuotedNewLines())
-          .setEncoding(csvOptions.encoding())
-          .setQuote(csvOptions.quote());
-      if (csvOptions.skipLeadingRows() != null) {
+          .setEncoding(csvOptions.getEncoding())
+          .setQuote(csvOptions.getQuote());
+      if (csvOptions.getSkipLeadingRows() != null) {
         // todo(mziccard) remove checked cast or comment when #1044 is closed
-        loadConfigurationPb.setSkipLeadingRows(Ints.checkedCast(csvOptions.skipLeadingRows()));
+        loadConfigurationPb.setSkipLeadingRows(Ints.checkedCast(csvOptions.getSkipLeadingRows()));
       }
     }
     if (schema != null) {
       loadConfigurationPb.setSchema(schema.toPb());
     }
     if (formatOptions != null) {
-      loadConfigurationPb.setSourceFormat(formatOptions.type());
+      loadConfigurationPb.setSourceFormat(formatOptions.getType());
     }
     loadConfigurationPb.setMaxBadRecords(maxBadRecords);
     loadConfigurationPb.setIgnoreUnknownValues(ignoreUnknownValues);
@@ -333,8 +449,17 @@ com.google.api.services.bigquery.model.JobConfiguration toPb() {
    * Creates a builder for a BigQuery Load Job configuration given the destination table and source
    * URIs.
    */
+  @Deprecated
   public static Builder builder(TableId destinationTable, List sourceUris) {
-    return new Builder().destinationTable(destinationTable).sourceUris(sourceUris);
+    return newBuilder(destinationTable, sourceUris);
+  }
+
+  /**
+   * Creates a builder for a BigQuery Load Job configuration given the destination table and source
+   * URIs.
+   */
+  public static Builder newBuilder(TableId destinationTable, List sourceUris) {
+    return new Builder().setDestinationTable(destinationTable).setSourceUris(sourceUris);
   }
 
   /**
@@ -342,31 +467,59 @@ public static Builder builder(TableId destinationTable, List sourceUris)
    * URI.
    */
   public static Builder builder(TableId destinationTable, String sourceUri) {
-    return builder(destinationTable, ImmutableList.of(sourceUri));
+    return newBuilder(destinationTable, ImmutableList.of(sourceUri));
+  }
+
+  /**
+   * Creates a builder for a BigQuery Load Job configuration given the destination table and source
+   * URI.
+   */
+  public static Builder newBuilder(TableId destinationTable, String sourceUri) {
+    return newBuilder(destinationTable, ImmutableList.of(sourceUri));
   }
 
   /**
    * Creates a builder for a BigQuery Load Job configuration given the destination table, format and
    * source URIs.
    */
+  @Deprecated
   public static Builder builder(TableId destinationTable, List sourceUris,
       FormatOptions format) {
-    return builder(destinationTable, sourceUris).formatOptions(format);
+    return newBuilder(destinationTable, sourceUris, format);
+  }
+
+  /**
+   * Creates a builder for a BigQuery Load Job configuration given the destination table, format and
+   * source URIs.
+   */
+  public static Builder newBuilder(TableId destinationTable, List sourceUris,
+      FormatOptions format) {
+    return newBuilder(destinationTable, sourceUris).setFormatOptions(format);
   }
 
   /**
    * Creates a builder for a BigQuery Load Job configuration given the destination table, format and
    * source URI.
    */
+  @Deprecated
   public static Builder builder(TableId destinationTable, String sourceUri, FormatOptions format) {
-    return builder(destinationTable, ImmutableList.of(sourceUri), format);
+    return newBuilder(destinationTable, sourceUri, format);
+  }
+
+  /**
+   * Creates a builder for a BigQuery Load Job configuration given the destination table, format and
+   * source URI.
+   */
+  public static Builder newBuilder(TableId destinationTable, String sourceUri,
+      FormatOptions format) {
+    return newBuilder(destinationTable, ImmutableList.of(sourceUri), format);
   }
 
   /**
    * Returns a BigQuery Load Job Configuration for the given destination table and source URIs.
    */
   public static LoadJobConfiguration of(TableId destinationTable, List sourceUris) {
-    return builder(destinationTable, sourceUris).build();
+    return newBuilder(destinationTable, sourceUris).build();
   }
 
   /**
@@ -382,7 +535,7 @@ public static LoadJobConfiguration of(TableId destinationTable, String sourceUri
    */
   public static LoadJobConfiguration of(TableId destinationTable, List sourceUris,
       FormatOptions format) {
-    return builder(destinationTable, sourceUris, format).build();
+    return newBuilder(destinationTable, sourceUris, format).build();
   }
 
   /**
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Option.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Option.java
index 75108d6dfec5..eabdb0d8e72a 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Option.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Option.java
@@ -39,11 +39,11 @@ abstract class Option implements Serializable {
     this.value = value;
   }
 
-  BigQueryRpc.Option rpcOption() {
+  BigQueryRpc.Option getRpcOption() {
     return rpcOption;
   }
 
-  Object value() {
+  Object getValue() {
     return value;
   }
 
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryJobConfiguration.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryJobConfiguration.java
index e540a6e72c70..99c158baf23e 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryJobConfiguration.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryJobConfiguration.java
@@ -151,7 +151,15 @@ private Builder(com.google.api.services.bigquery.model.JobConfiguration configur
     /**
      * Sets the BigQuery SQL query to execute.
      */
+    @Deprecated
     public Builder query(String query) {
+      return setQuery(query);
+    }
+
+    /**
+     * Sets the BigQuery SQL query to execute.
+     */
+    public Builder setQuery(String query) {
       this.query = query;
       return this;
     }
@@ -160,7 +168,16 @@ public Builder query(String query) {
      * Sets the table where to put query results. If not provided a new table is created. This value
      * is required if {@link Builder#allowLargeResults(Boolean)} is set to {@code true}.
      */
+    @Deprecated
     public Builder destinationTable(TableId destinationTable) {
+      return setDestinationTable(destinationTable);
+    }
+
+    /**
+     * Sets the table where to put query results. If not provided a new table is created. This value
+     * is required if {@link Builder#allowLargeResults(Boolean)} is set to {@code true}.
+     */
+    public Builder setDestinationTable(TableId destinationTable) {
       this.destinationTable = destinationTable;
       return this;
     }
@@ -171,7 +188,18 @@ public Builder destinationTable(TableId destinationTable) {
      * sources. By defining these properties, the data sources can be queried as if they were
      * standard BigQuery tables.
      */
+    @Deprecated
     public Builder tableDefinitions(Map tableDefinitions) {
+      return setTableDefinitions(tableDefinitions);
+    }
+
+    /**
+     * Sets the external tables definitions. If querying external data sources outside of BigQuery,
+     * this value describes the data format, location and other properties of the data
+     * sources. By defining these properties, the data sources can be queried as if they were
+     * standard BigQuery tables.
+     */
+    public Builder setTableDefinitions(Map tableDefinitions) {
       this.tableDefinitions = tableDefinitions != null ? Maps.newHashMap(tableDefinitions) : null;
       return this;
     }
@@ -196,7 +224,17 @@ public Builder addTableDefinition(String tableName, ExternalTableDefinition tabl
      * can either be defined inline ({@link UserDefinedFunction#inline(String)}) or loaded from
      * a Google Cloud Storage URI ({@link UserDefinedFunction#fromUri(String)}.
      */
+    @Deprecated
     public Builder userDefinedFunctions(List userDefinedFunctions) {
+      return setUserDefinedFunctions(userDefinedFunctions);
+    }
+
+    /**
+     * Sets user defined function resources that can be used by this query. Function resources
+     * can either be defined inline ({@link UserDefinedFunction#inline(String)}) or loaded from
+     * a Google Cloud Storage URI ({@link UserDefinedFunction#fromUri(String)}.
+     */
+    public Builder setUserDefinedFunctions(List userDefinedFunctions) {
       this.userDefinedFunctions =
           userDefinedFunctions != null ? ImmutableList.copyOf(userDefinedFunctions) : null;
       return this;
@@ -208,7 +246,18 @@ public Builder userDefinedFunctions(List userDefinedFunctio
      * @see 
      *     Create Disposition
      */
+    @Deprecated
     public Builder createDisposition(CreateDisposition createDisposition) {
+      return setCreateDisposition(createDisposition);
+    }
+
+    /**
+     * Sets whether the job is allowed to create tables.
+     *
+     * @see 
+     *     Create Disposition
+     */
+    public Builder setCreateDisposition(CreateDisposition createDisposition) {
       this.createDisposition = createDisposition;
       return this;
     }
@@ -219,7 +268,18 @@ public Builder createDisposition(CreateDisposition createDisposition) {
      * @see 
      *     Write Disposition
      */
+    @Deprecated
     public Builder writeDisposition(WriteDisposition writeDisposition) {
+      return setWriteDisposition(writeDisposition);
+    }
+
+    /**
+     * Sets the action that should occur if the destination table already exists.
+     *
+     * @see 
+     *     Write Disposition
+     */
+    public Builder setWriteDisposition(WriteDisposition writeDisposition) {
       this.writeDisposition = writeDisposition;
       return this;
     }
@@ -228,7 +288,16 @@ public Builder writeDisposition(WriteDisposition writeDisposition) {
      * Sets the default dataset. This dataset is used for all unqualified table names used in the
      * query.
      */
+    @Deprecated
     public Builder defaultDataset(DatasetId defaultDataset) {
+      return setDefaultDataset(defaultDataset);
+    }
+
+    /**
+     * Sets the default dataset. This dataset is used for all unqualified table names used in the
+     * query.
+     */
+    public Builder setDefaultDataset(DatasetId defaultDataset) {
       this.defaultDataset = defaultDataset;
       return this;
     }
@@ -237,15 +306,33 @@ public Builder defaultDataset(DatasetId defaultDataset) {
      * Sets the default dataset. This dataset is used for all unqualified table names used in the
      * query.
      */
+    @Deprecated
     public Builder defaultDataset(String defaultDataset) {
-      return defaultDataset(DatasetId.of(defaultDataset));
+      return setDefaultDataset(DatasetId.of(defaultDataset));
+    }
+
+    /**
+     * Sets the default dataset. This dataset is used for all unqualified table names used in the
+     * query.
+     */
+    public Builder setDefaultDataset(String defaultDataset) {
+      return setDefaultDataset(DatasetId.of(defaultDataset));
     }
 
     /**
      * Sets a priority for the query. If not specified the priority is assumed to be
      * {@link Priority#INTERACTIVE}.
      */
+    @Deprecated
     public Builder priority(Priority priority) {
+      return setPriority(priority);
+    }
+
+    /**
+     * Sets a priority for the query. If not specified the priority is assumed to be
+     * {@link Priority#INTERACTIVE}.
+     */
+    public Builder setPriority(Priority priority) {
       this.priority = priority;
       return this;
     }
@@ -258,7 +345,20 @@ public Builder priority(Priority priority) {
      * @see 
      *     Returning Large Query Results
      */
+    @Deprecated
     public Builder allowLargeResults(Boolean allowLargeResults) {
+      return setAllowLargeResults(allowLargeResults);
+    }
+
+    /**
+     * Sets whether the job is enabled to create arbitrarily large results. If {@code true}
+     * the query is allowed to create large results at a slight cost in performance. If {@code true}
+     * {@link Builder#destinationTable(TableId)} must be provided.
+     *
+     * @see 
+     *     Returning Large Query Results
+     */
+    public Builder setAllowLargeResults(Boolean allowLargeResults) {
       this.allowLargeResults = allowLargeResults;
       return this;
     }
@@ -270,7 +370,19 @@ public Builder allowLargeResults(Boolean allowLargeResults) {
      *
      * @see Query Caching
      */
+    @Deprecated
     public Builder useQueryCache(Boolean useQueryCache) {
+      return setUseQueryCache(useQueryCache);
+    }
+
+    /**
+     * Sets whether to look for the result in the query cache. The query cache is a best-effort
+     * cache that will be flushed whenever tables in the query are modified. Moreover, the query
+     * cache is only available when {@link Builder#destinationTable(TableId)} is not set.
+     *
+     * @see Query Caching
+     */
+    public Builder setUseQueryCache(Boolean useQueryCache) {
       this.useQueryCache = useQueryCache;
       return this;
     }
@@ -282,7 +394,19 @@ public Builder useQueryCache(Boolean useQueryCache) {
      *
      * @see Flatten
      */
+    @Deprecated
     public Builder flattenResults(Boolean flattenResults) {
+      return setFlattenResults(flattenResults);
+    }
+
+    /**
+     * Sets whether nested and repeated fields should be flattened. If set to {@code false}
+     * {@link Builder#allowLargeResults(Boolean)} must be {@code true}. By default results are
+     * flattened.
+     *
+     * @see Flatten
+     */
+    public Builder setFlattenResults(Boolean flattenResults) {
       this.flattenResults = flattenResults;
       return this;
     }
@@ -292,7 +416,17 @@ public Builder flattenResults(Boolean flattenResults) {
      * will return a mostly empty response with some processing statistics, while an invalid query
      * will return the same error it would if it wasn't a dry run.
      */
+    @Deprecated
     public Builder dryRun(Boolean dryRun) {
+      return setDryRun(dryRun);
+    }
+
+    /**
+     * Sets whether the job has to be dry run or not. If set, the job is not executed. A valid query
+     * will return a mostly empty response with some processing statistics, while an invalid query
+     * will return the same error it would if it wasn't a dry run.
+     */
+    public Builder setDryRun(Boolean dryRun) {
       this.dryRun = dryRun;
       return this;
     }
@@ -306,7 +440,21 @@ public Builder dryRun(Boolean dryRun) {
      * {@link #flattenResults(Boolean)} is {@code false}. If not set, legacy SQL dialect is used.
      * This property is experimental and might be subject to change.
      */
+    @Deprecated
     public Builder useLegacySql(Boolean useLegacySql) {
+      return setUseLegacySql(useLegacySql);
+    }
+
+    /**
+     * Sets whether to use BigQuery's legacy SQL dialect for this query. If set to {@code false},
+     * the query will use BigQuery's 
+     * Standard SQL. When set to {@code false}, the values of
+     * {@link #allowLargeResults(Boolean)} and {@link #flattenResults(Boolean)} are ignored; query
+     * will be run as if {@link #allowLargeResults(Boolean)} is {@code true} and
+     * {@link #flattenResults(Boolean)} is {@code false}. If not set, legacy SQL dialect is used.
+     * This property is experimental and might be subject to change.
+     */
+    public Builder setUseLegacySql(Boolean useLegacySql) {
       this.useLegacySql = useLegacySql;
       return this;
     }
@@ -352,7 +500,18 @@ public Boolean allowLargeResults() {
    * @see 
    *     Create Disposition
    */
+  @Deprecated
   public CreateDisposition createDisposition() {
+    return getCreateDisposition();
+  }
+
+  /**
+   * Returns whether the job is allowed to create new tables.
+   *
+   * @see 
+   *     Create Disposition
+   */
+  public CreateDisposition getCreateDisposition() {
     return createDisposition;
   }
 
@@ -360,7 +519,16 @@ public CreateDisposition createDisposition() {
    * Returns the default dataset. This dataset is used for all unqualified table names used in the
    * query.
    */
+  @Deprecated
   public DatasetId defaultDataset() {
+    return getDefaultDataset();
+  }
+
+  /**
+   * Returns the default dataset. This dataset is used for all unqualified table names used in the
+   * query.
+   */
+  public DatasetId getDefaultDataset() {
     return defaultDataset;
   }
 
@@ -368,7 +536,16 @@ public DatasetId defaultDataset() {
    * Returns the table where to put query results. If not provided a new table is created. This
    * value is required if {@link #allowLargeResults()} is {@code true}.
    */
+  @Deprecated
   public TableId destinationTable() {
+    return getDestinationTable();
+  }
+
+  /**
+   * Returns the table where to put query results. If not provided a new table is created. This
+   * value is required if {@link #allowLargeResults()} is {@code true}.
+   */
+  public TableId getDestinationTable() {
     return destinationTable;
   }
 
@@ -385,14 +562,30 @@ public Boolean flattenResults() {
   /**
    * Returns the query priority.
    */
+  @Deprecated
   public Priority priority() {
+    return getPriority();
+  }
+
+  /**
+   * Returns the query priority.
+   */
+  public Priority getPriority() {
     return priority;
   }
 
   /**
    * Returns the Google BigQuery SQL query.
    */
+  @Deprecated
   public String query() {
+    return getQuery();
+  }
+
+  /**
+   * Returns the Google BigQuery SQL query.
+   */
+  public String getQuery() {
     return query;
   }
 
@@ -402,7 +595,18 @@ public String query() {
    * sources. By defining these properties, the data sources can be queried as if they were
    * standard BigQuery tables.
    */
+  @Deprecated
   public Map tableDefinitions() {
+    return getTableDefinitions();
+  }
+
+  /**
+   * Returns the external tables definitions. If querying external data sources outside of BigQuery,
+   * this value describes the data format, location and other properties of the data
+   * sources. By defining these properties, the data sources can be queried as if they were
+   * standard BigQuery tables.
+   */
+  public Map getTableDefinitions() {
     return tableDefinitions;
   }
 
@@ -422,7 +626,17 @@ public Boolean useQueryCache() {
    * can either be defined inline ({@link UserDefinedFunction.Type#INLINE}) or loaded from
    * a Google Cloud Storage URI ({@link UserDefinedFunction.Type#FROM_URI}.
    */
+  @Deprecated
   public List userDefinedFunctions() {
+    return getUserDefinedFunctions();
+  }
+
+  /**
+   * Returns user defined function resources that can be used by this query. Function resources
+   * can either be defined inline ({@link UserDefinedFunction.Type#INLINE}) or loaded from
+   * a Google Cloud Storage URI ({@link UserDefinedFunction.Type#FROM_URI}.
+   */
+  public List getUserDefinedFunctions() {
     return userDefinedFunctions;
   }
 
@@ -432,7 +646,18 @@ public List userDefinedFunctions() {
    * @see 
    *     Write Disposition
    */
+  @Deprecated
   public WriteDisposition writeDisposition() {
+    return getWriteDisposition();
+  }
+
+  /**
+   * Returns the action that should occur if the destination table already exists.
+   *
+   * @see 
+   *     Write Disposition
+   */
+  public WriteDisposition getWriteDisposition() {
     return writeDisposition;
   }
 
@@ -497,11 +722,11 @@ public int hashCode() {
   @Override
   QueryJobConfiguration setProjectId(String projectId) {
     Builder builder = toBuilder();
-    if (destinationTable() != null) {
-      builder.destinationTable(destinationTable().setProjectId(projectId));
+    if (getDestinationTable() != null) {
+      builder.setDestinationTable(getDestinationTable().setProjectId(projectId));
     }
-    if (defaultDataset() != null) {
-      builder.defaultDataset(defaultDataset().setProjectId(projectId));
+    if (getDefaultDataset() != null) {
+      builder.setDefaultDataset(getDefaultDataset().setProjectId(projectId));
     }
     return builder.build();
   }
@@ -554,8 +779,16 @@ com.google.api.services.bigquery.model.JobConfiguration toPb() {
   /**
    * Creates a builder for a BigQuery Query Job given the query to be run.
    */
+  @Deprecated
   public static Builder builder(String query) {
-    return new Builder().query(query);
+    return newBuilder(query);
+  }
+
+  /**
+   * Creates a builder for a BigQuery Query Job given the query to be run.
+   */
+  public static Builder newBuilder(String query) {
+    return new Builder().setQuery(query);
   }
 
   /**
@@ -563,7 +796,7 @@ public static Builder builder(String query) {
    * service.
    */
   public static QueryJobConfiguration of(String query) {
-    return builder(query).build();
+    return newBuilder(query).build();
   }
 
   @SuppressWarnings("unchecked")
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryRequest.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryRequest.java
index fba99340cde7..9e3f57ba5ba8 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryRequest.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryRequest.java
@@ -27,29 +27,30 @@
  * Google Cloud BigQuery Query Request. This class can be used to run a BigQuery SQL query and
  * return results if the query completes within a specified timeout. The query results are saved to
  * a temporary table that is deleted approximately 24 hours after the query is run. The query is run
- * through a BigQuery Job whose identity can be accessed via {@link QueryResponse#jobId()}. If the
- * query does not complete within the provided {@link Builder#maxWaitTime(Long)}, the response
- * returned by {@link BigQuery#query(QueryRequest)} will have {@link QueryResponse#jobCompleted()}
- * set to {@code false} and {@link QueryResponse#result()} set to {@code null}. To obtain query
- * results you can use {@link BigQuery#getQueryResults(JobId, BigQuery.QueryResultsOption...)} until
+ * through a BigQuery Job whose identity can be accessed via {@link QueryResponse#getJobId()}. If
+ * the query does not complete within the provided {@link Builder#setMaxWaitTime(Long)}, the
+ * response returned by {@link BigQuery#query(QueryRequest)} will have
+ * {@link QueryResponse#jobCompleted()} set to {@code false} and {@link QueryResponse#getResult()}
+ * set to {@code null}. To obtain query results you can use
+ * {@link BigQuery#getQueryResults(JobId, BigQuery.QueryResultsOption...)} until
  * {@link QueryResponse#jobCompleted()} returns {@code true}.
  *
  * 

Example usage of a query request: *

 {@code
  * // Substitute "field", "table" and "dataset" with real field, table and dataset identifiers
- * QueryRequest request = QueryRequest.builder("SELECT field FROM table")
- *     .defaultDataset(DatasetId.of("dataset"))
- *     .maxWaitTime(60000L)
- *     .pageSize(1000L)
+ * QueryRequest request = QueryRequest.newBuilder("SELECT field FROM table")
+ *     .setDefaultDataset(DatasetId.of("dataset"))
+ *     .setMaxWaitTime(60000L)
+ *     .setPageSize(1000L)
  *     .build();
  * QueryResponse response = bigquery.query(request);
  * while (!response.jobCompleted()) {
  *   Thread.sleep(1000);
- *   response = bigquery.getQueryResults(response.jobId());
+ *   response = bigquery.getQueryResults(response.getJobId());
  * }
- * List executionErrors = response.executionErrors();
+ * List executionErrors = response.getExecutionErrors();
  * // look for errors in executionErrors
- * QueryResult result = response.result();
+ * QueryResult result = response.getResult();
  * Iterator> rowIterator = result.iterateAll();
  * while(rowIterator.hasNext()) {
  *   List row = rowIterator.next();
@@ -87,7 +88,15 @@ private Builder() {}
     /**
      * Sets the BigQuery query to be executed.
      */
+    @Deprecated
     public Builder query(String query) {
+      return setQuery(query);
+    }
+
+    /**
+     * Sets the BigQuery query to be executed.
+     */
+    public Builder setQuery(String query) {
       this.query = checkNotNull(query);
       return this;
     }
@@ -98,7 +107,18 @@ public Builder query(String query) {
      * query result set is large. In addition to this limit, responses are also limited to 10 MB.
      * By default, there is no maximum row count, and only the byte limit applies.
      */
+    @Deprecated
     public Builder pageSize(Long pageSize) {
+      return setPageSize(pageSize);
+    }
+
+    /**
+     * Sets the maximum number of rows of data to return per page of results. Setting this flag to a
+     * small value such as 1000 and then paging through results might improve reliability when the
+     * query result set is large. In addition to this limit, responses are also limited to 10 MB.
+     * By default, there is no maximum row count, and only the byte limit applies.
+     */
+    public Builder setPageSize(Long pageSize) {
       this.pageSize = pageSize;
       return this;
     }
@@ -106,7 +126,15 @@ public Builder pageSize(Long pageSize) {
     /**
      * Sets the default dataset to assume for any unqualified table names in the query.
      */
+    @Deprecated
     public Builder defaultDataset(DatasetId defaultDataset) {
+      return setDefaultDataset(defaultDataset);
+    }
+
+    /**
+     * Sets the default dataset to assume for any unqualified table names in the query.
+     */
+    public Builder setDefaultDataset(DatasetId defaultDataset) {
       this.defaultDataset = defaultDataset;
       return this;
     }
@@ -114,8 +142,16 @@ public Builder defaultDataset(DatasetId defaultDataset) {
     /**
      * Sets the default dataset to assume for any unqualified table names in the query.
      */
+    @Deprecated
     public Builder defaultDataset(String defaultDataset) {
-      return defaultDataset(DatasetId.of(defaultDataset));
+      return setDefaultDataset(DatasetId.of(defaultDataset));
+    }
+
+    /**
+     * Sets the default dataset to assume for any unqualified table names in the query.
+     */
+    public Builder setDefaultDataset(String defaultDataset) {
+      return setDefaultDataset(DatasetId.of(defaultDataset));
     }
 
     /**
@@ -125,7 +161,19 @@ public Builder defaultDataset(String defaultDataset) {
      * with the {@link QueryResponse#jobCompleted()} set to {@code false}. If not set, a wait time
      * of 10000 milliseconds (10 seconds) is used.
      */
+    @Deprecated
     public Builder maxWaitTime(Long maxWaitTime) {
+      return setMaxWaitTime(maxWaitTime);
+    }
+
+    /**
+     * Sets how long to wait for the query to complete, in milliseconds, before the request times
+     * out and returns. Note that this is only a timeout for the request, not the query. If the
+     * query takes longer to run than the timeout value, the call returns without any results and
+     * with the {@link QueryResponse#jobCompleted()} set to {@code false}. If not set, a wait time
+     * of 10000 milliseconds (10 seconds) is used.
+     */
+    public Builder setMaxWaitTime(Long maxWaitTime) {
       this.maxWaitTime = maxWaitTime;
       return this;
     }
@@ -135,7 +183,17 @@ public Builder maxWaitTime(Long maxWaitTime) {
      * query is valid statistics are returned on how many bytes would be processed. If the query is
      * invalid an error is returned. If not set the query is executed.
      */
+    @Deprecated
     public Builder dryRun(Boolean dryRun) {
+      return setDryRun(dryRun);
+    }
+
+    /**
+     * Sets whether the query has to be dry run or not. If set, the query is not executed. If the
+     * query is valid statistics are returned on how many bytes would be processed. If the query is
+     * invalid an error is returned. If not set the query is executed.
+     */
+    public Builder setDryRun(Boolean dryRun) {
       this.dryRun = dryRun;
       return this;
     }
@@ -147,7 +205,19 @@ public Builder dryRun(Boolean dryRun) {
      *
      * @see Query Caching
      */
+    @Deprecated
     public Builder useQueryCache(Boolean useQueryCache) {
+      return setUseQueryCache(useQueryCache);
+    }
+
+    /**
+     * Sets whether to look for the result in the query cache. The query cache is a best-effort
+     * cache that will be flushed whenever tables in the query are modified. If not specified the
+     * query cache is used.
+     *
+     * @see Query Caching
+     */
+    public Builder setUseQueryCache(Boolean useQueryCache) {
       this.useQueryCache = useQueryCache;
       return this;
     }
@@ -158,7 +228,18 @@ public Builder useQueryCache(Boolean useQueryCache) {
      * Standard SQL. If not set, legacy SQL dialect is used. This property is experimental and
      * might be subject to change.
      */
+    @Deprecated
     public Builder useLegacySql(Boolean useLegacySql) {
+      return setUseLegacySql(useLegacySql);
+    }
+
+    /**
+     * Sets whether to use BigQuery's legacy SQL dialect for this query. If set to {@code false},
+     * the query will use BigQuery's 
+     * Standard SQL. If not set, legacy SQL dialect is used. This property is experimental and
+     * might be subject to change.
+     */
+    public Builder setUseLegacySql(Boolean useLegacySql) {
       this.useLegacySql = useLegacySql;
       return this;
     }
@@ -181,21 +262,45 @@ private QueryRequest(Builder builder) {
   /**
    * Sets the BigQuery query to be executed.
    */
+  @Deprecated
   public String query() {
+    return getQuery();
+  }
+
+  /**
+   * Sets the BigQuery query to be executed.
+   */
+  public String getQuery() {
     return query;
   }
 
   /**
    * Returns the maximum number of rows of data to return per page of results.
    */
+  @Deprecated
   public Long pageSize() {
+    return getPageSize();
+  }
+
+  /**
+   * Returns the maximum number of rows of data to return per page of results.
+   */
+  public Long getPageSize() {
     return pageSize;
   }
 
   /**
    * Returns the default dataset to assume for any unqualified table names in the query.
    */
+  @Deprecated
   public DatasetId defaultDataset() {
+    return getDefaultDataset();
+  }
+
+  /**
+   * Returns the default dataset to assume for any unqualified table names in the query.
+   */
+  public DatasetId getDefaultDataset() {
     return defaultDataset;
   }
 
@@ -208,7 +313,21 @@ public DatasetId defaultDataset() {
    * to complete and read the results. If not set, a wait time of 10000 milliseconds (10 seconds)
    * is used.
    */
+  @Deprecated
   public Long maxWaitTime() {
+    return getMaxWaitTime();
+  }
+
+  /**
+   * Returns how long to wait for the query to complete, in milliseconds, before the request times
+   * out and returns. Note that this is only a timeout for the request, not the query. If the
+   * query takes longer to run than the timeout value, the call returns without any results and
+   * with the {@link QueryResponse#jobCompleted()} set to {@code false}. You can call
+   * {@link BigQuery#getQueryResults(JobId, BigQuery.QueryResultsOption...)} to wait for the query
+   * to complete and read the results. If not set, a wait time of 10000 milliseconds (10 seconds)
+   * is used.
+   */
+  public Long getMaxWaitTime() {
     return maxWaitTime;
   }
 
@@ -247,13 +366,13 @@ public Boolean useLegacySql() {
    */
   public Builder toBuilder() {
     return new Builder()
-        .query(query)
-        .pageSize(pageSize)
-        .defaultDataset(defaultDataset)
-        .maxWaitTime(maxWaitTime)
-        .dryRun(dryRun)
-        .useQueryCache(useQueryCache)
-        .useLegacySql(useLegacySql);
+        .setQuery(query)
+        .setPageSize(pageSize)
+        .setDefaultDataset(defaultDataset)
+        .setMaxWaitTime(maxWaitTime)
+        .setDryRun(dryRun)
+        .setUseQueryCache(useQueryCache)
+        .setUseLegacySql(useLegacySql);
   }
 
   @Override
@@ -284,8 +403,8 @@ public boolean equals(Object obj) {
 
   QueryRequest setProjectId(String projectId) {
     Builder builder = toBuilder();
-    if (defaultDataset() != null) {
-      builder.defaultDataset(defaultDataset().setProjectId(projectId));
+    if (getDefaultDataset() != null) {
+      builder.setDefaultDataset(getDefaultDataset().setProjectId(projectId));
     }
     return builder.build();
   }
@@ -317,36 +436,44 @@ com.google.api.services.bigquery.model.QueryRequest toPb() {
   /**
    * Creates a builder for a {@code QueryRequest} given the BigQuery SQL query to be executed.
    */
+  @Deprecated
   public static Builder builder(String query) {
-    return new Builder().query(query);
+    return newBuilder(query);
+  }
+
+  /**
+   * Creates a builder for a {@code QueryRequest} given the BigQuery SQL query to be executed.
+   */
+  public static Builder newBuilder(String query) {
+    return new Builder().setQuery(query);
   }
 
   /**
    * Creates a {@code QueryRequest} object given the BigQuery SQL query to be executed.
    */
   public static QueryRequest of(String query) {
-    return new Builder().query(query).build();
+    return new Builder().setQuery(query).build();
   }
 
   static QueryRequest fromPb(com.google.api.services.bigquery.model.QueryRequest queryRequestPb) {
-    Builder builder = builder(queryRequestPb.getQuery());
+    Builder builder = newBuilder(queryRequestPb.getQuery());
     if (queryRequestPb.getMaxResults() != null) {
-      builder.pageSize(queryRequestPb.getMaxResults());
+      builder.setPageSize(queryRequestPb.getMaxResults());
     }
     if (queryRequestPb.getDefaultDataset() != null) {
-      builder.defaultDataset(DatasetId.fromPb(queryRequestPb.getDefaultDataset()));
+      builder.setDefaultDataset(DatasetId.fromPb(queryRequestPb.getDefaultDataset()));
     }
     if (queryRequestPb.getTimeoutMs() != null) {
-      builder.maxWaitTime(queryRequestPb.getTimeoutMs());
+      builder.setMaxWaitTime(queryRequestPb.getTimeoutMs());
     }
     if (queryRequestPb.getDryRun() != null) {
-      builder.dryRun(queryRequestPb.getDryRun());
+      builder.setDryRun(queryRequestPb.getDryRun());
     }
     if (queryRequestPb.getUseQueryCache() != null) {
-      builder.useQueryCache(queryRequestPb.getUseQueryCache());
+      builder.setUseQueryCache(queryRequestPb.getUseQueryCache());
     }
     if (queryRequestPb.getUseLegacySql() != null) {
-      builder.useLegacySql(queryRequestPb.getUseLegacySql());
+      builder.setUseLegacySql(queryRequestPb.getUseLegacySql());
     }
     return builder.build();
   }
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResponse.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResponse.java
index 57a8966b0301..2ae44d8cef56 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResponse.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResponse.java
@@ -33,11 +33,11 @@
  * QueryResponse response = bigquery.query(request);
  * while (!response.jobCompleted()) {
  *   Thread.sleep(1000);
- *   response = bigquery.getQueryResults(response.jobId());
+ *   response = bigquery.getQueryResults(response.getJobId());
  * }
- * List executionErrors = response.executionErrors();
+ * List executionErrors = response.getExecutionErrors();
  * // look for errors in executionErrors
- * QueryResult result = response.result();
+ * QueryResult result = response.getResult();
  * Iterator> rowIterator = result.iterateAll();
  * while(rowIterator.hasNext()) {
  *   List row = rowIterator.next();
@@ -69,27 +69,27 @@ static final class Builder {
 
     private Builder() {}
 
-    Builder result(QueryResult result) {
+    Builder setResult(QueryResult result) {
       this.result = result;
       return this;
     }
 
-    Builder etag(String etag) {
+    Builder setEtag(String etag) {
       this.etag = etag;
       return this;
     }
 
-    Builder jobId(JobId jobId) {
+    Builder setJobId(JobId jobId) {
       this.jobId = jobId;
       return this;
     }
 
-    Builder jobCompleted(boolean jobCompleted) {
+    Builder setJobCompleted(boolean jobCompleted) {
       this.jobCompleted = jobCompleted;
       return this;
     }
 
-    Builder executionErrors(List executionErrors) {
+    Builder setExecutionErrors(List executionErrors) {
       this.executionErrors = executionErrors;
       return this;
     }
@@ -112,14 +112,31 @@ private QueryResponse(Builder builder) {
    * Returns the result of the query. Returns {@code null} if {@link #jobCompleted()} is {@code
    * false}.
    */
+  @Deprecated
   public QueryResult result() {
+    return getResult();
+  }
+
+  /**
+   * Returns the result of the query. Returns {@code null} if {@link #jobCompleted()} is {@code
+   * false}.
+   */
+  public QueryResult getResult() {
     return result;
   }
 
   /**
    * Returns the hash of the {@code QueryResponse} resource or {@code null} if not set.
    */
+  @Deprecated
   public String etag() {
+    return getEtag();
+  }
+
+  /**
+   * Returns the hash of the {@code QueryResponse} resource or {@code null} if not set.
+   */
+  public String getEtag() {
     return etag;
   }
 
@@ -127,7 +144,16 @@ public String etag() {
    * Returns the identity of the BigQuery Job that was created to run the query. This field will be
    * present even if the original request timed out.
    */
+  @Deprecated
   public JobId jobId() {
+    return getJobId();
+  }
+
+  /**
+   * Returns the identity of the BigQuery Job that was created to run the query. This field will be
+   * present even if the original request timed out.
+   */
+  public JobId getJobId() {
     return jobId;
   }
 
@@ -154,7 +180,16 @@ public boolean hasErrors() {
    * Returns errors and warnings encountered during the running of the job, if any. Errors here do
    * not necessarily mean that the job has completed or was unsuccessful.
    */
+  @Deprecated
   public List executionErrors() {
+    return getExecutionErrors();
+  }
+
+  /**
+   * Returns errors and warnings encountered during the running of the job, if any. Errors here do
+   * not necessarily mean that the job has completed or was unsuccessful.
+   */
+  public List getExecutionErrors() {
     return executionErrors;
   }
 
@@ -190,7 +225,7 @@ public final boolean equals(Object obj) {
         && Objects.equals(executionErrors, response.executionErrors);
   }
 
-  static Builder builder() {
+  static Builder newBuilder() {
     return new Builder();
   }
 }
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResult.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResult.java
index ba036187307c..93626537a79c 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResult.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResult.java
@@ -49,37 +49,37 @@ static final class Builder {
 
     private Builder() {}
 
-    Builder cacheHit(boolean cacheHit) {
+    Builder setCacheHit(boolean cacheHit) {
       this.cacheHit = cacheHit;
       return this;
     }
 
-    Builder schema(Schema schema) {
+    Builder setSchema(Schema schema) {
       this.schema = schema;
       return this;
     }
 
-    Builder totalBytesProcessed(long totalBytesProcessed) {
+    Builder setTotalBytesProcessed(long totalBytesProcessed) {
       this.totalBytesProcessed = totalBytesProcessed;
       return this;
     }
 
-    Builder totalRows(long totalRows) {
+    Builder setTotalRows(long totalRows) {
       this.totalRows = totalRows;
       return this;
     }
 
-    Builder pageFetcher(QueryResultsPageFetcher pageFetcher) {
+    Builder setPageFetcher(QueryResultsPageFetcher pageFetcher) {
       this.pageFetcher = pageFetcher;
       return this;
     }
 
-    Builder cursor(String cursor) {
+    Builder setCursor(String cursor) {
       this.cursor = cursor;
       return this;
     }
 
-    Builder results(Iterable> results) {
+    Builder setResults(Iterable> results) {
       this.results = results;
       return this;
     }
@@ -110,7 +110,15 @@ public boolean cacheHit() {
   /**
    * Returns the schema of the results. This is present only when the query completes successfully.
    */
+  @Deprecated
   public Schema schema() {
+    return getSchema();
+  }
+
+  /**
+   * Returns the schema of the results. This is present only when the query completes successfully.
+   */
+  public Schema getSchema() {
     return schema;
   }
 
@@ -118,7 +126,16 @@ public Schema schema() {
    * Returns the total number of bytes processed for the query. If this query was a dry run, this is
    * the number of bytes that would be processed if the query were run.
    */
+  @Deprecated
   public long totalBytesProcessed() {
+    return getTotalBytesProcessed();
+  }
+
+  /**
+   * Returns the total number of bytes processed for the query. If this query was a dry run, this is
+   * the number of bytes that would be processed if the query were run.
+   */
+  public long getTotalBytesProcessed() {
     return totalBytesProcessed;
   }
 
@@ -127,7 +144,17 @@ public long totalBytesProcessed() {
    * number of rows in the first page of results returned by {@link #values()}. Returns {@code 0}
    * if the query was a dry run.
    */
+  @Deprecated
   public long totalRows() {
+    return getTotalRows();
+  }
+
+  /**
+   * Returns the total number of rows in the complete query result set, which can be more than the
+   * number of rows in the first page of results returned by {@link #values()}. Returns {@code 0}
+   * if the query was a dry run.
+   */
+  public long getTotalRows() {
     return totalRows;
   }
 
@@ -170,7 +197,7 @@ public final boolean equals(Object obj) {
         && cacheHit == response.cacheHit;
   }
 
-  static Builder builder() {
+  static Builder newBuilder() {
     return new Builder();
   }
 }
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryStage.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryStage.java
index 7276a86e7eeb..258a6efd034e 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryStage.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryStage.java
@@ -92,14 +92,33 @@ public ExplainQueryStep apply(QueryStep stage) {
      * @see Steps
      *     Metadata
      */
+    @Deprecated
     public String name() {
+      return getName();
+    }
+
+    /**
+     * Returns a machine-readable name for the operation.
+     *
+     * @see Steps
+     *     Metadata
+     */
+    public String getName() {
       return name;
     }
 
     /**
      * Returns a list of human-readable stage descriptions.
      */
+    @Deprecated
     public List substeps() {
+      return getSubsteps();
+    }
+
+    /**
+     * Returns a list of human-readable stage descriptions.
+     */
+    public List getSubsteps() {
       return substeps;
     }
 
@@ -167,67 +186,67 @@ static final class Builder {
 
     private Builder() {}
 
-    Builder computeRatioAvg(double computeRatioAvg) {
+    Builder setComputeRationAvg(double computeRatioAvg) {
       this.computeRatioAvg = computeRatioAvg;
       return this;
     }
 
-    Builder computeRatioMax(double computeRatioMax) {
+    Builder setComputeRatioMax(double computeRatioMax) {
       this.computeRatioMax = computeRatioMax;
       return this;
     }
 
-    Builder generatedId(long generatedId) {
+    Builder setGeneratedId(long generatedId) {
       this.generatedId = generatedId;
       return this;
     }
 
-    Builder name(String name) {
+    Builder setName(String name) {
       this.name = name;
       return this;
     }
 
-    Builder readRatioAvg(double readRatioAvg) {
+    Builder setReadRatioAvg(double readRatioAvg) {
       this.readRatioAvg = readRatioAvg;
       return this;
     }
 
-    Builder readRatioMax(double readRatioMax) {
+    Builder setReadRatioMax(double readRatioMax) {
       this.readRatioMax = readRatioMax;
       return this;
     }
 
-    Builder recordsRead(long recordsRead) {
+    Builder setRecordsRead(long recordsRead) {
       this.recordsRead = recordsRead;
       return this;
     }
 
-    Builder recordsWritten(long recordsWritten) {
+    Builder setRecordsWritten(long recordsWritten) {
       this.recordsWritten = recordsWritten;
       return this;
     }
 
-    Builder steps(List steps) {
+    Builder setSteps(List steps) {
       this.steps = steps;
       return this;
     }
 
-    Builder waitRatioAvg(double waitRatioAvg) {
+    Builder setWaitRatioAvg(double waitRatioAvg) {
       this.waitRatioAvg = waitRatioAvg;
       return this;
     }
 
-    Builder waitRatioMax(double waitRatioMax) {
+    Builder setWaitRatioMax(double waitRatioMax) {
       this.waitRatioMax = waitRatioMax;
       return this;
     }
 
-    Builder writeRatioAvg(double writeRatioAvg) {
+    Builder setWriteRatioAvg(double writeRatioAvg) {
       this.writeRatioAvg = writeRatioAvg;
       return this;
     }
 
-    Builder writeRatioMax(double writeRatioMax) {
+    Builder setWriteRatioMax(double writeRatioMax) {
       this.writeRatioMax = writeRatioMax;
       return this;
     }
@@ -257,7 +276,16 @@ QueryStage build() {
    * Returns the time the average worker spent CPU-bound, divided by the longest time spent by any
    * worker in any segment.
    */
+  @Deprecated
   public double computeRatioAvg() {
+    return getComputeRatioAvg();
+  }
+
+  /**
+   * Returns the time the average worker spent CPU-bound, divided by the longest time spent by any
+   * worker in any segment.
+   */
+  public double getComputeRatioAvg() {
     return computeRatioAvg;
   }
 
@@ -265,21 +293,46 @@ public double computeRatioAvg() {
    * Returns the time the slowest worker spent CPU-bound, divided by the longest time spent by any
    * worker in any segment.
    */
+  @Deprecated
   public double computeRatioMax() {
+    return getComputeRatioMax();
+  }
+
+  /**
+   * Returns the time the slowest worker spent CPU-bound, divided by the longest time spent by any
+   * worker in any segment.
+   */
+  public double getComputeRatioMax() {
     return computeRatioMax;
   }
 
   /**
    * Returns a unique, server-generated ID for the stage within its plan.
    */
+  @Deprecated
   public long generatedId() {
+    return getGeneratedId();
+  }
+
+  /**
+   * Returns a unique, server-generated ID for the stage within its plan.
+   */
+  public long getGeneratedId() {
     return generatedId;
   }
 
   /**
    * Returns a human-readable name for the stage.
    */
+  @Deprecated
   public String name() {
+    return getName();
+  }
+
+  /**
+   * Returns a human-readable name for the stage.
+   */
+  public String getName() {
     return name;
   }
 
@@ -287,7 +340,16 @@ public String name() {
    * Returns the time the average worker spent reading input data, divided by the longest time spent
    * by any worker in any segment.
    */
+  @Deprecated
   public double readRatioAvg() {
+    return getReadRatioAvg();
+  }
+
+  /**
+   * Returns the time the average worker spent reading input data, divided by the longest time spent
+   * by any worker in any segment.
+   */
+  public double getReadRatioAvg() {
     return readRatioAvg;
   }
 
@@ -295,28 +357,61 @@ public double readRatioAvg() {
    * Returns the time the slowest worker spent reading input data, divided by the longest time spent
    * by any worker in any segment.
    */
+  @Deprecated
   public double readRatioMax() {
+    return getReadRatioMax();
+  }
+
+  /**
+   * Returns the time the slowest worker spent reading input data, divided by the longest time spent
+   * by any worker in any segment.
+   */
+  public double getReadRatioMax() {
     return readRatioMax;
   }
 
   /**
    * Returns the number of rows (top-level records) read by the stage.
    */
+  @Deprecated
   public long recordsRead() {
+    return getRecordsRead();
+  }
+
+  /**
+   * Returns the number of rows (top-level records) read by the stage.
+   */
+  public long getRecordsRead() {
     return recordsRead;
   }
 
   /**
    * Returns the number of rows (top-level records) written by the stage.
    */
+  @Deprecated
   public long recordsWritten() {
+    return getRecordsWritten();
+  }
+
+  /**
+   * Returns the number of rows (top-level records) written by the stage.
+   */
+  public long getRecordsWritten() {
     return recordsWritten;
   }
 
   /**
    * Returns the list of steps within the stage in dependency order (approximately chronological).
    */
+  @Deprecated
   public List steps() {
+    return getSteps();
+  }
+
+  /**
+   * Returns the list of steps within the stage in dependency order (approximately chronological).
+   */
+  public List getSteps() {
     return steps;
   }
 
@@ -324,7 +419,16 @@ public List steps() {
    * Returns the time the average worker spent waiting to be scheduled, divided by the longest time
    * spent by any worker in any segment.
    */
+  @Deprecated
   public double waitRatioAvg() {
+    return getWaitRatioAvg();
+  }
+
+  /**
+   * Returns the time the average worker spent waiting to be scheduled, divided by the longest time
+   * spent by any worker in any segment.
+   */
+  public double getWaitRatioAvg() {
     return waitRatioAvg;
   }
 
@@ -332,7 +436,16 @@ public double waitRatioAvg() {
    * Returns the time the slowest worker spent waiting to be scheduled, divided by the longest time
    * spent by any worker in any segment.
    */
+  @Deprecated
   public double waitRatioMax() {
+    return getWaitRatioMax();
+  }
+
+  /**
+   * Returns the time the slowest worker spent waiting to be scheduled, divided by the longest time
+   * spent by any worker in any segment.
+   */
+  public double getWaitRatioMax() {
     return waitRatioMax;
   }
 
@@ -340,7 +453,16 @@ public double waitRatioMax() {
    * Returns the time the average worker spent writing output data, divided by the longest time
    * spent by any worker in any segment.
    */
+  @Deprecated
   public double writeRatioAvg() {
+    return getWriteRatioAvg();
+  }
+
+  /**
+   * Returns the time the average worker spent writing output data, divided by the longest time
+   * spent by any worker in any segment.
+   */
+  public double getWriteRatioAvg() {
     return writeRatioAvg;
   }
 
@@ -348,7 +470,16 @@ public double writeRatioAvg() {
    * Returns the time the slowest worker spent writing output data, divided by the longest time
    * spent by any worker in any segment.
    */
+  @Deprecated
   public double writeRatioMax() {
+    return getWriteRatioMax();
+  }
+
+  /**
+   * Returns the time the slowest worker spent writing output data, divided by the longest time
+   * spent by any worker in any segment.
+   */
+  public double getWriteRatioMax() {
     return writeRatioMax;
   }
 
@@ -402,7 +533,7 @@ public final boolean equals(Object obj) {
         && Objects.equals(name, other.name);
   }
 
-  static Builder builder() {
+  static Builder newBuilder() {
     return new Builder();
   }
 
@@ -428,21 +559,21 @@ ExplainQueryStage toPb() {
 
   static QueryStage fromPb(com.google.api.services.bigquery.model.ExplainQueryStage stagePb) {
     Builder builder = new QueryStage.Builder();
-    builder.computeRatioAvg(stagePb.getComputeRatioAvg());
-    builder.computeRatioMax(stagePb.getComputeRatioMax());
-    builder.generatedId(stagePb.getId());
-    builder.name(stagePb.getName());
-    builder.readRatioAvg(stagePb.getReadRatioAvg());
-    builder.readRatioMax(stagePb.getReadRatioMax());
-    builder.recordsRead(stagePb.getRecordsRead());
-    builder.recordsWritten(stagePb.getRecordsWritten());
+    builder.setComputeRationAvg(stagePb.getComputeRatioAvg());
+    builder.setComputeRatioMax(stagePb.getComputeRatioMax());
+    builder.setGeneratedId(stagePb.getId());
+    builder.setName(stagePb.getName());
+    builder.setReadRatioAvg(stagePb.getReadRatioAvg());
+    builder.setReadRatioMax(stagePb.getReadRatioMax());
+    builder.setRecordsRead(stagePb.getRecordsRead());
+    builder.setRecordsWritten(stagePb.getRecordsWritten());
     if (stagePb.getSteps() != null) {
-      builder.steps(Lists.transform(stagePb.getSteps(), QueryStep.FROM_PB_FUNCTION));
+      builder.setSteps(Lists.transform(stagePb.getSteps(), QueryStep.FROM_PB_FUNCTION));
     }
-    builder.waitRatioAvg(stagePb.getWaitRatioAvg());
-    builder.waitRatioMax(stagePb.getWaitRatioMax());
-    builder.writeRatioAvg(stagePb.getWriteRatioAvg());
-    builder.writeRatioMax(stagePb.getWriteRatioMax());
+    builder.setWaitRatioAvg(stagePb.getWaitRatioAvg());
+    builder.setWaitRatioMax(stagePb.getWaitRatioMax());
+    builder.setWriteRatioAvg(stagePb.getWriteRatioAvg());
+    builder.setWriteRatioMax(stagePb.getWriteRatioMax());
     return builder.build();
   }
 }
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Schema.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Schema.java
index 218c2a214e50..5ca667af63b9 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Schema.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Schema.java
@@ -74,7 +74,15 @@ public Builder addField(Field field) {
     /**
      * Sets table's schema fields.
      */
+    @Deprecated
     public Builder fields(Iterable fields) {
+      return setFields(fields);
+    }
+
+    /**
+     * Sets table's schema fields.
+     */
+    public Builder setFields(Iterable fields) {
       this.fields = Lists.newArrayList(checkNotNull(fields));
       return this;
     }
@@ -82,7 +90,15 @@ public Builder fields(Iterable fields) {
     /**
      * Sets table's schema fields.
      */
+    @Deprecated
     public Builder fields(Field... fields) {
+      return setFields(fields);
+    }
+
+    /**
+     * Sets table's schema fields.
+     */
+    public Builder setFields(Field... fields) {
       this.fields = Lists.newArrayList(fields);
       return this;
     }
@@ -103,7 +119,15 @@ private Schema(Builder builder) {
   /**
    * Returns the fields in the current table schema.
    */
+  @Deprecated
   public List fields() {
+    return getFields();
+  }
+
+  /**
+   * Returns the fields in the current table schema.
+   */
+  public List getFields() {
     return fields;
   }
 
@@ -111,7 +135,7 @@ public List fields() {
    * Returns a builder for the {@code Schema} object.
    */
   public Builder toBuilder() {
-    return builder().fields(fields);
+    return newBuilder().setFields(fields);
   }
 
   @Override
@@ -143,16 +167,33 @@ com.google.api.services.bigquery.model.TableSchema toPb() {
     return tableSchemaPb;
   }
 
+  /**
+   * Creates a builder for a {@code Schema} object.
+   */
+  @Deprecated
   public static Builder builder() {
+    return newBuilder();
+  }
+
+  /**
+   * Creates a builder for a {@code Schema} object.
+   */
+  public static Builder newBuilder() {
     return new Builder();
   }
 
+  /**
+   * Creates a {@code Schema} object given a list of fields.
+   */
   public static Schema of(Iterable fields) {
-    return builder().fields(fields).build();
+    return newBuilder().setFields(fields).build();
   }
 
+  /**
+   * Creates a {@code Schema} object given some fields.
+   */
   public static Schema of(Field... fields) {
-    return builder().fields(fields).build();
+    return newBuilder().setFields(fields).build();
   }
 
   static Schema fromPb(com.google.api.services.bigquery.model.TableSchema tableSchemaPb) {
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/StandardTableDefinition.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/StandardTableDefinition.java
index d6a5bd17a959..871d84f962fe 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/StandardTableDefinition.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/StandardTableDefinition.java
@@ -64,14 +64,30 @@ public static class StreamingBuffer implements Serializable {
     /**
      * Returns a lower-bound estimate of the number of rows currently in the streaming buffer.
      */
+    @Deprecated
     public long estimatedRows() {
+      return getEstimatedRows();
+    }
+
+    /**
+     * Returns a lower-bound estimate of the number of rows currently in the streaming buffer.
+     */
+    public long getEstimatedRows() {
       return estimatedRows;
     }
 
     /**
      * Returns a lower-bound estimate of the number of bytes currently in the streaming buffer.
      */
+    @Deprecated
     public long estimatedBytes() {
+      return getEstimatedBytes();
+    }
+
+    /**
+     * Returns a lower-bound estimate of the number of bytes currently in the streaming buffer.
+     */
+    public long getEstimatedBytes() {
       return estimatedBytes;
     }
 
@@ -79,7 +95,16 @@ public long estimatedBytes() {
      * Returns the timestamp of the oldest entry in the streaming buffer, in milliseconds since
      * epoch. Returns {@code null} if the streaming buffer is empty.
      */
+    @Deprecated
     public Long oldestEntryTime() {
+      return getOldestEntryTime();
+    }
+
+    /**
+     * Returns the timestamp of the oldest entry in the streaming buffer, in milliseconds since
+     * epoch. Returns {@code null} if the streaming buffer is empty.
+     */
+    public Long getOldestEntryTime() {
       return oldestEntryTime;
     }
 
@@ -146,7 +171,7 @@ private Builder(StandardTableDefinition tableDefinition) {
     private Builder(Table tablePb) {
       super(tablePb);
       if (tablePb.getNumRows() != null) {
-        this.numRows(tablePb.getNumRows().longValue());
+        this.setNumRows(tablePb.getNumRows().longValue());
       }
       this.numBytes = tablePb.getNumBytes();
       this.location = tablePb.getLocation();
@@ -158,22 +183,22 @@ private Builder(Table tablePb) {
       }
     }
 
-    Builder numBytes(Long numBytes) {
+    Builder setNumBytes(Long numBytes) {
       this.numBytes = numBytes;
       return self();
     }
 
-    Builder numRows(Long numRows) {
+    Builder setNumRows(Long numRows) {
       this.numRows = numRows;
       return self();
     }
 
-    Builder location(String location) {
+    Builder setLocation(String location) {
       this.location = location;
       return self();
     }
 
-    Builder streamingBuffer(StreamingBuffer streamingBuffer) {
+    Builder setStreamingBuffer(StreamingBuffer streamingBuffer) {
       this.streamingBuffer = streamingBuffer;
       return self();
     }
@@ -182,7 +207,16 @@ Builder streamingBuffer(StreamingBuffer streamingBuffer) {
      * Sets the time partitioning configuration for the table. If not set, the table is not
      * time-partitioned.
      */
+    @Deprecated
     public Builder timePartitioning(TimePartitioning timePartitioning) {
+      return setTimePartitioning(timePartitioning);
+    }
+
+    /**
+     * Sets the time partitioning configuration for the table. If not set, the table is not
+     * time-partitioned.
+     */
+    public Builder setTimePartitioning(TimePartitioning timePartitioning) {
       this.timePartitioning = timePartitioning;
       return this;
     }
@@ -208,14 +242,30 @@ private StandardTableDefinition(Builder builder) {
   /**
    * Returns the size of this table in bytes, excluding any data in the streaming buffer.
    */
+  @Deprecated
   public Long numBytes() {
+    return getNumBytes();
+  }
+
+  /**
+   * Returns the size of this table in bytes, excluding any data in the streaming buffer.
+   */
+  public Long getNumBytes() {
     return numBytes;
   }
 
   /**
    * Returns the number of rows in this table, excluding any data in the streaming buffer.
    */
+  @Deprecated
   public Long numRows() {
+    return getNumRows();
+  }
+
+  /**
+   * Returns the number of rows in this table, excluding any data in the streaming buffer.
+   */
+  public Long getNumRows() {
     return numRows;
   }
 
@@ -226,7 +276,19 @@ public Long numRows() {
    * @see 
    *     Dataset Location
    */
+  @Deprecated
   public String location() {
+    return getLocation();
+  }
+
+  /**
+   * Returns the geographic location where the table should reside. This value is inherited from the
+   * dataset.
+   *
+   * @see 
+   *     Dataset Location
+   */
+  public String getLocation() {
     return location;
   }
 
@@ -234,14 +296,48 @@ public String location() {
    * Returns information on the table's streaming buffer if any exists. Returns {@code null} if no
    * streaming buffer exists.
    */
+  @Deprecated
   public StreamingBuffer streamingBuffer() {
+    return getStreamingBuffer();
+  }
+
+  /**
+   * Returns information on the table's streaming buffer if any exists. Returns {@code null} if no
+   * streaming buffer exists.
+   */
+  public StreamingBuffer getStreamingBuffer() {
     return streamingBuffer;
   }
 
+  /**
+   * Returns the time partitioning configuration for this table. If {@code null}, the table is not
+   * time-partitioned.
+   */
+  @Deprecated
+  public TimePartitioning timePartitioning() {
+    return getTimePartitioning();
+  }
+
+  /**
+   * Returns the time partitioning configuration for this table. If {@code null}, the table is not
+   * time-partitioned.
+   */
+  public TimePartitioning getTimePartitioning() {
+    return timePartitioning;
+  }
+
   /**
    * Returns a builder for a BigQuery standard table definition.
    */
+  @Deprecated
   public static Builder builder() {
+    return newBuilder();
+  }
+
+  /**
+   * Returns a builder for a BigQuery standard table definition.
+   */
+  public static Builder newBuilder() {
     return new Builder();
   }
 
@@ -251,15 +347,7 @@ public static Builder builder() {
    * @param schema the schema of the table
    */
   public static StandardTableDefinition of(Schema schema) {
-    return builder().schema(schema).build();
-  }
-
-  /**
-   * Returns the time partitioning configuration for this table. If {@code null}, the table is not
-   * time-partitioned.
-   */
-  public TimePartitioning timePartitioning() {
-    return timePartitioning;
+    return newBuilder().setSchema(schema).build();
   }
 
   /**
diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Table.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Table.java
index 26f79be6f754..cf6ccdb52101 100644
--- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Table.java
+++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Table.java
@@ -56,7 +56,7 @@ public static class Builder extends TableInfo.Builder {
     Builder(BigQuery bigquery, TableId tableId, TableDefinition defintion) {
       this.bigquery = bigquery;
       this.infoBuilder = new TableInfo.BuilderImpl();
-      this.infoBuilder.tableId(tableId).definition(defintion);
+      this.infoBuilder.setTableId(tableId).setDefinition(defintion);
     }
 
     Builder(Table table) {
@@ -65,62 +65,92 @@ public static class Builder extends TableInfo.Builder {
     }
 
     @Override
-    Builder creationTime(Long creationTime) {
-      infoBuilder.creationTime(creationTime);
+    Builder setCreationTime(Long creationTime) {
+      infoBuilder.setCreationTime(creationTime);
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder description(String description) {
-      infoBuilder.description(description);
+      return setDescription(description);
+    }
+
+    @Override
+    public Builder setDescription(String description) {
+      infoBuilder.setDescription(description);
       return this;
     }
 
     @Override
-    Builder etag(String etag) {
-      infoBuilder.etag(etag);
+    Builder setEtag(String etag) {
+      infoBuilder.setEtag(etag);
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder expirationTime(Long expirationTime) {
-      infoBuilder.expirationTime(expirationTime);
+      return setExpirationTime(expirationTime);
+    }
+
+    @Override
+    public Builder setExpirationTime(Long expirationTime) {
+      infoBuilder.setExpirationTime(expirationTime);
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder friendlyName(String friendlyName) {
-      infoBuilder.friendlyName(friendlyName);
+      return setFriendlyName(friendlyName);
+    }
+
+    @Override
+    public Builder setFriendlyName(String friendlyName) {
+      infoBuilder.setFriendlyName(friendlyName);
       return this;
     }
 
     @Override
-    Builder generatedId(String generatedId) {
-      infoBuilder.generatedId(generatedId);
+    Builder setGeneratedId(String generatedId) {
+      infoBuilder.setGeneratedId(generatedId);
       return this;
     }
 
     @Override
-    Builder lastModifiedTime(Long lastModifiedTime) {
-      infoBuilder.lastModifiedTime(lastModifiedTime);
+    Builder setLastModifiedTime(Long lastModifiedTime) {
+      infoBuilder.setLastModifiedTime(lastModifiedTime);
       return this;
     }
 
     @Override
-    Builder selfLink(String selfLink) {
-      infoBuilder.selfLink(selfLink);
+    Builder setSelfLink(String selfLink) {
+      infoBuilder.setSelfLink(selfLink);
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder tableId(TableId tableId) {
-      infoBuilder.tableId(tableId);
+      return setTableId(tableId);
+    }
+
+    @Override
+    public Builder setTableId(TableId tableId) {
+      infoBuilder.setTableId(tableId);
       return this;
     }
 
     @Override
+    @Deprecated
     public Builder definition(TableDefinition definition) {
-      infoBuilder.definition(definition);
+      return setDefinition(definition);
+    }
+
+    @Override
+    public Builder setDefinition(TableDefinition definition) {
+      infoBuilder.setDefinition(definition);
       return this;
     }
 
@@ -153,7 +183,7 @@ public Table build() {
    * @throws BigQueryException upon failure
    */
   public boolean exists() {
-    return bigquery.getTable(tableId(), TableOption.fields()) != null;
+    return bigquery.getTable(getTableId(), TableOption.fields()) != null;
   }
 
   /**
@@ -175,7 +205,7 @@ public boolean exists() {
    * @throws BigQueryException upon failure
    */
   public Table reload(TableOption... options) {
-    return bigquery.getTable(tableId(), options);
+    return bigquery.getTable(getTableId(), options);
   }
 
   /**
@@ -184,7 +214,7 @@ public Table reload(TableOption... options) {
    *
    * 

Example of updating the table's information. *

 {@code
-   * Table updatedTable = table.toBuilder().description("new description").build().update();
+   * Table updatedTable = table.toBuilder().setDescription("new description").build().update();
    * }
* * @param options dataset options @@ -212,7 +242,7 @@ public Table update(TableOption... options) { * @throws BigQueryException upon failure */ public boolean delete() { - return bigquery.delete(tableId()); + return bigquery.delete(getTableId()); } /** @@ -240,7 +270,7 @@ public boolean delete() { */ public InsertAllResponse insert(Iterable rows) throws BigQueryException { - return bigquery.insertAll(InsertAllRequest.of(tableId(), rows)); + return bigquery.insertAll(InsertAllRequest.of(getTableId(), rows)); } /** @@ -272,10 +302,10 @@ public InsertAllResponse insert(Iterable rows) * @throws BigQueryException upon failure */ public InsertAllResponse insert(Iterable rows, - boolean skipInvalidRows, boolean ignoreUnknownValues) throws BigQueryException { - InsertAllRequest request = InsertAllRequest.builder(tableId(), rows) - .skipInvalidRows(skipInvalidRows) - .ignoreUnknownValues(ignoreUnknownValues) + boolean skipInvalidRows, boolean ignoreUnknownValues) throws BigQueryException { + InsertAllRequest request = InsertAllRequest.newBuilder(getTableId(), rows) + .setSkipInvalidRows(skipInvalidRows) + .setIgnoreUnknownValues(ignoreUnknownValues) .build(); return bigquery.insertAll(request); } @@ -298,7 +328,7 @@ public InsertAllResponse insert(Iterable rows, */ public Page> list(TableDataListOption... options) throws BigQueryException { - return bigquery.listTableData(tableId(), options); + return bigquery.listTableData(getTableId(), options); } /** @@ -314,7 +344,7 @@ public Page> list(TableDataListOption... options) * try { * Job completedJob = job.waitFor(WaitForOption.checkEvery(1, TimeUnit.SECONDS), * WaitForOption.timeout(3, TimeUnit.MINUTES)); - * if (completedJob != null && completedJob.status().error() == null) { + * if (completedJob != null && completedJob.getStatus().getError() == null) { * // Job completed successfully * } else { * // Handle error case @@ -349,7 +379,7 @@ public Job copy(String destinationDataset, String destinationTable, JobOption... * try { * Job completedJob = job.waitFor(WaitForOption.checkEvery(1, TimeUnit.SECONDS), * WaitForOption.timeout(3, TimeUnit.MINUTES)); - * if (completedJob != null && completedJob.status().error() == null) { + * if (completedJob != null && completedJob.getStatus().getError() == null) { * // Job completed successfully. * } else { * // Handle error case. @@ -365,7 +395,7 @@ public Job copy(String destinationDataset, String destinationTable, JobOption... */ public Job copy(TableId destinationTable, JobOption... options) throws BigQueryException { - CopyJobConfiguration configuration = CopyJobConfiguration.of(destinationTable, tableId()); + CopyJobConfiguration configuration = CopyJobConfiguration.of(destinationTable, getTableId()); return bigquery.create(JobInfo.of(configuration), options); } @@ -382,7 +412,7 @@ public Job copy(TableId destinationTable, JobOption... options) * try { * Job completedJob = job.waitFor(WaitForOption.checkEvery(1, TimeUnit.SECONDS), * WaitForOption.timeout(3, TimeUnit.MINUTES)); - * if (completedJob != null && completedJob.status().error() == null) { + * if (completedJob != null && completedJob.getStatus().getError() == null) { * // Job completed successfully * } else { * // Handle error case @@ -420,7 +450,7 @@ public Job extract(String format, String destinationUri, JobOption... options) * try { * Job completedJob = job.waitFor(WaitForOption.checkEvery(1, TimeUnit.SECONDS), * WaitForOption.timeout(3, TimeUnit.MINUTES)); - * if (completedJob != null && completedJob.status().error() == null) { + * if (completedJob != null && completedJob.getStatus().getError() == null) { * // Job completed successfully * } else { * // Handle error case @@ -439,7 +469,7 @@ public Job extract(String format, String destinationUri, JobOption... options) public Job extract(String format, List destinationUris, JobOption... options) throws BigQueryException { ExtractJobConfiguration extractConfiguration = - ExtractJobConfiguration.of(tableId(), destinationUris, format); + ExtractJobConfiguration.of(getTableId(), destinationUris, format); return bigquery.create(JobInfo.of(extractConfiguration), options); } @@ -455,7 +485,7 @@ public Job extract(String format, List destinationUris, JobOption... opt * try { * Job completedJob = job.waitFor(WaitForOption.checkEvery(1, TimeUnit.SECONDS), * WaitForOption.timeout(3, TimeUnit.MINUTES)); - * if (completedJob != null && completedJob.status().error() == null) { + * if (completedJob != null && completedJob.getStatus().getError() == null) { * // Job completed successfully * } else { * // Handle error case @@ -492,7 +522,7 @@ public Job load(FormatOptions format, String sourceUri, JobOption... options) * try { * Job completedJob = job.waitFor(WaitForOption.checkEvery(1, TimeUnit.SECONDS), * WaitForOption.timeout(3, TimeUnit.MINUTES)); - * if (completedJob != null && completedJob.status().error() == null) { + * if (completedJob != null && completedJob.getStatus().getError() == null) { * // Job completed successfully * } else { * // Handle error case @@ -510,14 +540,22 @@ public Job load(FormatOptions format, String sourceUri, JobOption... options) */ public Job load(FormatOptions format, List sourceUris, JobOption... options) throws BigQueryException { - LoadJobConfiguration loadConfig = LoadJobConfiguration.of(tableId(), sourceUris, format); + LoadJobConfiguration loadConfig = LoadJobConfiguration.of(getTableId(), sourceUris, format); return bigquery.create(JobInfo.of(loadConfig), options); } /** * Returns the table's {@code BigQuery} object used to issue requests. */ + @Deprecated public BigQuery bigquery() { + return getBigquery(); + } + + /** + * Returns the table's {@code BigQuery} object used to issue requests. + */ + public BigQuery getBigquery() { return bigquery; } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TableDefinition.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TableDefinition.java index 2570c50373a7..ec947bfe9c79 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TableDefinition.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TableDefinition.java @@ -85,7 +85,7 @@ public abstract static class BuildernullOf(String.class)); return this; } @Override - Builder etag(String etag) { + Builder setEtag(String etag) { this.etag = etag; return this; } @Override + @Deprecated public Builder expirationTime(Long expirationTime) { + return setExpirationTime(expirationTime); + } + + @Override + public Builder setExpirationTime(Long expirationTime) { this.expirationTime = firstNonNull(expirationTime, Data.nullOf(Long.class)); return this; } @Override + @Deprecated public Builder friendlyName(String friendlyName) { + return setFriendlyName(friendlyName); + } + + @Override + public Builder setFriendlyName(String friendlyName) { this.friendlyName = firstNonNull(friendlyName, Data.nullOf(String.class)); return this; } @Override - Builder generatedId(String generatedId) { + Builder setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } @Override - Builder lastModifiedTime(Long lastModifiedTime) { + Builder setLastModifiedTime(Long lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; return this; } @Override - Builder selfLink(String selfLink) { + Builder setSelfLink(String selfLink) { this.selfLink = selfLink; return this; } @Override + @Deprecated public Builder tableId(TableId tableId) { + return setTableId(tableId); + } + + @Override + public Builder setTableId(TableId tableId) { this.tableId = checkNotNull(tableId); return this; } @Override + @Deprecated public Builder definition(TableDefinition definition) { + return setDefinition(definition); + } + + @Override + public Builder setDefinition(TableDefinition definition) { this.definition = checkNotNull(definition); return this; } @@ -239,14 +302,30 @@ public TableInfo build() { /** * Returns the hash of the table resource. */ + @Deprecated public String etag() { + return getEtag(); + } + + /** + * Returns the hash of the table resource. + */ + public String getEtag() { return etag; } /** * Returns the service-generated id for the table. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated id for the table. + */ + public String getGeneratedId() { return generatedId; } @@ -254,35 +333,76 @@ public String generatedId() { * Returns an URL that can be used to access the resource again. The returned URL can be used for * get or update requests. */ + @Deprecated public String selfLink() { + return getSelfLink(); + } + + /** + * Returns an URL that can be used to access the resource again. The returned URL can be used for + * get or update requests. + */ + public String getSelfLink() { return selfLink; } /** * Returns the table identity. */ + @Deprecated public TableId tableId() { + return getTableId(); + } + + /** + * Returns the table identity. + */ + public TableId getTableId() { return tableId; } /** * Returns a user-friendly name for the table. */ + @Deprecated public String friendlyName() { + return getFriendlyName(); + } + + /** + * Returns a user-friendly name for the table. + */ + public String getFriendlyName() { return Data.isNull(friendlyName) ? null : friendlyName; } /** * Returns a user-friendly description for the table. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns a user-friendly description for the table. + */ + public String getDescription() { return Data.isNull(description) ? null : description; } /** * Returns the time when this table was created, in milliseconds since the epoch. */ + @Deprecated public Long creationTime() { + return getCreationTime(); + } + + /** + * Returns the time when this table was created, in milliseconds since the epoch. + */ + public Long getCreationTime() { return creationTime; } @@ -290,14 +410,31 @@ public Long creationTime() { * Returns the time when this table expires, in milliseconds since the epoch. If not present, the * table will persist indefinitely. Expired tables will be deleted and their storage reclaimed. */ + @Deprecated public Long expirationTime() { + return getExpirationTime(); + } + + /** + * Returns the time when this table expires, in milliseconds since the epoch. If not present, the + * table will persist indefinitely. Expired tables will be deleted and their storage reclaimed. + */ + public Long getExpirationTime() { return Data.isNull(expirationTime) ? null : expirationTime; } /** * Returns the time when this table was last modified, in milliseconds since the epoch. */ + @Deprecated public Long lastModifiedTime() { + return getLastModifiedTime(); + } + + /** + * Returns the time when this table was last modified, in milliseconds since the epoch. + */ + public Long getLastModifiedTime() { return lastModifiedTime; } @@ -305,7 +442,16 @@ public Long lastModifiedTime() { * Returns the table definition. */ @SuppressWarnings("unchecked") + @Deprecated public T definition() { + return getDefinition(); + } + + /** + * Returns the table definition. + */ + @SuppressWarnings("unchecked") + public T getDefinition() { return (T) definition; } @@ -351,8 +497,19 @@ public boolean equals(Object obj) { * create a BigQuery view. Use {@link ExternalTableDefinition} to create a BigQuery a table backed * by external data. */ + @Deprecated public static Builder builder(TableId tableId, TableDefinition definition) { - return new BuilderImpl().tableId(tableId).definition(definition); + return newBuilder(tableId, definition); + } + + /** + * Returns a builder for a {@code TableInfo} object given table identity and definition. Use + * {@link StandardTableDefinition} to create simple BigQuery table. Use {@link ViewDefinition} to + * create a BigQuery view. Use {@link ExternalTableDefinition} to create a BigQuery a table backed + * by external data. + */ + public static Builder newBuilder(TableId tableId, TableDefinition definition) { + return new BuilderImpl().setTableId(tableId).setDefinition(definition); } /** @@ -362,11 +519,11 @@ public static Builder builder(TableId tableId, TableDefinition definition) { * by external data. */ public static TableInfo of(TableId tableId, TableDefinition definition) { - return builder(tableId, definition).build(); + return newBuilder(tableId, definition).build(); } TableInfo setProjectId(String projectId) { - return toBuilder().tableId(tableId().setProjectId(projectId)).build(); + return toBuilder().setTableId(getTableId().setProjectId(projectId)).build(); } Table toPb() { diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TimePartitioning.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TimePartitioning.java index 35e32ac49308..46f234104cee 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TimePartitioning.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TimePartitioning.java @@ -58,7 +58,16 @@ private TimePartitioning(Type type, Long expirationMs) { * Returns the time partitioning type. Currently, the only type supported is {@link Type#DAY}, * which will generate one partition per day based on data loading time. */ + @Deprecated public Type type() { + return getType(); + } + + /** + * Returns the time partitioning type. Currently, the only type supported is {@link Type#DAY}, + * which will generate one partition per day based on data loading time. + */ + public Type getType() { return type; } @@ -66,7 +75,16 @@ public Type type() { * Returns the number of milliseconds for which to keep the storage for a partition. When expired, * the storage for the partition is reclaimed. */ + @Deprecated public Long expirationMs() { + return getExpirationMs(); + } + + /** + * Returns the number of milliseconds for which to keep the storage for a partition. When expired, + * the storage for the partition is reclaimed. + */ + public Long getExpirationMs() { return expirationMs; } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/UserDefinedFunction.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/UserDefinedFunction.java index 36ac2c27485e..bbd32a432bbe 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/UserDefinedFunction.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/UserDefinedFunction.java @@ -68,7 +68,18 @@ public enum Type { this.content = content; } + /** + * Returns the type of user defined function. + */ + @Deprecated public Type type() { + return getType(); + } + + /** + * Returns the type of user defined function. + */ + public Type getType() { return type; } @@ -76,7 +87,16 @@ public Type type() { * If {@link #type()} is {@link Type#INLINE} this method returns a code blob. If {@link #type()} * is {@link Type#FROM_URI} the method returns a Google Cloud Storage URI (e.g. gs://bucket/path). */ + @Deprecated public String content() { + return getContent(); + } + + /** + * If {@link #type()} is {@link Type#INLINE} this method returns a code blob. If {@link #type()} + * is {@link Type#FROM_URI} the method returns a Google Cloud Storage URI (e.g. gs://bucket/path). + */ + public String getContent() { return content; } @@ -93,13 +113,13 @@ static final class InlineFunction extends UserDefinedFunction { @Override public String toString() { - return MoreObjects.toStringHelper(this).add("inlineCode", content()).toString(); + return MoreObjects.toStringHelper(this).add("inlineCode", getContent()).toString(); } @Override public com.google.api.services.bigquery.model.UserDefinedFunctionResource toPb() { return new com.google.api.services.bigquery.model.UserDefinedFunctionResource() - .setInlineCode(content()); + .setInlineCode(getContent()); } } @@ -116,13 +136,13 @@ static final class UriFunction extends UserDefinedFunction { @Override public String toString() { - return MoreObjects.toStringHelper(this).add("functionUri", content()).toString(); + return MoreObjects.toStringHelper(this).add("functionUri", getContent()).toString(); } @Override public com.google.api.services.bigquery.model.UserDefinedFunctionResource toPb() { return new com.google.api.services.bigquery.model.UserDefinedFunctionResource() - .setResourceUri(content()); + .setResourceUri(getContent()); } } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ViewDefinition.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ViewDefinition.java index 1d3a97ba616d..fe9d1d1e3396 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ViewDefinition.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/ViewDefinition.java @@ -70,7 +70,15 @@ private Builder(Table tablePb) { /** * Sets the query used to create the view. */ + @Deprecated public Builder query(String query) { + return setQuery(query); + } + + /** + * Sets the query used to create the view. + */ + public Builder setQuery(String query) { this.query = checkNotNull(query); return self(); } @@ -81,7 +89,18 @@ public Builder query(String query) { * @see User-Defined * Functions */ + @Deprecated public Builder userDefinedFunctions(List userDefinedFunctions) { + return setUserDefinedFunctions(userDefinedFunctions); + } + + /** + * Sets user defined functions that can be used by {@link #query()}. + * + * @see User-Defined + * Functions + */ + public Builder setUserDefinedFunctions(List userDefinedFunctions) { this.userDefinedFunctions = ImmutableList.copyOf(checkNotNull(userDefinedFunctions)); return self(); } @@ -92,7 +111,18 @@ public Builder userDefinedFunctions(List userDefinedFunctio * @see User-Defined * Functions */ + @Deprecated public Builder userDefinedFunctions(UserDefinedFunction... userDefinedFunctions) { + return setUserDefinedFunctions(userDefinedFunctions); + } + + /** + * Sets user defined functions that can be used by {@link #query()}. + * + * @see User-Defined + * Functions + */ + public Builder setUserDefinedFunctions(UserDefinedFunction... userDefinedFunctions) { this.userDefinedFunctions = ImmutableList.copyOf(userDefinedFunctions); return self(); } @@ -115,7 +145,15 @@ private ViewDefinition(Builder builder) { /** * Returns the query used to create the view. */ + @Deprecated public String query() { + return getQuery(); + } + + /** + * Returns the query used to create the view. + */ + public String getQuery() { return query; } @@ -126,7 +164,19 @@ public String query() { * @see User-Defined Functions * */ + @Deprecated public List userDefinedFunctions() { + return getUserDefinedFunctions(); + } + + /** + * Returns user defined functions that can be used by {@link #query()}. Returns {@code null} if + * not set. + * + * @see User-Defined Functions + * + */ + public List getUserDefinedFunctions() { return userDefinedFunctions; } @@ -176,8 +226,18 @@ Table toPb() { * * @param query the query used to generate the view */ + @Deprecated public static Builder builder(String query) { - return new Builder().query(query); + return newBuilder(query); + } + + /** + * Returns a builder for a BigQuery view definition. + * + * @param query the query used to generate the view + */ + public static Builder newBuilder(String query) { + return new Builder().setQuery(query); } /** @@ -186,8 +246,9 @@ public static Builder builder(String query) { * @param query the query used to generate the table * @param functions user-defined functions that can be used by the query */ + @Deprecated public static Builder builder(String query, List functions) { - return new Builder().type(Type.VIEW).userDefinedFunctions(functions).query(query); + return newBuilder(query, functions); } /** @@ -196,8 +257,29 @@ public static Builder builder(String query, List functions) * @param query the query used to generate the table * @param functions user-defined functions that can be used by the query */ + public static Builder newBuilder(String query, List functions) { + return newBuilder(query).setUserDefinedFunctions(functions); + } + + /** + * Returns a builder for a BigQuery view definition. + * + * @param query the query used to generate the table + * @param functions user-defined functions that can be used by the query + */ + @Deprecated public static Builder builder(String query, UserDefinedFunction... functions) { - return new Builder().type(Type.VIEW).userDefinedFunctions(functions).query(query); + return newBuilder(query, functions); + } + + /** + * Returns a builder for a BigQuery view definition. + * + * @param query the query used to generate the table + * @param functions user-defined functions that can be used by the query + */ + public static Builder newBuilder(String query, UserDefinedFunction... functions) { + return newBuilder(query).setUserDefinedFunctions(functions); } /** @@ -206,7 +288,7 @@ public static Builder builder(String query, UserDefinedFunction... functions) { * @param query the query used to generate the table */ public static ViewDefinition of(String query) { - return builder(query).build(); + return newBuilder(query).build(); } /** @@ -216,7 +298,7 @@ public static ViewDefinition of(String query) { * @param functions user-defined functions that can be used by the query */ public static ViewDefinition of(String query, List functions) { - return builder(query, functions).build(); + return newBuilder(query, functions).build(); } /** @@ -226,7 +308,7 @@ public static ViewDefinition of(String query, List function * @param functions user-defined functions that can be used by the query */ public static ViewDefinition of(String query, UserDefinedFunction... functions) { - return builder(query, functions).build(); + return newBuilder(query, functions).build(); } @SuppressWarnings("unchecked") diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/WriteChannelConfiguration.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/WriteChannelConfiguration.java index 354b4c9443db..6be6c084064d 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/WriteChannelConfiguration.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/WriteChannelConfiguration.java @@ -90,18 +90,18 @@ private Builder(com.google.api.services.bigquery.model.JobConfiguration configur || loadConfigurationPb.getFieldDelimiter() != null || loadConfigurationPb.getQuote() != null || loadConfigurationPb.getSkipLeadingRows() != null) { - CsvOptions.Builder builder = CsvOptions.builder() - .encoding(loadConfigurationPb.getEncoding()) - .fieldDelimiter(loadConfigurationPb.getFieldDelimiter()) - .quote(loadConfigurationPb.getQuote()); + CsvOptions.Builder builder = CsvOptions.newBuilder() + .setEncoding(loadConfigurationPb.getEncoding()) + .setFieldDelimiter(loadConfigurationPb.getFieldDelimiter()) + .setQuote(loadConfigurationPb.getQuote()); if (loadConfigurationPb.getAllowJaggedRows() != null) { - builder.allowJaggedRows(loadConfigurationPb.getAllowJaggedRows()); + builder.setAllowJaggedRows(loadConfigurationPb.getAllowJaggedRows()); } if (loadConfigurationPb.getAllowQuotedNewlines() != null) { - builder.allowQuotedNewLines(loadConfigurationPb.getAllowQuotedNewlines()); + builder.setAllowQuotedNewLines(loadConfigurationPb.getAllowQuotedNewlines()); } if (loadConfigurationPb.getSkipLeadingRows() != null) { - builder.skipLeadingRows(loadConfigurationPb.getSkipLeadingRows()); + builder.setSkipLeadingRows(loadConfigurationPb.getSkipLeadingRows()); } this.formatOptions = builder.build(); } @@ -114,49 +114,97 @@ private Builder(com.google.api.services.bigquery.model.JobConfiguration configur } @Override + @Deprecated public Builder destinationTable(TableId destinationTable) { + return setDestinationTable(destinationTable); + } + + @Override + public Builder setDestinationTable(TableId destinationTable) { this.destinationTable = destinationTable; return this; } @Override + @Deprecated public Builder createDisposition(CreateDisposition createDisposition) { + return setCreateDisposition(createDisposition); + } + + @Override + public Builder setCreateDisposition(CreateDisposition createDisposition) { this.createDisposition = createDisposition; return this; } @Override + @Deprecated public Builder writeDisposition(WriteDisposition writeDisposition) { + return setWriteDisposition(writeDisposition); + } + + @Override + public Builder setWriteDisposition(WriteDisposition writeDisposition) { this.writeDisposition = writeDisposition; return this; } @Override + @Deprecated public Builder formatOptions(FormatOptions formatOptions) { + return setFormatOptions(formatOptions); + } + + @Override + public Builder setFormatOptions(FormatOptions formatOptions) { this.formatOptions = formatOptions; return this; } @Override + @Deprecated public Builder maxBadRecords(Integer maxBadRecords) { + return setMaxBadRecords(maxBadRecords); + } + + @Override + public Builder setMaxBadRecords(Integer maxBadRecords) { this.maxBadRecords = maxBadRecords; return this; } @Override + @Deprecated public Builder schema(Schema schema) { + return setSchema(schema); + } + + @Override + public Builder setSchema(Schema schema) { this.schema = schema; return this; } @Override + @Deprecated public Builder ignoreUnknownValues(Boolean ignoreUnknownValues) { + return setIgnoreUnknownValues(ignoreUnknownValues); + } + + @Override + public Builder setIgnoreUnknownValues(Boolean ignoreUnknownValues) { this.ignoreUnknownValues = ignoreUnknownValues; return this; } @Override + @Deprecated public Builder projectionFields(List projectionFields) { + return setProjectionFields(projectionFields); + } + + @Override + public Builder setProjectionFields(List projectionFields) { this.projectionFields = projectionFields != null ? ImmutableList.copyOf(projectionFields) : null; return this; @@ -180,38 +228,80 @@ protected WriteChannelConfiguration(Builder builder) { } @Override + @Deprecated public TableId destinationTable() { + return getDestinationTable(); + } + + @Override + public TableId getDestinationTable() { return destinationTable; } @Override + @Deprecated public CreateDisposition createDisposition() { + return this.getCreateDisposition(); + } + + @Override + public CreateDisposition getCreateDisposition() { return this.createDisposition; } @Override + @Deprecated public WriteDisposition writeDisposition() { + return getWriteDisposition(); + } + + @Override + public WriteDisposition getWriteDisposition() { return writeDisposition; } @Override + @Deprecated public CsvOptions csvOptions() { + return getCsvOptions(); + } + + @Override + public CsvOptions getCsvOptions() { return formatOptions instanceof CsvOptions ? (CsvOptions) formatOptions : null; } @Override + @Deprecated public Integer maxBadRecords() { + return getMaxBadRecords(); + } + + @Override + public Integer getMaxBadRecords() { return maxBadRecords; } @Override + @Deprecated public Schema schema() { + return getSchema(); + } + + @Override + public Schema getSchema() { return schema; } @Override + @Deprecated public String format() { - return formatOptions != null ? formatOptions.type() : null; + return getFormat(); + } + + @Override + public String getFormat() { + return formatOptions != null ? formatOptions.getType() : null; } @Override @@ -220,7 +310,13 @@ public Boolean ignoreUnknownValues() { } @Override + @Deprecated public List projectionFields() { + return getProjectionFields(); + } + + @Override + public List getProjectionFields() { return projectionFields; } @@ -260,7 +356,7 @@ public int hashCode() { } WriteChannelConfiguration setProjectId(String projectId) { - return toBuilder().destinationTable(destinationTable().setProjectId(projectId)).build(); + return toBuilder().setDestinationTable(getDestinationTable().setProjectId(projectId)).build(); } com.google.api.services.bigquery.model.JobConfiguration toPb() { @@ -272,23 +368,23 @@ com.google.api.services.bigquery.model.JobConfiguration toPb() { if (writeDisposition != null) { loadConfigurationPb.setWriteDisposition(writeDisposition.toString()); } - if (csvOptions() != null) { - CsvOptions csvOptions = csvOptions(); - loadConfigurationPb.setFieldDelimiter(csvOptions.fieldDelimiter()) + if (getCsvOptions() != null) { + CsvOptions csvOptions = getCsvOptions(); + loadConfigurationPb.setFieldDelimiter(csvOptions.getFieldDelimiter()) .setAllowJaggedRows(csvOptions.allowJaggedRows()) .setAllowQuotedNewlines(csvOptions.allowQuotedNewLines()) - .setEncoding(csvOptions.encoding()) - .setQuote(csvOptions.quote()); - if (csvOptions.skipLeadingRows() != null) { + .setEncoding(csvOptions.getEncoding()) + .setQuote(csvOptions.getQuote()); + if (csvOptions.getSkipLeadingRows() != null) { // todo(mziccard) remove checked cast or comment when #1044 is closed - loadConfigurationPb.setSkipLeadingRows(Ints.checkedCast(csvOptions.skipLeadingRows())); + loadConfigurationPb.setSkipLeadingRows(Ints.checkedCast(csvOptions.getSkipLeadingRows())); } } if (schema != null) { loadConfigurationPb.setSchema(schema.toPb()); } if (formatOptions != null) { - loadConfigurationPb.setSourceFormat(formatOptions.type()); + loadConfigurationPb.setSourceFormat(formatOptions.getType()); } loadConfigurationPb.setMaxBadRecords(maxBadRecords); loadConfigurationPb.setIgnoreUnknownValues(ignoreUnknownValues); @@ -305,28 +401,44 @@ static WriteChannelConfiguration fromPb( /** * Creates a builder for a BigQuery Load Configuration given the destination table. */ + @Deprecated public static Builder builder(TableId destinationTable) { - return new Builder().destinationTable(destinationTable); + return newBuilder(destinationTable); + } + + /** + * Creates a builder for a BigQuery Load Configuration given the destination table. + */ + public static Builder newBuilder(TableId destinationTable) { + return new Builder().setDestinationTable(destinationTable); } /** * Creates a builder for a BigQuery Load Configuration given the destination table and format. */ + @Deprecated public static Builder builder(TableId destinationTable, FormatOptions format) { - return builder(destinationTable).formatOptions(format); + return newBuilder(destinationTable, format); + } + + /** + * Creates a builder for a BigQuery Load Configuration given the destination table and format. + */ + public static Builder newBuilder(TableId destinationTable, FormatOptions format) { + return newBuilder(destinationTable).setFormatOptions(format); } /** * Returns a BigQuery Load Configuration for the given destination table. */ public static WriteChannelConfiguration of(TableId destinationTable) { - return builder(destinationTable).build(); + return newBuilder(destinationTable).build(); } /** * Returns a BigQuery Load Configuration for the given destination table and format. */ public static WriteChannelConfiguration of(TableId destinationTable, FormatOptions format) { - return builder(destinationTable).formatOptions(format).build(); + return newBuilder(destinationTable).setFormatOptions(format).build(); } } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java index d844ad56235a..05df90b4dda4 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java @@ -30,7 +30,7 @@ /** * Utility to create a remote BigQuery configuration for testing. BigQuery options can be obtained - * via the {@link #options()} method. Returned options have custom + * via the {@link #getOptions()} method. Returned options have custom * {@link BigQueryOptions#retryParams()}: {@link RetryParams#retryMaxAttempts()} is {@code 10}, * {@link RetryParams#retryMinAttempts()} is {@code 6}, {@link RetryParams#maxRetryDelayMillis()} is * {@code 30000}, {@link RetryParams#totalRetryPeriodMillis()} is {@code 120000} and @@ -51,10 +51,18 @@ private RemoteBigQueryHelper(BigQueryOptions options) { /** * Returns a {@link BigQueryOptions} object to be used for testing. */ + @Deprecated public BigQueryOptions options() { return options; } + /** + * Returns a {@link BigQueryOptions} object to be used for testing. + */ + public BigQueryOptions getOptions() { + return options; + } + /** * Deletes a dataset, even if non-empty. * diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/package-info.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/package-info.java index 87761312d8b2..29fc8243cbf0 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/package-info.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/package-info.java @@ -22,9 +22,9 @@ *

Before the test: *

 {@code
  * RemoteBigQueryHelper bigqueryHelper = RemoteBigQueryHelper.create();
- * BigQuery bigquery = bigqueryHelper.options().service();
+ * BigQuery bigquery = bigqueryHelper.getOptions().service();
  * String dataset = RemoteBigQueryHelper.generateDatasetName();
- * bigquery.create(DatasetInfo.builder(dataset).build());
+ * bigquery.create(DatasetInfo.newBuilder(dataset).build());
  * } 
* *

After the test: diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/AclTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/AclTest.java index 51b5e1ad496e..c960f1e425cd 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/AclTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/AclTest.java @@ -33,6 +33,15 @@ public class AclTest { @Test public void testDomainEntity() { + Domain entity = new Domain("d1"); + assertEquals("d1", entity.getDomain()); + assertEquals(Type.DOMAIN, entity.getType()); + Dataset.Access pb = entity.toPb(); + assertEquals(entity, Entity.fromPb(pb)); + } + + @Test + public void testDomainEntityDeprecated() { Domain entity = new Domain("d1"); assertEquals("d1", entity.domain()); assertEquals(Type.DOMAIN, entity.type()); @@ -42,6 +51,15 @@ public void testDomainEntity() { @Test public void testGroupEntity() { + Group entity = new Group("g1"); + assertEquals("g1", entity.getIdentifier()); + assertEquals(Type.GROUP, entity.getType()); + Dataset.Access pb = entity.toPb(); + assertEquals(entity, Entity.fromPb(pb)); + } + + @Test + public void testGroupEntityDeprecated() { Group entity = new Group("g1"); assertEquals("g1", entity.identifier()); assertEquals(Type.GROUP, entity.type()); @@ -51,6 +69,18 @@ public void testGroupEntity() { @Test public void testSpecialGroupEntity() { + Group entity = Group.ofAllAuthenticatedUsers(); + assertEquals("allAuthenticatedUsers", entity.getIdentifier()); + entity = Group.ofProjectWriters(); + assertEquals("projectWriters", entity.getIdentifier()); + entity = Group.ofProjectReaders(); + assertEquals("projectReaders", entity.getIdentifier()); + entity = Group.ofProjectOwners(); + assertEquals("projectOwners", entity.getIdentifier()); + } + + @Test + public void testSpecialGroupEntityDeprecated() { Group entity = Group.ofAllAuthenticatedUsers(); assertEquals("allAuthenticatedUsers", entity.identifier()); entity = Group.ofProjectWriters(); @@ -63,6 +93,15 @@ public void testSpecialGroupEntity() { @Test public void testUserEntity() { + User entity = new User("u1"); + assertEquals("u1", entity.getEmail()); + assertEquals(Type.USER, entity.getType()); + Dataset.Access pb = entity.toPb(); + assertEquals(entity, Entity.fromPb(pb)); + } + + @Test + public void testUserEntityDeprecated() { User entity = new User("u1"); assertEquals("u1", entity.email()); assertEquals(Type.USER, entity.type()); @@ -72,6 +111,16 @@ public void testUserEntity() { @Test public void testViewEntity() { + TableId viewId = TableId.of("project", "dataset", "view"); + View entity = new View(viewId); + assertEquals(viewId, entity.getId()); + assertEquals(Type.VIEW, entity.getType()); + Dataset.Access pb = entity.toPb(); + assertEquals(entity, Entity.fromPb(pb)); + } + + @Test + public void testViewEntityDeprecated() { TableId viewId = TableId.of("project", "dataset", "view"); View entity = new View(viewId); assertEquals(viewId, entity.id()); @@ -82,6 +131,19 @@ public void testViewEntity() { @Test public void testOf() { + Acl acl = Acl.of(Group.ofAllAuthenticatedUsers(), Role.READER); + assertEquals(Group.ofAllAuthenticatedUsers(), acl.getEntity()); + assertEquals(Role.READER, acl.getRole()); + Dataset.Access pb = acl.toPb(); + assertEquals(acl, Acl.fromPb(pb)); + View view = new View(TableId.of("project", "dataset", "view")); + acl = Acl.of(view); + assertEquals(view, acl.getEntity()); + assertEquals(null, acl.getRole()); + } + + @Test + public void testOfDeprecated() { Acl acl = Acl.of(Group.ofAllAuthenticatedUsers(), Role.READER); assertEquals(Group.ofAllAuthenticatedUsers(), acl.entity()); assertEquals(Role.READER, acl.role()); diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryErrorTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryErrorTest.java index c63095b96528..3dfb0576dd33 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryErrorTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryErrorTest.java @@ -33,13 +33,25 @@ public class BigQueryErrorTest { @Test public void testConstructor() { + assertEquals(REASON, ERROR.getReason()); + assertEquals(LOCATION, ERROR.getLocation()); + assertEquals(DEBUG_INFO, ERROR.getDebugInfo()); + assertEquals(MESSAGE, ERROR.getMessage()); + assertEquals(REASON, ERROR_INCOMPLETE.getReason()); + assertEquals(LOCATION, ERROR_INCOMPLETE.getLocation()); + assertEquals(null, ERROR_INCOMPLETE.getDebugInfo()); + assertEquals(MESSAGE, ERROR_INCOMPLETE.getMessage()); + } + + @Test + public void testConstructorDeprecated() { assertEquals(REASON, ERROR.reason()); assertEquals(LOCATION, ERROR.location()); - assertEquals(DEBUG_INFO, ERROR.debugInfo()); + assertEquals(DEBUG_INFO, ERROR.getDebugInfo()); assertEquals(MESSAGE, ERROR.message()); assertEquals(REASON, ERROR_INCOMPLETE.reason()); assertEquals(LOCATION, ERROR_INCOMPLETE.location()); - assertEquals(null, ERROR_INCOMPLETE.debugInfo()); + assertEquals(null, ERROR_INCOMPLETE.getDebugInfo()); assertEquals(MESSAGE, ERROR_INCOMPLETE.message()); } @@ -53,9 +65,9 @@ private void compareBigQueryError(BigQueryError expected, BigQueryError value) { assertEquals(expected, value); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); - assertEquals(expected.reason(), value.reason()); - assertEquals(expected.location(), value.location()); - assertEquals(expected.debugInfo(), value.debugInfo()); - assertEquals(expected.message(), value.message()); + assertEquals(expected.getReason(), value.getReason()); + assertEquals(expected.getLocation(), value.getLocation()); + assertEquals(expected.getDebugInfo(), value.getDebugInfo()); + assertEquals(expected.getMessage(), value.getMessage()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryExceptionTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryExceptionTest.java index e97606bfc463..059207df2fe9 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryExceptionTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryExceptionTest.java @@ -42,6 +42,7 @@ public void testBigqueryException() { assertEquals(500, exception.code()); assertEquals("message", exception.getMessage()); assertNull(exception.reason()); + assertNull(exception.getError()); assertNull(exception.error()); assertTrue(exception.retryable()); assertTrue(exception.idempotent()); @@ -50,6 +51,7 @@ public void testBigqueryException() { assertEquals(502, exception.code()); assertEquals("message", exception.getMessage()); assertNull(exception.reason()); + assertNull(exception.getError()); assertNull(exception.error()); assertTrue(exception.retryable()); assertTrue(exception.idempotent()); @@ -58,6 +60,7 @@ public void testBigqueryException() { assertEquals(503, exception.code()); assertEquals("message", exception.getMessage()); assertNull(exception.reason()); + assertNull(exception.getError()); assertNull(exception.error()); assertTrue(exception.retryable()); assertTrue(exception.idempotent()); @@ -66,6 +69,7 @@ public void testBigqueryException() { assertEquals(504, exception.code()); assertEquals("message", exception.getMessage()); assertNull(exception.reason()); + assertNull(exception.getError()); assertNull(exception.error()); assertTrue(exception.retryable()); assertTrue(exception.idempotent()); @@ -74,6 +78,7 @@ public void testBigqueryException() { assertEquals(400, exception.code()); assertEquals("message", exception.getMessage()); assertNull(exception.reason()); + assertNull(exception.getError()); assertNull(exception.error()); assertFalse(exception.retryable()); assertTrue(exception.idempotent()); @@ -83,6 +88,7 @@ public void testBigqueryException() { assertEquals(504, exception.code()); assertEquals("message", exception.getMessage()); assertEquals("reason", exception.reason()); + assertEquals(error, exception.getError()); assertEquals(error, exception.error()); assertTrue(exception.retryable()); assertTrue(exception.idempotent()); @@ -101,6 +107,7 @@ public void testBigqueryException() { assertEquals(504, exception.code()); assertEquals("message", exception.getMessage()); assertNull(exception.reason()); + assertNull(exception.getError()); assertNull(exception.error()); assertTrue(exception.retryable()); assertTrue(exception.idempotent()); diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryImplTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryImplTest.java index 32457c2bb051..6648b0d17508 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryImplTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryImplTest.java @@ -72,35 +72,37 @@ public class BigQueryImplTest { private static final List ACCESS_RULES_WITH_PROJECT = ImmutableList.of( Acl.of(Acl.Group.ofAllAuthenticatedUsers(), Acl.Role.READER), Acl.of(new Acl.View(TableId.of(PROJECT, "dataset", "table")))); - private static final DatasetInfo DATASET_INFO = DatasetInfo.builder(DATASET) - .acl(ACCESS_RULES) - .description("description") - .build(); - private static final DatasetInfo DATASET_INFO_WITH_PROJECT = DatasetInfo.builder(PROJECT, DATASET) - .acl(ACCESS_RULES_WITH_PROJECT) - .description("description") - .build(); - private static final DatasetInfo OTHER_DATASET_INFO = DatasetInfo.builder(PROJECT, OTHER_DATASET) - .acl(ACCESS_RULES) - .description("other description") + private static final DatasetInfo DATASET_INFO = DatasetInfo.newBuilder(DATASET) + .setAcl(ACCESS_RULES) + .setDescription("description") .build(); + private static final DatasetInfo DATASET_INFO_WITH_PROJECT = + DatasetInfo.newBuilder(PROJECT, DATASET) + .setAcl(ACCESS_RULES_WITH_PROJECT) + .setDescription("description") + .build(); + private static final DatasetInfo OTHER_DATASET_INFO = + DatasetInfo.newBuilder(PROJECT, OTHER_DATASET) + .setAcl(ACCESS_RULES) + .setDescription("other description") + .build(); private static final TableId TABLE_ID = TableId.of(DATASET, TABLE); private static final TableId OTHER_TABLE_ID = TableId.of(PROJECT, DATASET, OTHER_TABLE); private static final TableId TABLE_ID_WITH_PROJECT = TableId.of(PROJECT, DATASET, TABLE); private static final Field FIELD_SCHEMA1 = - Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) - .description("FieldDescription1") + Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) + .setDescription("FieldDescription1") .build(); private static final Field FIELD_SCHEMA2 = - Field.builder("IntegerField", Field.Type.integer()) - .mode(Field.Mode.REPEATED) - .description("FieldDescription2") + Field.newBuilder("IntegerField", Field.Type.integer()) + .setMode(Field.Mode.REPEATED) + .setDescription("FieldDescription2") .build(); private static final Field FIELD_SCHEMA3 = - Field.builder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) - .mode(Field.Mode.REQUIRED) - .description("FieldDescription3") + Field.newBuilder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) + .setMode(Field.Mode.REQUIRED) + .setDescription("FieldDescription3") .build(); private static final Schema TABLE_SCHEMA = Schema.of(FIELD_SCHEMA1, FIELD_SCHEMA2, FIELD_SCHEMA3); private static final StandardTableDefinition TABLE_DEFINITION = @@ -126,14 +128,14 @@ public class BigQueryImplTest { private static final JobInfo COMPLETE_COPY_JOB = JobInfo.of(JobId.of(PROJECT, JOB), COPY_JOB_CONFIGURATION_WITH_PROJECT); private static final QueryJobConfiguration QUERY_JOB_CONFIGURATION = - QueryJobConfiguration.builder("SQL") - .defaultDataset(DatasetId.of(DATASET)) - .destinationTable(TABLE_ID) + QueryJobConfiguration.newBuilder("SQL") + .setDefaultDataset(DatasetId.of(DATASET)) + .setDestinationTable(TABLE_ID) .build(); private static final QueryJobConfiguration QUERY_JOB_CONFIGURATION_WITH_PROJECT = - QueryJobConfiguration.builder("SQL") - .defaultDataset(DatasetId.of(PROJECT, DATASET)) - .destinationTable(TABLE_ID_WITH_PROJECT) + QueryJobConfiguration.newBuilder("SQL") + .setDefaultDataset(DatasetId.of(PROJECT, DATASET)) + .setDestinationTable(TABLE_ID_WITH_PROJECT) .build(); private static final JobInfo QUERY_JOB = JobInfo.of(QUERY_JOB_CONFIGURATION); private static final JobInfo COMPLETE_QUERY_JOB = @@ -149,15 +151,15 @@ public class BigQueryImplTest { private static final TableCell INTEGER_FIELD = new TableCell().setV("1"); private static final TableRow TABLE_ROW = new TableRow().setF(ImmutableList.of(BOOLEAN_FIELD, INTEGER_FIELD)); - private static final QueryRequest QUERY_REQUEST = QueryRequest.builder("SQL") - .pageSize(42L) - .useQueryCache(false) - .defaultDataset(DatasetId.of(DATASET)) + private static final QueryRequest QUERY_REQUEST = QueryRequest.newBuilder("SQL") + .setPageSize(42L) + .setUseQueryCache(false) + .setDefaultDataset(DatasetId.of(DATASET)) .build(); - private static final QueryRequest QUERY_REQUEST_WITH_PROJECT = QueryRequest.builder("SQL") - .pageSize(42L) - .useQueryCache(false) - .defaultDataset(DatasetId.of(PROJECT, DATASET)) + private static final QueryRequest QUERY_REQUEST_WITH_PROJECT = QueryRequest.newBuilder("SQL") + .setPageSize(42L) + .setUseQueryCache(false) + .setDefaultDataset(DatasetId.of(PROJECT, DATASET)) .build(); private static final String CURSOR = "cursor"; private static final TableCell CELL_PB1 = new TableCell().setV("Value1"); @@ -310,7 +312,7 @@ public void testCreateDatasetWithSelectedFields() { EasyMock.replay(bigqueryRpcMock); bigquery = options.service(); Dataset dataset = bigquery.create(DATASET_INFO, DATASET_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(DATASET_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(DATASET_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("datasetReference")); assertTrue(selector.contains("access")); assertTrue(selector.contains("etag")); @@ -361,7 +363,7 @@ public void testGetDatasetWithSelectedFields() { EasyMock.replay(bigqueryRpcMock); bigquery = options.service(); Dataset dataset = bigquery.getDataset(DATASET, DATASET_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(DATASET_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(DATASET_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("datasetReference")); assertTrue(selector.contains("access")); assertTrue(selector.contains("etag")); @@ -470,7 +472,7 @@ public void testDeleteDatasetWithOptions() { @Test public void testUpdateDataset() { DatasetInfo updatedDatasetInfo = DATASET_INFO.setProjectId(OTHER_PROJECT).toBuilder() - .description("newDescription") + .setDescription("newDescription") .build(); EasyMock.expect(bigqueryRpcMock.patch(updatedDatasetInfo.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(updatedDatasetInfo.toPb()); @@ -483,9 +485,10 @@ public void testUpdateDataset() { @Test public void testUpdateDatasetWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - DatasetInfo updatedDatasetInfo = DATASET_INFO.toBuilder().description("newDescription").build(); + DatasetInfo updatedDatasetInfo = + DATASET_INFO.toBuilder().setDescription("newDescription").build(); DatasetInfo updatedDatasetInfoWithProject = DATASET_INFO_WITH_PROJECT.toBuilder() - .description("newDescription") + .setDescription("newDescription") .build(); EasyMock.expect( bigqueryRpcMock.patch(eq(updatedDatasetInfoWithProject.toPb()), capture(capturedOptions))) @@ -493,7 +496,7 @@ public void testUpdateDatasetWithSelectedFields() { EasyMock.replay(bigqueryRpcMock); bigquery = options.service(); Dataset dataset = bigquery.update(updatedDatasetInfo, DATASET_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(DATASET_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(DATASET_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("datasetReference")); assertTrue(selector.contains("access")); assertTrue(selector.contains("etag")); @@ -522,7 +525,7 @@ public void testCreateTableWithSelectedFields() { EasyMock.replay(bigqueryRpcMock); bigquery = options.service(); Table table = bigquery.create(TABLE_INFO, TABLE_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(TABLE_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(TABLE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("tableReference")); assertTrue(selector.contains("schema")); assertTrue(selector.contains("etag")); @@ -571,7 +574,7 @@ public void testGetTableWithSelectedFields() { EasyMock.replay(bigqueryRpcMock); bigquery = options.service(); Table table = bigquery.getTable(TABLE_ID, TABLE_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(TABLE_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(TABLE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("tableReference")); assertTrue(selector.contains("schema")); assertTrue(selector.contains("etag")); @@ -670,7 +673,7 @@ public void testDeleteTableFromTableIdWithProject() { @Test public void testUpdateTable() { TableInfo updatedTableInfo = TABLE_INFO.setProjectId(OTHER_PROJECT).toBuilder() - .description("newDescription") + .setDescription("newDescription") .build(); EasyMock.expect(bigqueryRpcMock.patch(updatedTableInfo.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(updatedTableInfo.toPb()); @@ -683,16 +686,16 @@ public void testUpdateTable() { @Test public void testUpdateTableWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - TableInfo updatedTableInfo = TABLE_INFO.toBuilder().description("newDescription").build(); + TableInfo updatedTableInfo = TABLE_INFO.toBuilder().setDescription("newDescription").build(); TableInfo updatedTableInfoWithProject = TABLE_INFO_WITH_PROJECT.toBuilder() - .description("newDescription") + .setDescription("newDescription") .build(); EasyMock.expect(bigqueryRpcMock.patch(eq(updatedTableInfoWithProject.toPb()), capture(capturedOptions))).andReturn(updatedTableInfoWithProject.toPb()); EasyMock.replay(bigqueryRpcMock); bigquery = options.service(); Table table = bigquery.update(updatedTableInfo, TABLE_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(TABLE_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(TABLE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("tableReference")); assertTrue(selector.contains("schema")); assertTrue(selector.contains("etag")); @@ -709,18 +712,18 @@ public void testInsertAll() { new RowToInsert("row1", row1), new RowToInsert("row2", row2) ); - InsertAllRequest request = InsertAllRequest.builder(TABLE_ID) - .rows(rows) - .skipInvalidRows(false) - .ignoreUnknownValues(true) - .templateSuffix("suffix") + InsertAllRequest request = InsertAllRequest.newBuilder(TABLE_ID) + .setRows(rows) + .setSkipInvalidRows(false) + .setIgnoreUnknownValues(true) + .setTemplateSuffix("suffix") .build(); TableDataInsertAllRequest requestPb = new TableDataInsertAllRequest().setRows( Lists.transform(rows, new Function() { @Override public TableDataInsertAllRequest.Rows apply(RowToInsert rowToInsert) { - return new TableDataInsertAllRequest.Rows().setInsertId(rowToInsert.id()) - .setJson(rowToInsert.content()); + return new TableDataInsertAllRequest.Rows().setInsertId(rowToInsert.getId()) + .setJson(rowToInsert.getContent()); } })).setSkipInvalidRows(false).setIgnoreUnknownValues(true).setTemplateSuffix("suffix"); TableDataInsertAllResponse responsePb = new TableDataInsertAllResponse().setInsertErrors( @@ -731,10 +734,10 @@ public TableDataInsertAllRequest.Rows apply(RowToInsert rowToInsert) { EasyMock.replay(bigqueryRpcMock); bigquery = options.service(); InsertAllResponse response = bigquery.insertAll(request); - assertNotNull(response.errorsFor(0L)); - assertNull(response.errorsFor(1L)); - assertEquals(1, response.errorsFor(0L).size()); - assertEquals("ErrorMessage", response.errorsFor(0L).get(0).message()); + assertNotNull(response.getErrorsFor(0L)); + assertNull(response.getErrorsFor(1L)); + assertEquals(1, response.getErrorsFor(0L).size()); + assertEquals("ErrorMessage", response.getErrorsFor(0L).get(0).getMessage()); } @Test @@ -746,18 +749,18 @@ public void testInsertAllWithProject() { new RowToInsert("row2", row2) ); TableId tableId = TableId.of(OTHER_PROJECT, DATASET, TABLE); - InsertAllRequest request = InsertAllRequest.builder(tableId) - .rows(rows) - .skipInvalidRows(false) - .ignoreUnknownValues(true) - .templateSuffix("suffix") + InsertAllRequest request = InsertAllRequest.newBuilder(tableId) + .setRows(rows) + .setSkipInvalidRows(false) + .setIgnoreUnknownValues(true) + .setTemplateSuffix("suffix") .build(); TableDataInsertAllRequest requestPb = new TableDataInsertAllRequest().setRows( Lists.transform(rows, new Function() { @Override public TableDataInsertAllRequest.Rows apply(RowToInsert rowToInsert) { - return new TableDataInsertAllRequest.Rows().setInsertId(rowToInsert.id()) - .setJson(rowToInsert.content()); + return new TableDataInsertAllRequest.Rows().setInsertId(rowToInsert.getId()) + .setJson(rowToInsert.getContent()); } })).setSkipInvalidRows(false).setIgnoreUnknownValues(true).setTemplateSuffix("suffix"); TableDataInsertAllResponse responsePb = new TableDataInsertAllResponse().setInsertErrors( @@ -768,10 +771,10 @@ public TableDataInsertAllRequest.Rows apply(RowToInsert rowToInsert) { EasyMock.replay(bigqueryRpcMock); bigquery = options.service(); InsertAllResponse response = bigquery.insertAll(request); - assertNotNull(response.errorsFor(0L)); - assertNull(response.errorsFor(1L)); - assertEquals(1, response.errorsFor(0L).size()); - assertEquals("ErrorMessage", response.errorsFor(0L).get(0).message()); + assertNotNull(response.getErrorsFor(0L)); + assertNull(response.getErrorsFor(1L)); + assertEquals(1, response.getErrorsFor(0L).size()); + assertEquals("ErrorMessage", response.getErrorsFor(0L).get(0).getMessage()); } @Test @@ -875,7 +878,7 @@ public void testCreateJobWithSelectedFields() { bigquery = options.service(); Job job = bigquery.create(QUERY_JOB, JOB_OPTION_FIELDS); assertEquals(new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_QUERY_JOB)), job); - String selector = (String) capturedOptions.getValue().get(JOB_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(JOB_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("jobReference")); assertTrue(selector.contains("configuration")); assertTrue(selector.contains("user_email")); @@ -884,8 +887,8 @@ public void testCreateJobWithSelectedFields() { @Test public void testCreateJobWithProjectId() { - JobInfo jobInfo = JobInfo.builder(QUERY_JOB_CONFIGURATION.setProjectId(OTHER_PROJECT)) - .jobId(JobId.of(OTHER_PROJECT, JOB)) + JobInfo jobInfo = JobInfo.newBuilder(QUERY_JOB_CONFIGURATION.setProjectId(OTHER_PROJECT)) + .setJobId(JobId.of(OTHER_PROJECT, JOB)) .build(); Capture> capturedOptions = Capture.newInstance(); EasyMock.expect(bigqueryRpcMock.create(eq(jobInfo.toPb()), capture(capturedOptions))) @@ -894,7 +897,7 @@ public void testCreateJobWithProjectId() { bigquery = options.service(); Job job = bigquery.create(jobInfo, JOB_OPTION_FIELDS); assertEquals(new Job(bigquery, new JobInfo.BuilderImpl(jobInfo)), job); - String selector = (String) capturedOptions.getValue().get(JOB_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(JOB_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("jobReference")); assertTrue(selector.contains("configuration")); assertTrue(selector.contains("user_email")); @@ -997,7 +1000,7 @@ public com.google.api.services.bigquery.model.Job apply(Job job) { Page page = bigquery.listJobs(JOB_LIST_OPTION_FIELD); assertEquals(CURSOR, page.nextPageCursor()); assertArrayEquals(jobList.toArray(), Iterables.toArray(page.values(), Job.class)); - String selector = (String) capturedOptions.getValue().get(JOB_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(JOB_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("nextPageToken,jobs(")); assertTrue(selector.contains("configuration")); assertTrue(selector.contains("jobReference")); @@ -1044,13 +1047,13 @@ public void testQueryRequest() { EasyMock.replay(bigqueryRpcMock); bigquery = options.service(); QueryResponse response = bigquery.query(QUERY_REQUEST); - assertNull(response.etag()); - assertNull(response.result()); - assertEquals(queryJob, response.jobId()); + assertNull(response.getEtag()); + assertNull(response.getResult()); + assertEquals(queryJob, response.getJobId()); assertEquals(false, response.jobCompleted()); - assertEquals(ImmutableList.of(), response.executionErrors()); + assertEquals(ImmutableList.of(), response.getExecutionErrors()); assertFalse(response.hasErrors()); - assertEquals(null, response.result()); + assertEquals(null, response.getResult()); } @Test @@ -1069,20 +1072,20 @@ public void testQueryRequestCompleted() { EasyMock.replay(bigqueryRpcMock); bigquery = options.service(); QueryResponse response = bigquery.query(QUERY_REQUEST); - assertNull(response.etag()); - assertEquals(queryJob, response.jobId()); + assertNull(response.getEtag()); + assertEquals(queryJob, response.getJobId()); assertEquals(true, response.jobCompleted()); - assertEquals(false, response.result().cacheHit()); - assertEquals(ImmutableList.of(), response.executionErrors()); + assertEquals(false, response.getResult().cacheHit()); + assertEquals(ImmutableList.of(), response.getExecutionErrors()); assertFalse(response.hasErrors()); - assertEquals(null, response.result().schema()); - assertEquals(42L, response.result().totalBytesProcessed()); - assertEquals(1L, response.result().totalRows()); - for (List row : response.result().values()) { - assertEquals(false, row.get(0).booleanValue()); - assertEquals(1L, row.get(1).longValue()); + assertEquals(null, response.getResult().getSchema()); + assertEquals(42L, response.getResult().getTotalBytesProcessed()); + assertEquals(1L, response.getResult().getTotalRows()); + for (List row : response.getResult().values()) { + assertEquals(false, row.get(0).getBooleanValue()); + assertEquals(1L, row.get(1).getLongValue()); } - assertEquals(CURSOR, response.result().nextPageCursor()); + assertEquals(CURSOR, response.getResult().nextPageCursor()); } @Test @@ -1102,20 +1105,20 @@ public void testGetQueryResults() { EasyMock.replay(bigqueryRpcMock); bigquery = options.service(); QueryResponse response = bigquery.getQueryResults(queryJob); - assertEquals("etag", response.etag()); - assertEquals(queryJob, response.jobId()); + assertEquals("etag", response.getEtag()); + assertEquals(queryJob, response.getJobId()); assertEquals(true, response.jobCompleted()); - assertEquals(false, response.result().cacheHit()); - assertEquals(ImmutableList.of(), response.executionErrors()); + assertEquals(false, response.getResult().cacheHit()); + assertEquals(ImmutableList.of(), response.getExecutionErrors()); assertFalse(response.hasErrors()); - assertEquals(null, response.result().schema()); - assertEquals(42L, response.result().totalBytesProcessed()); - assertEquals(1L, response.result().totalRows()); - for (List row : response.result().values()) { - assertEquals(false, row.get(0).booleanValue()); - assertEquals(1L, row.get(1).longValue()); + assertEquals(null, response.getResult().getSchema()); + assertEquals(42L, response.getResult().getTotalBytesProcessed()); + assertEquals(1L, response.getResult().getTotalRows()); + for (List row : response.getResult().values()) { + assertEquals(false, row.get(0).getBooleanValue()); + assertEquals(1L, row.get(1).getLongValue()); } - assertEquals(CURSOR, response.result().nextPageCursor()); + assertEquals(CURSOR, response.getResult().nextPageCursor()); } @Test @@ -1135,20 +1138,20 @@ public void testGetQueryResultsWithProject() { EasyMock.replay(bigqueryRpcMock); bigquery = options.service(); QueryResponse response = bigquery.getQueryResults(queryJob); - assertEquals("etag", response.etag()); - assertEquals(queryJob, response.jobId()); + assertEquals("etag", response.getEtag()); + assertEquals(queryJob, response.getJobId()); assertEquals(true, response.jobCompleted()); - assertEquals(false, response.result().cacheHit()); - assertEquals(ImmutableList.of(), response.executionErrors()); + assertEquals(false, response.getResult().cacheHit()); + assertEquals(ImmutableList.of(), response.getExecutionErrors()); assertFalse(response.hasErrors()); - assertEquals(null, response.result().schema()); - assertEquals(42L, response.result().totalBytesProcessed()); - assertEquals(1L, response.result().totalRows()); - for (List row : response.result().values()) { - assertEquals(false, row.get(0).booleanValue()); - assertEquals(1L, row.get(1).longValue()); + assertEquals(null, response.getResult().getSchema()); + assertEquals(42L, response.getResult().getTotalBytesProcessed()); + assertEquals(1L, response.getResult().getTotalRows()); + for (List row : response.getResult().values()) { + assertEquals(false, row.get(0).getBooleanValue()); + assertEquals(1L, row.get(1).getLongValue()); } - assertEquals(CURSOR, response.result().nextPageCursor()); + assertEquals(CURSOR, response.getResult().nextPageCursor()); } @Test @@ -1169,19 +1172,19 @@ public void testGetQueryResultsWithOptions() { QueryResponse response = bigquery.getQueryResults(queryJob, QUERY_RESULTS_OPTION_TIME, QUERY_RESULTS_OPTION_INDEX, QUERY_RESULTS_OPTION_PAGE_SIZE, QUERY_RESULTS_OPTION_PAGE_TOKEN); - assertEquals(queryJob, response.jobId()); + assertEquals(queryJob, response.getJobId()); assertEquals(true, response.jobCompleted()); - assertEquals(false, response.result().cacheHit()); - assertEquals(ImmutableList.of(), response.executionErrors()); + assertEquals(false, response.getResult().cacheHit()); + assertEquals(ImmutableList.of(), response.getExecutionErrors()); assertFalse(response.hasErrors()); - assertEquals(null, response.result().schema()); - assertEquals(42L, response.result().totalBytesProcessed()); - assertEquals(1L, response.result().totalRows()); - for (List row : response.result().values()) { - assertEquals(false, row.get(0).booleanValue()); - assertEquals(1L, row.get(1).longValue()); + assertEquals(null, response.getResult().getSchema()); + assertEquals(42L, response.getResult().getTotalBytesProcessed()); + assertEquals(1L, response.getResult().getTotalRows()); + for (List row : response.getResult().values()) { + assertEquals(false, row.get(0).getBooleanValue()); + assertEquals(1L, row.get(1).getLongValue()); } - assertEquals(CURSOR, response.result().nextPageCursor()); + assertEquals(CURSOR, response.getResult().nextPageCursor()); } @Test diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/CopyJobConfigurationTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/CopyJobConfigurationTest.java index 7d676a9b1505..90d744717934 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/CopyJobConfigurationTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/CopyJobConfigurationTest.java @@ -38,11 +38,21 @@ public class CopyJobConfigurationTest { private static final CreateDisposition CREATE_DISPOSITION = CreateDisposition.CREATE_IF_NEEDED; private static final WriteDisposition WRITE_DISPOSITION = WriteDisposition.WRITE_APPEND; private static final CopyJobConfiguration COPY_JOB_CONFIGURATION = + CopyJobConfiguration.newBuilder(DESTINATION_TABLE, SOURCE_TABLE) + .setCreateDisposition(CREATE_DISPOSITION) + .setWriteDisposition(WRITE_DISPOSITION) + .build(); + private static final CopyJobConfiguration COPY_JOB_CONFIGURATION_MULTIPLE_TABLES = + CopyJobConfiguration.newBuilder(DESTINATION_TABLE, SOURCE_TABLES) + .setCreateDisposition(CREATE_DISPOSITION) + .setWriteDisposition(WRITE_DISPOSITION) + .build(); + private static final CopyJobConfiguration DEPRECATED_COPY_JOB_CONFIGURATION = CopyJobConfiguration.builder(DESTINATION_TABLE, SOURCE_TABLE) .createDisposition(CREATE_DISPOSITION) .writeDisposition(WRITE_DISPOSITION) .build(); - private static final CopyJobConfiguration COPY_JOB_CONFIGURATION_MULTIPLE_TABLES = + private static final CopyJobConfiguration DEPRECATED_COPY_JOB_CONFIGURATION_MULTIPLE_TABLES = CopyJobConfiguration.builder(DESTINATION_TABLE, SOURCE_TABLES) .createDisposition(CREATE_DISPOSITION) .writeDisposition(WRITE_DISPOSITION) @@ -54,21 +64,21 @@ public void testToBuilder() { compareCopyJobConfiguration(COPY_JOB_CONFIGURATION_MULTIPLE_TABLES, COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.toBuilder().build()); CopyJobConfiguration jobConfiguration = COPY_JOB_CONFIGURATION.toBuilder() - .destinationTable(TableId.of("dataset", "newTable")) + .setDestinationTable(TableId.of("dataset", "newTable")) .build(); - assertEquals("newTable", jobConfiguration.destinationTable().table()); - jobConfiguration = jobConfiguration.toBuilder().destinationTable(DESTINATION_TABLE).build(); + assertEquals("newTable", jobConfiguration.getDestinationTable().getTable()); + jobConfiguration = jobConfiguration.toBuilder().setDestinationTable(DESTINATION_TABLE).build(); compareCopyJobConfiguration(COPY_JOB_CONFIGURATION, jobConfiguration); } @Test public void testOf() { CopyJobConfiguration job = CopyJobConfiguration.of(DESTINATION_TABLE, SOURCE_TABLES); - assertEquals(DESTINATION_TABLE, job.destinationTable()); - assertEquals(SOURCE_TABLES, job.sourceTables()); + assertEquals(DESTINATION_TABLE, job.getDestinationTable()); + assertEquals(SOURCE_TABLES, job.getSourceTables()); job = CopyJobConfiguration.of(DESTINATION_TABLE, SOURCE_TABLE); - assertEquals(DESTINATION_TABLE, job.destinationTable()); - assertEquals(ImmutableList.of(SOURCE_TABLE), job.sourceTables()); + assertEquals(DESTINATION_TABLE, job.getDestinationTable()); + assertEquals(ImmutableList.of(SOURCE_TABLE), job.getSourceTables()); } @Test @@ -80,14 +90,30 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(DESTINATION_TABLE, COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.destinationTable()); - assertEquals(SOURCE_TABLES, COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.sourceTables()); - assertEquals(CREATE_DISPOSITION, COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.createDisposition()); - assertEquals(WRITE_DISPOSITION, COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.writeDisposition()); - assertEquals(DESTINATION_TABLE, COPY_JOB_CONFIGURATION.destinationTable()); - assertEquals(ImmutableList.of(SOURCE_TABLE), COPY_JOB_CONFIGURATION.sourceTables()); - assertEquals(CREATE_DISPOSITION, COPY_JOB_CONFIGURATION.createDisposition()); - assertEquals(WRITE_DISPOSITION, COPY_JOB_CONFIGURATION.writeDisposition()); + assertEquals(DESTINATION_TABLE, COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.getDestinationTable()); + assertEquals(SOURCE_TABLES, COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.getSourceTables()); + assertEquals(CREATE_DISPOSITION, COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.getCreateDisposition()); + assertEquals(WRITE_DISPOSITION, COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.getWriteDisposition()); + assertEquals(DESTINATION_TABLE, COPY_JOB_CONFIGURATION.getDestinationTable()); + assertEquals(ImmutableList.of(SOURCE_TABLE), COPY_JOB_CONFIGURATION.getSourceTables()); + assertEquals(CREATE_DISPOSITION, COPY_JOB_CONFIGURATION.getCreateDisposition()); + assertEquals(WRITE_DISPOSITION, COPY_JOB_CONFIGURATION.getWriteDisposition()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(DESTINATION_TABLE, + DEPRECATED_COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.destinationTable()); + assertEquals(SOURCE_TABLES, + DEPRECATED_COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.sourceTables()); + assertEquals(CREATE_DISPOSITION, + DEPRECATED_COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.createDisposition()); + assertEquals(WRITE_DISPOSITION, + DEPRECATED_COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.writeDisposition()); + assertEquals(DESTINATION_TABLE, DEPRECATED_COPY_JOB_CONFIGURATION.destinationTable()); + assertEquals(ImmutableList.of(SOURCE_TABLE), DEPRECATED_COPY_JOB_CONFIGURATION.sourceTables()); + assertEquals(CREATE_DISPOSITION, DEPRECATED_COPY_JOB_CONFIGURATION.createDisposition()); + assertEquals(WRITE_DISPOSITION, DEPRECATED_COPY_JOB_CONFIGURATION.writeDisposition()); } @Test @@ -111,9 +137,9 @@ public void testToPbAndFromPb() { @Test public void testSetProjectId() { CopyJobConfiguration configuration = COPY_JOB_CONFIGURATION_MULTIPLE_TABLES.setProjectId("p"); - assertEquals("p", configuration.destinationTable().project()); - for (TableId sourceTable : configuration.sourceTables()) { - assertEquals("p", sourceTable.project()); + assertEquals("p", configuration.getDestinationTable().getProject()); + for (TableId sourceTable : configuration.getSourceTables()) { + assertEquals("p", sourceTable.getProject()); } } @@ -122,9 +148,9 @@ private void compareCopyJobConfiguration(CopyJobConfiguration expected, assertEquals(expected, value); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); - assertEquals(expected.destinationTable(), value.destinationTable()); - assertEquals(expected.sourceTables(), value.sourceTables()); - assertEquals(expected.createDisposition(), value.createDisposition()); - assertEquals(expected.writeDisposition(), value.writeDisposition()); + assertEquals(expected.getDestinationTable(), value.getDestinationTable()); + assertEquals(expected.getSourceTables(), value.getSourceTables()); + assertEquals(expected.getCreateDisposition(), value.getCreateDisposition()); + assertEquals(expected.getWriteDisposition(), value.getWriteDisposition()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/CsvOptionsTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/CsvOptionsTest.java index edc5e8508188..f08ef14a61c5 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/CsvOptionsTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/CsvOptionsTest.java @@ -31,7 +31,15 @@ public class CsvOptionsTest { private static final String FIELD_DELIMITER = ","; private static final String QUOTE = "\""; private static final long SKIP_LEADING_ROWS = 42L; - private static final CsvOptions CSV_OPTIONS = CsvOptions.builder() + private static final CsvOptions CSV_OPTIONS = CsvOptions.newBuilder() + .setAllowJaggedRows(ALLOW_JAGGED_ROWS) + .setAllowQuotedNewLines(ALLOW_QUOTED_NEWLINE) + .setEncoding(ENCODING) + .setFieldDelimiter(FIELD_DELIMITER) + .setQuote(QUOTE) + .setSkipLeadingRows(SKIP_LEADING_ROWS) + .build(); + private static final CsvOptions DEPRECATED_CSV_OPTIONS = CsvOptions.builder() .allowJaggedRows(ALLOW_JAGGED_ROWS) .allowQuotedNewLines(ALLOW_QUOTED_NEWLINE) .encoding(ENCODING) @@ -44,34 +52,45 @@ public class CsvOptionsTest { public void testToBuilder() { compareCsvOptions(CSV_OPTIONS, CSV_OPTIONS.toBuilder().build()); CsvOptions csvOptions = CSV_OPTIONS.toBuilder() - .fieldDelimiter(";") + .setFieldDelimiter(";") .build(); - assertEquals(";", csvOptions.fieldDelimiter()); - csvOptions = csvOptions.toBuilder().fieldDelimiter(",").build(); + assertEquals(";", csvOptions.getFieldDelimiter()); + csvOptions = csvOptions.toBuilder().setFieldDelimiter(",").build(); compareCsvOptions(CSV_OPTIONS, csvOptions); } @Test public void testToBuilderIncomplete() { - CsvOptions csvOptions = CsvOptions.builder().fieldDelimiter("|").build(); + CsvOptions csvOptions = CsvOptions.newBuilder().setFieldDelimiter("|").build(); assertEquals(csvOptions, csvOptions.toBuilder().build()); } @Test public void testBuilder() { - assertEquals(FormatOptions.CSV, CSV_OPTIONS.type()); + assertEquals(FormatOptions.CSV, CSV_OPTIONS.getType()); assertEquals(ALLOW_JAGGED_ROWS, CSV_OPTIONS.allowJaggedRows()); assertEquals(ALLOW_QUOTED_NEWLINE, CSV_OPTIONS.allowQuotedNewLines()); - assertEquals(ENCODING.name(), CSV_OPTIONS.encoding()); - assertEquals(FIELD_DELIMITER, CSV_OPTIONS.fieldDelimiter()); - assertEquals(QUOTE, CSV_OPTIONS.quote()); - assertEquals(SKIP_LEADING_ROWS, (long) CSV_OPTIONS.skipLeadingRows()); + assertEquals(ENCODING.name(), CSV_OPTIONS.getEncoding()); + assertEquals(FIELD_DELIMITER, CSV_OPTIONS.getFieldDelimiter()); + assertEquals(QUOTE, CSV_OPTIONS.getQuote()); + assertEquals(SKIP_LEADING_ROWS, (long) CSV_OPTIONS.getSkipLeadingRows()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(FormatOptions.CSV, DEPRECATED_CSV_OPTIONS.type()); + assertEquals(ALLOW_JAGGED_ROWS, DEPRECATED_CSV_OPTIONS.allowJaggedRows()); + assertEquals(ALLOW_QUOTED_NEWLINE, DEPRECATED_CSV_OPTIONS.allowQuotedNewLines()); + assertEquals(ENCODING.name(), DEPRECATED_CSV_OPTIONS.encoding()); + assertEquals(FIELD_DELIMITER, DEPRECATED_CSV_OPTIONS.fieldDelimiter()); + assertEquals(QUOTE, DEPRECATED_CSV_OPTIONS.quote()); + assertEquals(SKIP_LEADING_ROWS, (long) DEPRECATED_CSV_OPTIONS.skipLeadingRows()); } @Test public void testToAndFromPb() { compareCsvOptions(CSV_OPTIONS, CsvOptions.fromPb(CSV_OPTIONS.toPb())); - CsvOptions csvOptions = CsvOptions.builder().allowJaggedRows(ALLOW_JAGGED_ROWS).build(); + CsvOptions csvOptions = CsvOptions.newBuilder().setAllowJaggedRows(ALLOW_JAGGED_ROWS).build(); compareCsvOptions(csvOptions, CsvOptions.fromPb(csvOptions.toPb())); } @@ -79,9 +98,9 @@ private void compareCsvOptions(CsvOptions expected, CsvOptions value) { assertEquals(expected, value); assertEquals(expected.allowJaggedRows(), value.allowJaggedRows()); assertEquals(expected.allowQuotedNewLines(), value.allowQuotedNewLines()); - assertEquals(expected.encoding(), value.encoding()); - assertEquals(expected.fieldDelimiter(), value.fieldDelimiter()); - assertEquals(expected.quote(), value.quote()); - assertEquals(expected.skipLeadingRows(), value.skipLeadingRows()); + assertEquals(expected.getEncoding(), value.getEncoding()); + assertEquals(expected.getFieldDelimiter(), value.getFieldDelimiter()); + assertEquals(expected.getQuote(), value.getQuote()); + assertEquals(expected.getSkipLeadingRows(), value.getSkipLeadingRows()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetIdTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetIdTest.java index 5cf627a42e38..8d9743fc8473 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetIdTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetIdTest.java @@ -27,6 +27,14 @@ public class DatasetIdTest { @Test public void testOf() { + assertEquals(null, DATASET.getProject()); + assertEquals("dataset", DATASET.getDataset()); + assertEquals("project", DATASET_COMPLETE.getProject()); + assertEquals("dataset", DATASET_COMPLETE.getDataset()); + } + + @Test + public void testOfDeprecated() { assertEquals(null, DATASET.project()); assertEquals("dataset", DATASET.dataset()); assertEquals("project", DATASET_COMPLETE.project()); @@ -52,8 +60,8 @@ public void testSetProjectId() { private void compareDatasetIds(DatasetId expected, DatasetId value) { assertEquals(expected, value); - assertEquals(expected.project(), value.project()); - assertEquals(expected.dataset(), value.dataset()); + assertEquals(expected.getProject(), value.getProject()); + assertEquals(expected.getDataset(), value.getDataset()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetInfoTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetInfoTest.java index 21d75cb28592..4951a8a065a3 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetInfoTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetInfoTest.java @@ -44,19 +44,35 @@ public class DatasetInfoTest { private static final String SELF_LINK = "http://bigquery/p/d"; private static final DatasetId DATASET_ID = DatasetId.of("dataset"); private static final DatasetId DATASET_ID_COMPLETE = DatasetId.of("project", "dataset"); - private static final DatasetInfo DATASET_INFO = DatasetInfo.builder(DATASET_ID) + private static final DatasetInfo DATASET_INFO = DatasetInfo.newBuilder(DATASET_ID) + .setAcl(ACCESS_RULES) + .setCreationTime(CREATION_TIME) + .setDefaultTableLifetime(DEFAULT_TABLE_EXPIRATION) + .setDescription(DESCRIPTION) + .setEtag(ETAG) + .setFriendlyName(FRIENDLY_NAME) + .setGeneratedId(GENERATED_ID) + .setLastModified(LAST_MODIFIED) + .setLocation(LOCATION) + .setSelfLink(SELF_LINK) + .build(); + private static final DatasetInfo DATASET_INFO_COMPLETE = DATASET_INFO.toBuilder() + .setDatasetId(DATASET_ID_COMPLETE) + .setAcl(ACCESS_RULES_COMPLETE) + .build(); + private static final DatasetInfo DEPRECATED_DATASET_INFO = DatasetInfo.builder(DATASET_ID) .acl(ACCESS_RULES) - .creationTime(CREATION_TIME) + .setCreationTime(CREATION_TIME) .defaultTableLifetime(DEFAULT_TABLE_EXPIRATION) .description(DESCRIPTION) - .etag(ETAG) + .setEtag(ETAG) .friendlyName(FRIENDLY_NAME) - .generatedId(GENERATED_ID) - .lastModified(LAST_MODIFIED) + .setGeneratedId(GENERATED_ID) + .setLastModified(LAST_MODIFIED) .location(LOCATION) - .selfLink(SELF_LINK) + .setSelfLink(SELF_LINK) .build(); - private static final DatasetInfo DATASET_INFO_COMPLETE = DATASET_INFO.toBuilder() + private static final DatasetInfo DEPRECATED_DATASET_INFO_COMPLETE = DATASET_INFO.toBuilder() .datasetId(DATASET_ID_COMPLETE) .acl(ACCESS_RULES_COMPLETE) .build(); @@ -65,80 +81,107 @@ public class DatasetInfoTest { public void testToBuilder() { compareDatasets(DATASET_INFO, DATASET_INFO.toBuilder().build()); DatasetInfo datasetInfo = DATASET_INFO.toBuilder() - .datasetId(DatasetId.of("dataset2")) - .description("description2") + .setDatasetId(DatasetId.of("dataset2")) + .setDescription("description2") .build(); - assertEquals(DatasetId.of("dataset2"), datasetInfo.datasetId()); - assertEquals("description2", datasetInfo.description()); - datasetInfo = datasetInfo.toBuilder().datasetId(DATASET_ID).description("description").build(); + assertEquals(DatasetId.of("dataset2"), datasetInfo.getDatasetId()); + assertEquals("description2", datasetInfo.getDescription()); + datasetInfo = datasetInfo.toBuilder().setDatasetId(DATASET_ID).setDescription("description").build(); compareDatasets(DATASET_INFO, datasetInfo); } @Test public void testToBuilderIncomplete() { - DatasetInfo datasetInfo = DatasetInfo.builder(DATASET_ID).build(); + DatasetInfo datasetInfo = DatasetInfo.newBuilder(DATASET_ID).build(); assertEquals(datasetInfo, datasetInfo.toBuilder().build()); } @Test public void testBuilder() { - assertNull(DATASET_INFO.datasetId().project()); - assertEquals(DATASET_ID, DATASET_INFO.datasetId()); - assertEquals(ACCESS_RULES, DATASET_INFO.acl()); - assertEquals(CREATION_TIME, DATASET_INFO.creationTime()); - assertEquals(DEFAULT_TABLE_EXPIRATION, DATASET_INFO.defaultTableLifetime()); - assertEquals(DESCRIPTION, DATASET_INFO.description()); - assertEquals(ETAG, DATASET_INFO.etag()); - assertEquals(FRIENDLY_NAME, DATASET_INFO.friendlyName()); - assertEquals(GENERATED_ID, DATASET_INFO.generatedId()); - assertEquals(LAST_MODIFIED, DATASET_INFO.lastModified()); - assertEquals(LOCATION, DATASET_INFO.location()); - assertEquals(SELF_LINK, DATASET_INFO.selfLink()); - assertEquals(DATASET_ID_COMPLETE, DATASET_INFO_COMPLETE.datasetId()); - assertEquals(ACCESS_RULES_COMPLETE, DATASET_INFO_COMPLETE.acl()); - assertEquals(CREATION_TIME, DATASET_INFO_COMPLETE.creationTime()); - assertEquals(DEFAULT_TABLE_EXPIRATION, DATASET_INFO_COMPLETE.defaultTableLifetime()); - assertEquals(DESCRIPTION, DATASET_INFO_COMPLETE.description()); - assertEquals(ETAG, DATASET_INFO_COMPLETE.etag()); - assertEquals(FRIENDLY_NAME, DATASET_INFO_COMPLETE.friendlyName()); - assertEquals(GENERATED_ID, DATASET_INFO_COMPLETE.generatedId()); - assertEquals(LAST_MODIFIED, DATASET_INFO_COMPLETE.lastModified()); - assertEquals(LOCATION, DATASET_INFO_COMPLETE.location()); - assertEquals(SELF_LINK, DATASET_INFO_COMPLETE.selfLink()); + assertNull(DATASET_INFO.getDatasetId().getProject()); + assertEquals(DATASET_ID, DATASET_INFO.getDatasetId()); + assertEquals(ACCESS_RULES, DATASET_INFO.getAcl()); + assertEquals(CREATION_TIME, DATASET_INFO.getCreationTime()); + assertEquals(DEFAULT_TABLE_EXPIRATION, DATASET_INFO.getDefaultTableLifetime()); + assertEquals(DESCRIPTION, DATASET_INFO.getDescription()); + assertEquals(ETAG, DATASET_INFO.getEtag()); + assertEquals(FRIENDLY_NAME, DATASET_INFO.getFriendlyName()); + assertEquals(GENERATED_ID, DATASET_INFO.getGeneratedId()); + assertEquals(LAST_MODIFIED, DATASET_INFO.getLastModified()); + assertEquals(LOCATION, DATASET_INFO.getLocation()); + assertEquals(SELF_LINK, DATASET_INFO.getSelfLink()); + assertEquals(DATASET_ID_COMPLETE, DATASET_INFO_COMPLETE.getDatasetId()); + assertEquals(ACCESS_RULES_COMPLETE, DATASET_INFO_COMPLETE.getAcl()); + assertEquals(CREATION_TIME, DATASET_INFO_COMPLETE.getCreationTime()); + assertEquals(DEFAULT_TABLE_EXPIRATION, DATASET_INFO_COMPLETE.getDefaultTableLifetime()); + assertEquals(DESCRIPTION, DATASET_INFO_COMPLETE.getDescription()); + assertEquals(ETAG, DATASET_INFO_COMPLETE.getEtag()); + assertEquals(FRIENDLY_NAME, DATASET_INFO_COMPLETE.getFriendlyName()); + assertEquals(GENERATED_ID, DATASET_INFO_COMPLETE.getGeneratedId()); + assertEquals(LAST_MODIFIED, DATASET_INFO_COMPLETE.getLastModified()); + assertEquals(LOCATION, DATASET_INFO_COMPLETE.getLocation()); + assertEquals(SELF_LINK, DATASET_INFO_COMPLETE.getSelfLink()); + } + + @Test + public void testBuilderDeprecated() { + assertNull(DEPRECATED_DATASET_INFO.datasetId().getProject()); + assertEquals(DATASET_ID, DEPRECATED_DATASET_INFO.datasetId()); + assertEquals(ACCESS_RULES, DEPRECATED_DATASET_INFO.acl()); + assertEquals(CREATION_TIME, DEPRECATED_DATASET_INFO.creationTime()); + assertEquals(DEFAULT_TABLE_EXPIRATION, DEPRECATED_DATASET_INFO.defaultTableLifetime()); + assertEquals(DESCRIPTION, DEPRECATED_DATASET_INFO.description()); + assertEquals(ETAG, DEPRECATED_DATASET_INFO.etag()); + assertEquals(FRIENDLY_NAME, DEPRECATED_DATASET_INFO.friendlyName()); + assertEquals(GENERATED_ID, DEPRECATED_DATASET_INFO.generatedId()); + assertEquals(LAST_MODIFIED, DEPRECATED_DATASET_INFO.lastModified()); + assertEquals(LOCATION, DEPRECATED_DATASET_INFO.location()); + assertEquals(SELF_LINK, DEPRECATED_DATASET_INFO.selfLink()); + assertEquals(DATASET_ID_COMPLETE, DEPRECATED_DATASET_INFO_COMPLETE.datasetId()); + assertEquals(ACCESS_RULES_COMPLETE, DEPRECATED_DATASET_INFO_COMPLETE.acl()); + assertEquals(CREATION_TIME, DEPRECATED_DATASET_INFO_COMPLETE.creationTime()); + assertEquals(DEFAULT_TABLE_EXPIRATION, DEPRECATED_DATASET_INFO_COMPLETE.defaultTableLifetime()); + assertEquals(DESCRIPTION, DEPRECATED_DATASET_INFO_COMPLETE.description()); + assertEquals(ETAG, DEPRECATED_DATASET_INFO_COMPLETE.etag()); + assertEquals(FRIENDLY_NAME, DEPRECATED_DATASET_INFO_COMPLETE.friendlyName()); + assertEquals(GENERATED_ID, DEPRECATED_DATASET_INFO_COMPLETE.generatedId()); + assertEquals(LAST_MODIFIED, DEPRECATED_DATASET_INFO_COMPLETE.lastModified()); + assertEquals(LOCATION, DEPRECATED_DATASET_INFO_COMPLETE.location()); + assertEquals(SELF_LINK, DEPRECATED_DATASET_INFO_COMPLETE.selfLink()); } @Test public void testOf() { - DatasetInfo datasetInfo = DatasetInfo.of(DATASET_ID.dataset()); - assertEquals(DATASET_ID, datasetInfo.datasetId()); - assertNull(datasetInfo.acl()); - assertNull(datasetInfo.creationTime()); - assertNull(datasetInfo.defaultTableLifetime()); - assertNull(datasetInfo.description()); - assertNull(datasetInfo.etag()); - assertNull(datasetInfo.friendlyName()); - assertNull(datasetInfo.generatedId()); - assertNull(datasetInfo.lastModified()); - assertNull(datasetInfo.location()); - assertNull(datasetInfo.selfLink()); + DatasetInfo datasetInfo = DatasetInfo.of(DATASET_ID.getDataset()); + assertEquals(DATASET_ID, datasetInfo.getDatasetId()); + assertNull(datasetInfo.getAcl()); + assertNull(datasetInfo.getCreationTime()); + assertNull(datasetInfo.getDefaultTableLifetime()); + assertNull(datasetInfo.getDescription()); + assertNull(datasetInfo.getEtag()); + assertNull(datasetInfo.getFriendlyName()); + assertNull(datasetInfo.getGeneratedId()); + assertNull(datasetInfo.getLastModified()); + assertNull(datasetInfo.getLocation()); + assertNull(datasetInfo.getSelfLink()); datasetInfo = DatasetInfo.of(DATASET_ID); - assertEquals(DATASET_ID, datasetInfo.datasetId()); - assertNull(datasetInfo.acl()); - assertNull(datasetInfo.creationTime()); - assertNull(datasetInfo.defaultTableLifetime()); - assertNull(datasetInfo.description()); - assertNull(datasetInfo.etag()); - assertNull(datasetInfo.friendlyName()); - assertNull(datasetInfo.generatedId()); - assertNull(datasetInfo.lastModified()); - assertNull(datasetInfo.location()); - assertNull(datasetInfo.selfLink()); + assertEquals(DATASET_ID, datasetInfo.getDatasetId()); + assertNull(datasetInfo.getAcl()); + assertNull(datasetInfo.getCreationTime()); + assertNull(datasetInfo.getDefaultTableLifetime()); + assertNull(datasetInfo.getDescription()); + assertNull(datasetInfo.getEtag()); + assertNull(datasetInfo.getFriendlyName()); + assertNull(datasetInfo.getGeneratedId()); + assertNull(datasetInfo.getLastModified()); + assertNull(datasetInfo.getLocation()); + assertNull(datasetInfo.getSelfLink()); } @Test public void testToPbAndFromPb() { compareDatasets(DATASET_INFO_COMPLETE, DatasetInfo.fromPb(DATASET_INFO_COMPLETE.toPb())); - DatasetInfo datasetInfo = DatasetInfo.builder("project", "dataset").build(); + DatasetInfo datasetInfo = DatasetInfo.newBuilder("project", "dataset").build(); compareDatasets(datasetInfo, DatasetInfo.fromPb(datasetInfo.toPb())); } @@ -149,16 +192,16 @@ public void testSetProjectId() { private void compareDatasets(DatasetInfo expected, DatasetInfo value) { assertEquals(expected, value); - assertEquals(expected.datasetId(), value.datasetId()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.etag(), value.etag()); - assertEquals(expected.friendlyName(), value.friendlyName()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.location(), value.location()); - assertEquals(expected.selfLink(), value.selfLink()); - assertEquals(expected.acl(), value.acl()); - assertEquals(expected.creationTime(), value.creationTime()); - assertEquals(expected.defaultTableLifetime(), value.defaultTableLifetime()); - assertEquals(expected.lastModified(), value.lastModified()); + assertEquals(expected.getDatasetId(), value.getDatasetId()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getEtag(), value.getEtag()); + assertEquals(expected.getFriendlyName(), value.getFriendlyName()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getLocation(), value.getLocation()); + assertEquals(expected.getSelfLink(), value.getSelfLink()); + assertEquals(expected.getAcl(), value.getAcl()); + assertEquals(expected.getCreationTime(), value.getCreationTime()); + assertEquals(expected.getDefaultTableLifetime(), value.getDefaultTableLifetime()); + assertEquals(expected.getLastModified(), value.getLastModified()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetTest.java index 7693e9900131..22b78471a2fb 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetTest.java @@ -55,7 +55,7 @@ public class DatasetTest { private static final Long LAST_MODIFIED = CREATION_TIME + 50; private static final String LOCATION = ""; private static final String SELF_LINK = "http://bigquery/p/d"; - private static final DatasetInfo DATASET_INFO = DatasetInfo.builder(DATASET_ID).build(); + private static final DatasetInfo DATASET_INFO = DatasetInfo.newBuilder(DATASET_ID).build(); private static final Field FIELD = Field.of("FieldName", Field.Type.integer()); private static final StandardTableDefinition TABLE_DEFINITION = StandardTableDefinition.of(Schema.of(FIELD)); @@ -63,11 +63,11 @@ public class DatasetTest { private static final ExternalTableDefinition EXTERNAL_TABLE_DEFINITION = ExternalTableDefinition.of(ImmutableList.of("URI"), Schema.of(), FormatOptions.csv()); private static final TableInfo TABLE_INFO1 = - TableInfo.builder(TableId.of("dataset", "table1"), TABLE_DEFINITION).build(); + TableInfo.newBuilder(TableId.of("dataset", "table1"), TABLE_DEFINITION).build(); private static final TableInfo TABLE_INFO2 = - TableInfo.builder(TableId.of("dataset", "table2"), VIEW_DEFINITION).build(); + TableInfo.newBuilder(TableId.of("dataset", "table2"), VIEW_DEFINITION).build(); private static final TableInfo TABLE_INFO3 = - TableInfo.builder(TableId.of("dataset", "table3"), EXTERNAL_TABLE_DEFINITION).build(); + TableInfo.newBuilder(TableId.of("dataset", "table3"), EXTERNAL_TABLE_DEFINITION).build(); private BigQuery serviceMockReturnsOptions = createStrictMock(BigQuery.class); private BigQueryOptions mockOptions = createMock(BigQueryOptions.class); @@ -93,19 +93,48 @@ public void tearDown() throws Exception { @Test public void testBuilder() { + initializeExpectedDataset(2); + replay(bigquery); + Dataset builtDataset = new Dataset.Builder(serviceMockReturnsOptions, DATASET_ID) + .setAcl(ACCESS_RULES) + .setCreationTime(CREATION_TIME) + .setDefaultTableLifetime(DEFAULT_TABLE_EXPIRATION) + .setDescription(DESCRIPTION) + .setEtag(ETAG) + .setFriendlyName(FRIENDLY_NAME) + .setGeneratedId(GENERATED_ID) + .setLastModified(LAST_MODIFIED) + .setLocation(LOCATION) + .setSelfLink(SELF_LINK) + .build(); + assertEquals(DATASET_ID, builtDataset.getDatasetId()); + assertEquals(ACCESS_RULES, builtDataset.getAcl()); + assertEquals(CREATION_TIME, builtDataset.getCreationTime()); + assertEquals(DEFAULT_TABLE_EXPIRATION, builtDataset.getDefaultTableLifetime()); + assertEquals(DESCRIPTION, builtDataset.getDescription()); + assertEquals(ETAG, builtDataset.getEtag()); + assertEquals(FRIENDLY_NAME, builtDataset.getFriendlyName()); + assertEquals(GENERATED_ID, builtDataset.getGeneratedId()); + assertEquals(LAST_MODIFIED, builtDataset.getLastModified()); + assertEquals(LOCATION, builtDataset.getLocation()); + assertEquals(SELF_LINK, builtDataset.getSelfLink()); + } + + @Test + public void testBuilderDeprecated() { initializeExpectedDataset(2); replay(bigquery); Dataset builtDataset = new Dataset.Builder(serviceMockReturnsOptions, DATASET_ID) .acl(ACCESS_RULES) - .creationTime(CREATION_TIME) + .setCreationTime(CREATION_TIME) .defaultTableLifetime(DEFAULT_TABLE_EXPIRATION) .description(DESCRIPTION) - .etag(ETAG) + .setEtag(ETAG) .friendlyName(FRIENDLY_NAME) - .generatedId(GENERATED_ID) - .lastModified(LAST_MODIFIED) + .setGeneratedId(GENERATED_ID) + .setLastModified(LAST_MODIFIED) .location(LOCATION) - .selfLink(SELF_LINK) + .setSelfLink(SELF_LINK) .build(); assertEquals(DATASET_ID, builtDataset.datasetId()); assertEquals(ACCESS_RULES, builtDataset.acl()); @@ -132,7 +161,7 @@ public void testExists_True() throws Exception { initializeExpectedDataset(1); BigQuery.DatasetOption[] expectedOptions = {BigQuery.DatasetOption.fields()}; expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getDataset(DATASET_INFO.datasetId(), expectedOptions)) + expect(bigquery.getDataset(DATASET_INFO.getDatasetId(), expectedOptions)) .andReturn(expectedDataset); replay(bigquery); initializeDataset(); @@ -144,7 +173,7 @@ public void testExists_False() throws Exception { initializeExpectedDataset(1); BigQuery.DatasetOption[] expectedOptions = {BigQuery.DatasetOption.fields()}; expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getDataset(DATASET_INFO.datasetId(), expectedOptions)).andReturn(null); + expect(bigquery.getDataset(DATASET_INFO.getDatasetId(), expectedOptions)).andReturn(null); replay(bigquery); initializeDataset(); assertFalse(dataset.exists()); @@ -153,11 +182,12 @@ public void testExists_False() throws Exception { @Test public void testReload() throws Exception { initializeExpectedDataset(4); - DatasetInfo updatedInfo = DATASET_INFO.toBuilder().description("Description").build(); + DatasetInfo updatedInfo = DATASET_INFO.toBuilder().setDescription("Description").build(); Dataset expectedDataset = new Dataset(serviceMockReturnsOptions, new DatasetInfo.BuilderImpl(updatedInfo)); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getDataset(DATASET_INFO.datasetId().dataset())).andReturn(expectedDataset); + expect( + bigquery.getDataset(DATASET_INFO.getDatasetId().getDataset())).andReturn(expectedDataset); replay(bigquery); initializeDataset(); Dataset updatedDataset = dataset.reload(); @@ -168,7 +198,7 @@ public void testReload() throws Exception { public void testReloadNull() throws Exception { initializeExpectedDataset(1); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getDataset(DATASET_INFO.datasetId().dataset())).andReturn(null); + expect(bigquery.getDataset(DATASET_INFO.getDatasetId().getDataset())).andReturn(null); replay(bigquery); initializeDataset(); assertNull(dataset.reload()); @@ -177,12 +207,12 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedDataset(4); - DatasetInfo updatedInfo = DATASET_INFO.toBuilder().description("Description").build(); + DatasetInfo updatedInfo = DATASET_INFO.toBuilder().setDescription("Description").build(); Dataset expectedDataset = new Dataset(serviceMockReturnsOptions, new DatasetInfo.BuilderImpl(updatedInfo)); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getDataset(DATASET_INFO.datasetId().dataset(), BigQuery.DatasetOption.fields())) - .andReturn(expectedDataset); + expect(bigquery.getDataset(DATASET_INFO.getDatasetId().getDataset(), + BigQuery.DatasetOption.fields())).andReturn(expectedDataset); replay(bigquery); initializeDataset(); Dataset updatedDataset = dataset.reload(BigQuery.DatasetOption.fields()); @@ -192,7 +222,8 @@ public void testReloadWithOptions() throws Exception { @Test public void testUpdate() { initializeExpectedDataset(4); - Dataset expectedUpdatedDataset = expectedDataset.toBuilder().description("Description").build(); + Dataset expectedUpdatedDataset = + expectedDataset.toBuilder().setDescription("Description").build(); expect(bigquery.options()).andReturn(mockOptions); expect(bigquery.update(eq(expectedDataset))).andReturn(expectedUpdatedDataset); replay(bigquery); @@ -204,7 +235,8 @@ public void testUpdate() { @Test public void testUpdateWithOptions() { initializeExpectedDataset(4); - Dataset expectedUpdatedDataset = expectedDataset.toBuilder().description("Description").build(); + Dataset expectedUpdatedDataset = + expectedDataset.toBuilder().setDescription("Description").build(); expect(bigquery.options()).andReturn(mockOptions); expect(bigquery.update(eq(expectedDataset), eq(BigQuery.DatasetOption.fields()))) .andReturn(expectedUpdatedDataset); @@ -218,7 +250,7 @@ public void testUpdateWithOptions() { public void testDeleteTrue() { initializeExpectedDataset(1); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.delete(DATASET_INFO.datasetId())).andReturn(true); + expect(bigquery.delete(DATASET_INFO.getDatasetId())).andReturn(true); replay(bigquery); initializeDataset(); assertTrue(dataset.delete()); @@ -228,7 +260,7 @@ public void testDeleteTrue() { public void testDeleteFalse() { initializeExpectedDataset(1); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.delete(DATASET_INFO.datasetId())).andReturn(false); + expect(bigquery.delete(DATASET_INFO.getDatasetId())).andReturn(false); replay(bigquery); initializeDataset(); assertFalse(dataset.delete()); @@ -243,7 +275,7 @@ public void testList() throws Exception { new Table(serviceMockReturnsOptions, new Table.BuilderImpl(TABLE_INFO3))); PageImpl

expectedPage = new PageImpl<>(null, "c", tableResults); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.listTables(DATASET_INFO.datasetId())).andReturn(expectedPage); + expect(bigquery.listTables(DATASET_INFO.getDatasetId())).andReturn(expectedPage); replay(bigquery); initializeDataset(); Page
tablePage = dataset.list(); @@ -260,7 +292,7 @@ public void testListWithOptions() throws Exception { new Table(serviceMockReturnsOptions, new Table.BuilderImpl(TABLE_INFO3))); PageImpl
expectedPage = new PageImpl<>(null, "c", tableResults); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.listTables(DATASET_INFO.datasetId(), BigQuery.TableListOption.pageSize(10L))) + expect(bigquery.listTables(DATASET_INFO.getDatasetId(), BigQuery.TableListOption.pageSize(10L))) .andReturn(expectedPage); replay(bigquery); initializeDataset(); @@ -275,10 +307,10 @@ public void testGet() throws Exception { Table expectedTable = new Table(serviceMockReturnsOptions, new TableInfo.BuilderImpl(TABLE_INFO1)); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getTable(TABLE_INFO1.tableId())).andReturn(expectedTable); + expect(bigquery.getTable(TABLE_INFO1.getTableId())).andReturn(expectedTable); replay(bigquery); initializeDataset(); - Table table = dataset.get(TABLE_INFO1.tableId().table()); + Table table = dataset.get(TABLE_INFO1.getTableId().getTable()); assertNotNull(table); assertEquals(expectedTable, table); } @@ -287,10 +319,10 @@ public void testGet() throws Exception { public void testGetNull() throws Exception { initializeExpectedDataset(1); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getTable(TABLE_INFO1.tableId())).andReturn(null); + expect(bigquery.getTable(TABLE_INFO1.getTableId())).andReturn(null); replay(bigquery); initializeDataset(); - assertNull(dataset.get(TABLE_INFO1.tableId().table())); + assertNull(dataset.get(TABLE_INFO1.getTableId().getTable())); } @Test @@ -299,11 +331,11 @@ public void testGetWithOptions() throws Exception { Table expectedTable = new Table(serviceMockReturnsOptions, new TableInfo.BuilderImpl(TABLE_INFO1)); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getTable(TABLE_INFO1.tableId(), BigQuery.TableOption.fields())) + expect(bigquery.getTable(TABLE_INFO1.getTableId(), BigQuery.TableOption.fields())) .andReturn(expectedTable); replay(bigquery); initializeDataset(); - Table table = dataset.get(TABLE_INFO1.tableId().table(), BigQuery.TableOption.fields()); + Table table = dataset.get(TABLE_INFO1.getTableId().getTable(), BigQuery.TableOption.fields()); assertNotNull(table); assertEquals(expectedTable, table); } @@ -317,7 +349,7 @@ public void testCreateTable() throws Exception { expect(bigquery.create(TABLE_INFO1)).andReturn(expectedTable); replay(bigquery); initializeDataset(); - Table table = dataset.create(TABLE_INFO1.tableId().table(), TABLE_DEFINITION); + Table table = dataset.create(TABLE_INFO1.getTableId().getTable(), TABLE_DEFINITION); assertEquals(expectedTable, table); } @@ -330,13 +362,20 @@ public void testCreateTableWithOptions() throws Exception { expect(bigquery.create(TABLE_INFO1, BigQuery.TableOption.fields())).andReturn(expectedTable); replay(bigquery); initializeDataset(); - Table table = dataset.create(TABLE_INFO1.tableId().table(), TABLE_DEFINITION, + Table table = dataset.create(TABLE_INFO1.getTableId().getTable(), TABLE_DEFINITION, BigQuery.TableOption.fields()); assertEquals(expectedTable, table); } @Test public void testBigquery() { + initializeExpectedDataset(1); + replay(bigquery); + assertSame(serviceMockReturnsOptions, expectedDataset.getBigquery()); + } + + @Test + public void testBigqueryDeprecated() { initializeExpectedDataset(1); replay(bigquery); assertSame(serviceMockReturnsOptions, expectedDataset.bigquery()); @@ -353,21 +392,21 @@ public void testToAndFromPb() { private void compareDataset(Dataset expected, Dataset value) { assertEquals(expected, value); compareDatasetInfo(expected, value); - assertEquals(expected.bigquery().options(), value.bigquery().options()); + assertEquals(expected.getBigquery().options(), value.getBigquery().options()); } private void compareDatasetInfo(DatasetInfo expected, DatasetInfo value) { assertEquals(expected, value); - assertEquals(expected.datasetId(), value.datasetId()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.etag(), value.etag()); - assertEquals(expected.friendlyName(), value.friendlyName()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.location(), value.location()); - assertEquals(expected.selfLink(), value.selfLink()); - assertEquals(expected.acl(), value.acl()); - assertEquals(expected.creationTime(), value.creationTime()); - assertEquals(expected.defaultTableLifetime(), value.defaultTableLifetime()); - assertEquals(expected.lastModified(), value.lastModified()); + assertEquals(expected.getDatasetId(), value.getDatasetId()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getEtag(), value.getEtag()); + assertEquals(expected.getFriendlyName(), value.getFriendlyName()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getLocation(), value.getLocation()); + assertEquals(expected.getSelfLink(), value.getSelfLink()); + assertEquals(expected.getAcl(), value.getAcl()); + assertEquals(expected.getCreationTime(), value.getCreationTime()); + assertEquals(expected.getDefaultTableLifetime(), value.getDefaultTableLifetime()); + assertEquals(expected.getLastModified(), value.getLastModified()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ExternalTableDefinitionTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ExternalTableDefinitionTest.java index e3e1c01b9403..41df8f178e74 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ExternalTableDefinitionTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ExternalTableDefinitionTest.java @@ -28,26 +28,32 @@ public class ExternalTableDefinitionTest { private static final List SOURCE_URIS = ImmutableList.of("uri1", "uri2"); private static final Field FIELD_SCHEMA1 = - Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) - .description("FieldDescription1") + Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) + .setDescription("FieldDescription1") .build(); private static final Field FIELD_SCHEMA2 = - Field.builder("IntegerField", Field.Type.integer()) - .mode(Field.Mode.REPEATED) - .description("FieldDescription2") + Field.newBuilder("IntegerField", Field.Type.integer()) + .setMode(Field.Mode.REPEATED) + .setDescription("FieldDescription2") .build(); private static final Field FIELD_SCHEMA3 = - Field.builder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) - .mode(Field.Mode.REQUIRED) - .description("FieldDescription3") + Field.newBuilder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) + .setMode(Field.Mode.REQUIRED) + .setDescription("FieldDescription3") .build(); private static final Schema TABLE_SCHEMA = Schema.of(FIELD_SCHEMA1, FIELD_SCHEMA2, FIELD_SCHEMA3); private static final Integer MAX_BAD_RECORDS = 42; private static final Boolean IGNORE_UNKNOWN_VALUES = true; private static final String COMPRESSION = "GZIP"; - private static final CsvOptions CSV_OPTIONS = CsvOptions.builder().build(); + private static final CsvOptions CSV_OPTIONS = CsvOptions.newBuilder().build(); private static final ExternalTableDefinition EXTERNAL_TABLE_DEFINITION = + ExternalTableDefinition.newBuilder(SOURCE_URIS, TABLE_SCHEMA, CSV_OPTIONS) + .setCompression(COMPRESSION) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setMaxBadRecords(MAX_BAD_RECORDS) + .build(); + private static final ExternalTableDefinition DEPRECATED_EXTERNAL_TABLE_DEFINITION = ExternalTableDefinition.builder(SOURCE_URIS, TABLE_SCHEMA, CSV_OPTIONS) .compression(COMPRESSION) .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) @@ -59,10 +65,10 @@ public void testToBuilder() { compareExternalTableDefinition(EXTERNAL_TABLE_DEFINITION, EXTERNAL_TABLE_DEFINITION.toBuilder().build()); ExternalTableDefinition externalTableDefinition = - EXTERNAL_TABLE_DEFINITION.toBuilder().compression("NONE").build(); - assertEquals("NONE", externalTableDefinition.compression()); + EXTERNAL_TABLE_DEFINITION.toBuilder().setCompression("NONE").build(); + assertEquals("NONE", externalTableDefinition.getCompression()); externalTableDefinition = externalTableDefinition.toBuilder() - .compression(COMPRESSION) + .setCompression(COMPRESSION) .build(); compareExternalTableDefinition(EXTERNAL_TABLE_DEFINITION, externalTableDefinition); } @@ -76,13 +82,24 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(TableDefinition.Type.EXTERNAL, EXTERNAL_TABLE_DEFINITION.type()); - assertEquals(COMPRESSION, EXTERNAL_TABLE_DEFINITION.compression()); - assertEquals(CSV_OPTIONS, EXTERNAL_TABLE_DEFINITION.formatOptions()); + assertEquals(TableDefinition.Type.EXTERNAL, EXTERNAL_TABLE_DEFINITION.getType()); + assertEquals(COMPRESSION, EXTERNAL_TABLE_DEFINITION.getCompression()); + assertEquals(CSV_OPTIONS, EXTERNAL_TABLE_DEFINITION.getFormatOptions()); assertEquals(IGNORE_UNKNOWN_VALUES, EXTERNAL_TABLE_DEFINITION.ignoreUnknownValues()); - assertEquals(MAX_BAD_RECORDS, EXTERNAL_TABLE_DEFINITION.maxBadRecords()); - assertEquals(TABLE_SCHEMA, EXTERNAL_TABLE_DEFINITION.schema()); - assertEquals(SOURCE_URIS, EXTERNAL_TABLE_DEFINITION.sourceUris()); + assertEquals(MAX_BAD_RECORDS, EXTERNAL_TABLE_DEFINITION.getMaxBadRecords()); + assertEquals(TABLE_SCHEMA, EXTERNAL_TABLE_DEFINITION.getSchema()); + assertEquals(SOURCE_URIS, EXTERNAL_TABLE_DEFINITION.getSourceUris()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(TableDefinition.Type.EXTERNAL, DEPRECATED_EXTERNAL_TABLE_DEFINITION.type()); + assertEquals(COMPRESSION, DEPRECATED_EXTERNAL_TABLE_DEFINITION.compression()); + assertEquals(CSV_OPTIONS, DEPRECATED_EXTERNAL_TABLE_DEFINITION.formatOptions()); + assertEquals(IGNORE_UNKNOWN_VALUES, DEPRECATED_EXTERNAL_TABLE_DEFINITION.ignoreUnknownValues()); + assertEquals(MAX_BAD_RECORDS, DEPRECATED_EXTERNAL_TABLE_DEFINITION.maxBadRecords()); + assertEquals(TABLE_SCHEMA, DEPRECATED_EXTERNAL_TABLE_DEFINITION.schema()); + assertEquals(SOURCE_URIS, DEPRECATED_EXTERNAL_TABLE_DEFINITION.sourceUris()); } @Test @@ -90,7 +107,7 @@ public void testToAndFromPb() { compareExternalTableDefinition(EXTERNAL_TABLE_DEFINITION, ExternalTableDefinition.fromPb(EXTERNAL_TABLE_DEFINITION.toPb())); ExternalTableDefinition externalTableDefinition = - ExternalTableDefinition.builder(SOURCE_URIS, TABLE_SCHEMA, CSV_OPTIONS).build(); + ExternalTableDefinition.newBuilder(SOURCE_URIS, TABLE_SCHEMA, CSV_OPTIONS).build(); compareExternalTableDefinition(externalTableDefinition, ExternalTableDefinition.fromPb(externalTableDefinition.toPb())); } @@ -98,12 +115,12 @@ public void testToAndFromPb() { private void compareExternalTableDefinition(ExternalTableDefinition expected, ExternalTableDefinition value) { assertEquals(expected, value); - assertEquals(expected.compression(), value.compression()); - assertEquals(expected.formatOptions(), value.formatOptions()); + assertEquals(expected.getCompression(), value.getCompression()); + assertEquals(expected.getFormatOptions(), value.getFormatOptions()); assertEquals(expected.ignoreUnknownValues(), value.ignoreUnknownValues()); - assertEquals(expected.maxBadRecords(), value.maxBadRecords()); - assertEquals(expected.schema(), value.schema()); - assertEquals(expected.sourceUris(), value.sourceUris()); + assertEquals(expected.getMaxBadRecords(), value.getMaxBadRecords()); + assertEquals(expected.getSchema(), value.getSchema()); + assertEquals(expected.getSourceUris(), value.getSourceUris()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ExtractJobConfigurationTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ExtractJobConfigurationTest.java index 62d5274e491d..b5a9b0dc5e83 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ExtractJobConfigurationTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ExtractJobConfigurationTest.java @@ -37,13 +37,27 @@ public class ExtractJobConfigurationTest { private static final Boolean PRINT_HEADER = true; private static final String COMPRESSION = "GZIP"; private static final ExtractJobConfiguration EXTRACT_CONFIGURATION = + ExtractJobConfiguration.newBuilder(TABLE_ID, DESTINATION_URIS) + .setPrintHeader(PRINT_HEADER) + .setFieldDelimiter(FIELD_DELIMITER) + .setCompression(COMPRESSION) + .setFormat(FORMAT) + .build(); + private static final ExtractJobConfiguration EXTRACT_CONFIGURATION_ONE_URI = + ExtractJobConfiguration.newBuilder(TABLE_ID, DESTINATION_URI) + .setPrintHeader(PRINT_HEADER) + .setFieldDelimiter(FIELD_DELIMITER) + .setCompression(COMPRESSION) + .setFormat(FORMAT) + .build(); + private static final ExtractJobConfiguration DEPRECATED_EXTRACT_CONFIGURATION = ExtractJobConfiguration.builder(TABLE_ID, DESTINATION_URIS) .printHeader(PRINT_HEADER) .fieldDelimiter(FIELD_DELIMITER) .compression(COMPRESSION) .format(FORMAT) .build(); - private static final ExtractJobConfiguration EXTRACT_CONFIGURATION_ONE_URI = + private static final ExtractJobConfiguration DEPRECATED_EXTRACT_CONFIGURATION_ONE_URI = ExtractJobConfiguration.builder(TABLE_ID, DESTINATION_URI) .printHeader(PRINT_HEADER) .fieldDelimiter(FIELD_DELIMITER) @@ -56,29 +70,29 @@ public void testToBuilder() { compareExtractJobConfiguration( EXTRACT_CONFIGURATION, EXTRACT_CONFIGURATION.toBuilder().build()); ExtractJobConfiguration job = EXTRACT_CONFIGURATION.toBuilder() - .sourceTable(TableId.of("dataset", "newTable")) + .setSourceTable(TableId.of("dataset", "newTable")) .build(); - assertEquals("newTable", job.sourceTable().table()); - job = job.toBuilder().sourceTable(TABLE_ID).build(); + assertEquals("newTable", job.getSourceTable().getTable()); + job = job.toBuilder().setSourceTable(TABLE_ID).build(); compareExtractJobConfiguration(EXTRACT_CONFIGURATION, job); } @Test public void testOf() { ExtractJobConfiguration job = ExtractJobConfiguration.of(TABLE_ID, DESTINATION_URIS); - assertEquals(TABLE_ID, job.sourceTable()); - assertEquals(DESTINATION_URIS, job.destinationUris()); + assertEquals(TABLE_ID, job.getSourceTable()); + assertEquals(DESTINATION_URIS, job.getDestinationUris()); job = ExtractJobConfiguration.of(TABLE_ID, DESTINATION_URI); - assertEquals(TABLE_ID, job.sourceTable()); - assertEquals(ImmutableList.of(DESTINATION_URI), job.destinationUris()); + assertEquals(TABLE_ID, job.getSourceTable()); + assertEquals(ImmutableList.of(DESTINATION_URI), job.getDestinationUris()); job = ExtractJobConfiguration.of(TABLE_ID, DESTINATION_URIS, JSON_FORMAT); - assertEquals(TABLE_ID, job.sourceTable()); - assertEquals(DESTINATION_URIS, job.destinationUris()); - assertEquals(JSON_FORMAT, job.format()); + assertEquals(TABLE_ID, job.getSourceTable()); + assertEquals(DESTINATION_URIS, job.getDestinationUris()); + assertEquals(JSON_FORMAT, job.getFormat()); job = ExtractJobConfiguration.of(TABLE_ID, DESTINATION_URI, JSON_FORMAT); - assertEquals(TABLE_ID, job.sourceTable()); - assertEquals(ImmutableList.of(DESTINATION_URI), job.destinationUris()); - assertEquals(JSON_FORMAT, job.format()); + assertEquals(TABLE_ID, job.getSourceTable()); + assertEquals(ImmutableList.of(DESTINATION_URI), job.getDestinationUris()); + assertEquals(JSON_FORMAT, job.getFormat()); } @Test @@ -89,19 +103,36 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(TABLE_ID, EXTRACT_CONFIGURATION.sourceTable()); - assertEquals(DESTINATION_URIS, EXTRACT_CONFIGURATION.destinationUris()); - assertEquals(FIELD_DELIMITER, EXTRACT_CONFIGURATION.fieldDelimiter()); - assertEquals(COMPRESSION, EXTRACT_CONFIGURATION.compression()); + assertEquals(TABLE_ID, EXTRACT_CONFIGURATION.getSourceTable()); + assertEquals(DESTINATION_URIS, EXTRACT_CONFIGURATION.getDestinationUris()); + assertEquals(FIELD_DELIMITER, EXTRACT_CONFIGURATION.getFieldDelimiter()); + assertEquals(COMPRESSION, EXTRACT_CONFIGURATION.getCompression()); assertEquals(PRINT_HEADER, EXTRACT_CONFIGURATION.printHeader()); - assertEquals(FORMAT, EXTRACT_CONFIGURATION.format()); - assertEquals(TABLE_ID, EXTRACT_CONFIGURATION_ONE_URI.sourceTable()); + assertEquals(FORMAT, EXTRACT_CONFIGURATION.getFormat()); + assertEquals(TABLE_ID, EXTRACT_CONFIGURATION_ONE_URI.getSourceTable()); assertEquals(ImmutableList.of(DESTINATION_URI), - EXTRACT_CONFIGURATION_ONE_URI.destinationUris()); - assertEquals(FIELD_DELIMITER, EXTRACT_CONFIGURATION_ONE_URI.fieldDelimiter()); - assertEquals(COMPRESSION, EXTRACT_CONFIGURATION_ONE_URI.compression()); + EXTRACT_CONFIGURATION_ONE_URI.getDestinationUris()); + assertEquals(FIELD_DELIMITER, EXTRACT_CONFIGURATION_ONE_URI.getFieldDelimiter()); + assertEquals(COMPRESSION, EXTRACT_CONFIGURATION_ONE_URI.getCompression()); assertEquals(PRINT_HEADER, EXTRACT_CONFIGURATION_ONE_URI.printHeader()); - assertEquals(FORMAT, EXTRACT_CONFIGURATION_ONE_URI.format()); + assertEquals(FORMAT, EXTRACT_CONFIGURATION_ONE_URI.getFormat()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(TABLE_ID, DEPRECATED_EXTRACT_CONFIGURATION.sourceTable()); + assertEquals(DESTINATION_URIS, DEPRECATED_EXTRACT_CONFIGURATION.destinationUris()); + assertEquals(FIELD_DELIMITER, DEPRECATED_EXTRACT_CONFIGURATION.fieldDelimiter()); + assertEquals(COMPRESSION, DEPRECATED_EXTRACT_CONFIGURATION.compression()); + assertEquals(PRINT_HEADER, DEPRECATED_EXTRACT_CONFIGURATION.printHeader()); + assertEquals(FORMAT, DEPRECATED_EXTRACT_CONFIGURATION.format()); + assertEquals(TABLE_ID, DEPRECATED_EXTRACT_CONFIGURATION_ONE_URI.sourceTable()); + assertEquals(ImmutableList.of(DESTINATION_URI), + DEPRECATED_EXTRACT_CONFIGURATION_ONE_URI.destinationUris()); + assertEquals(FIELD_DELIMITER, DEPRECATED_EXTRACT_CONFIGURATION_ONE_URI.fieldDelimiter()); + assertEquals(COMPRESSION, DEPRECATED_EXTRACT_CONFIGURATION_ONE_URI.compression()); + assertEquals(PRINT_HEADER, DEPRECATED_EXTRACT_CONFIGURATION_ONE_URI.printHeader()); + assertEquals(FORMAT, DEPRECATED_EXTRACT_CONFIGURATION_ONE_URI.format()); } @Test @@ -121,7 +152,7 @@ public void testToPbAndFromPb() { @Test public void testSetProjectId() { ExtractJobConfiguration configuration = EXTRACT_CONFIGURATION.setProjectId("p"); - assertEquals("p", configuration.sourceTable().project()); + assertEquals("p", configuration.getSourceTable().getProject()); } private void compareExtractJobConfiguration(ExtractJobConfiguration expected, @@ -129,11 +160,11 @@ private void compareExtractJobConfiguration(ExtractJobConfiguration expected, assertEquals(expected, value); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); - assertEquals(expected.sourceTable(), value.sourceTable()); - assertEquals(expected.destinationUris(), value.destinationUris()); - assertEquals(expected.compression(), value.compression()); + assertEquals(expected.getSourceTable(), value.getSourceTable()); + assertEquals(expected.getDestinationUris(), value.getDestinationUris()); + assertEquals(expected.getCompression(), value.getCompression()); assertEquals(expected.printHeader(), value.printHeader()); - assertEquals(expected.fieldDelimiter(), value.fieldDelimiter()); - assertEquals(expected.format(), value.format()); + assertEquals(expected.getFieldDelimiter(), value.getFieldDelimiter()); + assertEquals(expected.getFormat(), value.getFormat()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FieldTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FieldTest.java index 8e044d889313..4dc34d35dd87 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FieldTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FieldTest.java @@ -35,17 +35,30 @@ public class FieldTest { private static final String FIELD_DESCRIPTION1 = "FieldDescription1"; private static final String FIELD_DESCRIPTION2 = "FieldDescription2"; private static final String FIELD_DESCRIPTION3 = "FieldDescription3"; - private static final Field FIELD_SCHEMA1 = Field.builder(FIELD_NAME1, FIELD_TYPE1) + private static final Field FIELD_SCHEMA1 = Field.newBuilder(FIELD_NAME1, FIELD_TYPE1) + .setMode(FIELD_MODE1) + .setDescription(FIELD_DESCRIPTION1) + .build(); + private static final Field FIELD_SCHEMA2 = Field.newBuilder(FIELD_NAME2, FIELD_TYPE2) + .setMode(FIELD_MODE2) + .setDescription(FIELD_DESCRIPTION2) + .build(); + private static final Field.Type FIELD_TYPE3 = + Field.Type.record(ImmutableList.of(FIELD_SCHEMA1, FIELD_SCHEMA2)); + private static final Field FIELD_SCHEMA3 = Field + .newBuilder(FIELD_NAME3, FIELD_TYPE3) + .setMode(FIELD_MODE3) + .setDescription(FIELD_DESCRIPTION3) + .build(); + private static final Field DEPRECATED_FIELD_SCHEMA1 = Field.builder(FIELD_NAME1, FIELD_TYPE1) .mode(FIELD_MODE1) .description(FIELD_DESCRIPTION1) .build(); - private static final Field FIELD_SCHEMA2 = Field.builder(FIELD_NAME2, FIELD_TYPE2) + private static final Field DEPRECATED_FIELD_SCHEMA2 = Field.builder(FIELD_NAME2, FIELD_TYPE2) .mode(FIELD_MODE2) .description(FIELD_DESCRIPTION2) .build(); - private static final Field.Type FIELD_TYPE3 = - Field.Type.record(ImmutableList.of(FIELD_SCHEMA1, FIELD_SCHEMA2)); - private static final Field FIELD_SCHEMA3 = Field + private static final Field DEPRECATED_FIELD_SCHEMA3 = Field .builder(FIELD_NAME3, FIELD_TYPE3) .mode(FIELD_MODE3) .description(FIELD_DESCRIPTION3) @@ -57,10 +70,10 @@ public void testToBuilder() { compareFieldSchemas(FIELD_SCHEMA2, FIELD_SCHEMA2.toBuilder().build()); compareFieldSchemas(FIELD_SCHEMA3, FIELD_SCHEMA3.toBuilder().build()); Field field = FIELD_SCHEMA1.toBuilder() - .description("New Description") + .setDescription("New Description") .build(); - assertEquals("New Description", field.description()); - field = field.toBuilder().description(FIELD_DESCRIPTION1).build(); + assertEquals("New Description", field.getDescription()); + field = field.toBuilder().setDescription(FIELD_DESCRIPTION1).build(); compareFieldSchemas(FIELD_SCHEMA1, field); } @@ -74,16 +87,31 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(FIELD_NAME1, FIELD_SCHEMA1.name()); - assertEquals(FIELD_TYPE1, FIELD_SCHEMA1.type()); - assertEquals(FIELD_MODE1, FIELD_SCHEMA1.mode()); - assertEquals(FIELD_DESCRIPTION1, FIELD_SCHEMA1.description()); - assertEquals(null, FIELD_SCHEMA1.fields()); - assertEquals(FIELD_NAME3, FIELD_SCHEMA3.name()); - assertEquals(FIELD_TYPE3, FIELD_SCHEMA3.type()); - assertEquals(FIELD_MODE3, FIELD_SCHEMA3.mode()); - assertEquals(FIELD_DESCRIPTION3, FIELD_SCHEMA3.description()); - assertEquals(ImmutableList.of(FIELD_SCHEMA1, FIELD_SCHEMA2), FIELD_SCHEMA3.fields()); + assertEquals(FIELD_NAME1, FIELD_SCHEMA1.getName()); + assertEquals(FIELD_TYPE1, FIELD_SCHEMA1.getType()); + assertEquals(FIELD_MODE1, FIELD_SCHEMA1.getMode()); + assertEquals(FIELD_DESCRIPTION1, FIELD_SCHEMA1.getDescription()); + assertEquals(null, FIELD_SCHEMA1.getFields()); + assertEquals(FIELD_NAME3, FIELD_SCHEMA3.getName()); + assertEquals(FIELD_TYPE3, FIELD_SCHEMA3.getType()); + assertEquals(FIELD_MODE3, FIELD_SCHEMA3.getMode()); + assertEquals(FIELD_DESCRIPTION3, FIELD_SCHEMA3.getDescription()); + assertEquals(ImmutableList.of(FIELD_SCHEMA1, FIELD_SCHEMA2), FIELD_SCHEMA3.getFields()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(FIELD_NAME1, DEPRECATED_FIELD_SCHEMA1.name()); + assertEquals(FIELD_TYPE1, DEPRECATED_FIELD_SCHEMA1.type()); + assertEquals(FIELD_MODE1, DEPRECATED_FIELD_SCHEMA1.mode()); + assertEquals(FIELD_DESCRIPTION1, DEPRECATED_FIELD_SCHEMA1.description()); + assertEquals(null, DEPRECATED_FIELD_SCHEMA1.fields()); + assertEquals(FIELD_NAME3, DEPRECATED_FIELD_SCHEMA3.name()); + assertEquals(FIELD_TYPE3, DEPRECATED_FIELD_SCHEMA3.type()); + assertEquals(FIELD_MODE3, DEPRECATED_FIELD_SCHEMA3.mode()); + assertEquals(FIELD_DESCRIPTION3, DEPRECATED_FIELD_SCHEMA3.description()); + assertEquals(ImmutableList.of(DEPRECATED_FIELD_SCHEMA1, DEPRECATED_FIELD_SCHEMA2), + DEPRECATED_FIELD_SCHEMA3.fields()); } @Test @@ -91,16 +119,16 @@ public void testToAndFromPb() { compareFieldSchemas(FIELD_SCHEMA1, Field.fromPb(FIELD_SCHEMA1.toPb())); compareFieldSchemas(FIELD_SCHEMA2, Field.fromPb(FIELD_SCHEMA2.toPb())); compareFieldSchemas(FIELD_SCHEMA3, Field.fromPb(FIELD_SCHEMA3.toPb())); - Field field = Field.builder(FIELD_NAME1, FIELD_TYPE1).build(); + Field field = Field.newBuilder(FIELD_NAME1, FIELD_TYPE1).build(); compareFieldSchemas(field, Field.fromPb(field.toPb())); } private void compareFieldSchemas(Field expected, Field value) { assertEquals(expected, value); - assertEquals(expected.name(), value.name()); - assertEquals(expected.type(), value.type()); - assertEquals(expected.mode(), value.mode()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.fields(), value.fields()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getType(), value.getType()); + assertEquals(expected.getMode(), value.getMode()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getFields(), value.getFields()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FieldValueTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FieldValueTest.java index e104ab909f5b..9c99b97d9318 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FieldValueTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FieldValueTest.java @@ -50,6 +50,38 @@ public class FieldValueTest { @Test public void testFromPb() { + FieldValue value = FieldValue.fromPb(BOOLEAN_FIELD); + assertEquals(FieldValue.Attribute.PRIMITIVE, value.getAttribute()); + assertFalse(value.getBooleanValue()); + value = FieldValue.fromPb(INTEGER_FIELD); + assertEquals(FieldValue.Attribute.PRIMITIVE, value.getAttribute()); + assertEquals(1, value.getLongValue()); + value = FieldValue.fromPb(FLOAT_FIELD); + assertEquals(FieldValue.Attribute.PRIMITIVE, value.getAttribute()); + assertEquals(1.5, value.getDoubleValue(), 0); + value = FieldValue.fromPb(STRING_FIELD); + assertEquals(FieldValue.Attribute.PRIMITIVE, value.getAttribute()); + assertEquals("string", value.getStringValue()); + value = FieldValue.fromPb(TIMESTAMP_FIELD); + assertEquals(FieldValue.Attribute.PRIMITIVE, value.getAttribute()); + assertEquals(42000000, value.getTimestampValue()); + value = FieldValue.fromPb(BYTES_FIELD); + assertEquals(FieldValue.Attribute.PRIMITIVE, value.getAttribute()); + assertArrayEquals(BYTES, value.getBytesValue()); + value = FieldValue.fromPb(NULL_FIELD); + assertNull(value.getValue()); + value = FieldValue.fromPb(REPEATED_FIELD); + assertEquals(FieldValue.Attribute.REPEATED, value.getAttribute()); + assertEquals(FieldValue.fromPb(INTEGER_FIELD), value.getRepeatedValue().get(0)); + assertEquals(FieldValue.fromPb(INTEGER_FIELD), value.getRepeatedValue().get(1)); + value = FieldValue.fromPb(RECORD_FIELD); + assertEquals(FieldValue.Attribute.RECORD, value.getAttribute()); + assertEquals(FieldValue.fromPb(FLOAT_FIELD), value.getRepeatedValue().get(0)); + assertEquals(FieldValue.fromPb(TIMESTAMP_FIELD), value.getRepeatedValue().get(1)); + } + + @Test + public void testFromPbDeprecated() { FieldValue value = FieldValue.fromPb(BOOLEAN_FIELD); assertEquals(FieldValue.Attribute.PRIMITIVE, value.attribute()); assertFalse(value.booleanValue()); diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FormatOptionsTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FormatOptionsTest.java index 7406d8a7a283..bd231f0249e6 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FormatOptionsTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/FormatOptionsTest.java @@ -24,6 +24,16 @@ public class FormatOptionsTest { @Test public void testConstructor() { + FormatOptions options = new FormatOptions(FormatOptions.CSV); + assertEquals(FormatOptions.CSV, options.getType()); + options = new FormatOptions(FormatOptions.JSON); + assertEquals(FormatOptions.JSON, options.getType()); + options = new FormatOptions(FormatOptions.DATASTORE_BACKUP); + assertEquals(FormatOptions.DATASTORE_BACKUP, options.getType()); + } + + @Test + public void testConstructorDeprecated() { FormatOptions options = new FormatOptions(FormatOptions.CSV); assertEquals(FormatOptions.CSV, options.type()); options = new FormatOptions(FormatOptions.JSON); @@ -34,9 +44,9 @@ public void testConstructor() { @Test public void testFactoryMethods() { - assertEquals(FormatOptions.CSV, FormatOptions.csv().type()); - assertEquals(FormatOptions.JSON, FormatOptions.json().type()); - assertEquals(FormatOptions.DATASTORE_BACKUP, FormatOptions.datastoreBackup().type()); + assertEquals(FormatOptions.CSV, FormatOptions.csv().getType()); + assertEquals(FormatOptions.JSON, FormatOptions.json().getType()); + assertEquals(FormatOptions.DATASTORE_BACKUP, FormatOptions.datastoreBackup().getType()); } @Test diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllRequestTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllRequestTest.java index 607b6c4145a8..a25622399aae 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllRequestTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllRequestTest.java @@ -48,95 +48,167 @@ public class InsertAllRequestTest { private static final boolean SKIP_INVALID_ROWS = true; private static final boolean IGNORE_UNKNOWN_VALUES = false; private static final String TEMPLATE_SUFFIX = "templateSuffix"; - private static final InsertAllRequest INSERT_ALL_REQUEST1 = InsertAllRequest.builder(TABLE_ID) + private static final InsertAllRequest INSERT_ALL_REQUEST1 = InsertAllRequest.newBuilder(TABLE_ID) .addRow(CONTENT1) .addRow(CONTENT2) - .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) - .skipInvalidRows(SKIP_INVALID_ROWS) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setSkipInvalidRows(SKIP_INVALID_ROWS) .build(); - private static final InsertAllRequest INSERT_ALL_REQUEST2 = InsertAllRequest.builder(TABLE_ID) - .rows(ROWS) - .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) - .skipInvalidRows(SKIP_INVALID_ROWS) + private static final InsertAllRequest INSERT_ALL_REQUEST2 = InsertAllRequest.newBuilder(TABLE_ID) + .setRows(ROWS) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setSkipInvalidRows(SKIP_INVALID_ROWS) .build(); private static final InsertAllRequest INSERT_ALL_REQUEST3 = - InsertAllRequest.builder(TABLE_ID.dataset(), TABLE_ID.table()) + InsertAllRequest.newBuilder(TABLE_ID.getDataset(), TABLE_ID.getTable()) + .setRows(ROWS_WITH_ID) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setSkipInvalidRows(SKIP_INVALID_ROWS) + .build(); + private static final InsertAllRequest INSERT_ALL_REQUEST4 = + InsertAllRequest.newBuilder(TABLE_ID, ROWS) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setSkipInvalidRows(SKIP_INVALID_ROWS) + .build(); + private static final InsertAllRequest INSERT_ALL_REQUEST5 = + InsertAllRequest.newBuilder(TABLE_ID.getDataset(), TABLE_ID.getTable(), ROWS_WITH_ID) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setSkipInvalidRows(SKIP_INVALID_ROWS) + .build(); + private static final InsertAllRequest INSERT_ALL_REQUEST6 = + InsertAllRequest.newBuilder(TABLE_ID, ROWS.get(0), ROWS.get(1)) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setSkipInvalidRows(SKIP_INVALID_ROWS) + .build(); + private static final InsertAllRequest INSERT_ALL_REQUEST7 = + InsertAllRequest.newBuilder(TABLE_ID.getDataset(), TABLE_ID.getTable(), ROWS_WITH_ID.get(0), + ROWS_WITH_ID.get(1)) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setSkipInvalidRows(SKIP_INVALID_ROWS) + .build(); + private static final InsertAllRequest INSERT_ALL_REQUEST8 = + InsertAllRequest.newBuilder(TABLE_ID.getDataset(), TABLE_ID.getTable()) + .addRow("id1", CONTENT1) + .addRow("id2", CONTENT2) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setSkipInvalidRows(SKIP_INVALID_ROWS) + .build(); + private static final InsertAllRequest INSERT_ALL_REQUEST9 = + InsertAllRequest.newBuilder(TABLE_INFO) + .addRow("id1", CONTENT1) + .addRow("id2", CONTENT2) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setSkipInvalidRows(SKIP_INVALID_ROWS) + .build(); + private static final InsertAllRequest INSERT_ALL_REQUEST10 = + InsertAllRequest.newBuilder(TABLE_INFO) + .addRow("id1", CONTENT1) + .addRow("id2", CONTENT2) + .setIgnoreUnknownValues(true) + .setSkipInvalidRows(false) + .build(); + private static final InsertAllRequest INSERT_ALL_REQUEST11 = + InsertAllRequest.newBuilder(TABLE_INFO) + .addRow("id1", CONTENT1) + .addRow("id2", CONTENT2) + .setIgnoreUnknownValues(true) + .setSkipInvalidRows(false) + .setTemplateSuffix(TEMPLATE_SUFFIX) + .build(); + private static final InsertAllRequest DEPRECATED_INSERT_ALL_REQUEST1 = + InsertAllRequest.builder(TABLE_ID) + .addRow(CONTENT1) + .addRow(CONTENT2) + .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .skipInvalidRows(SKIP_INVALID_ROWS) + .build(); + private static final InsertAllRequest DEPRECATED_INSERT_ALL_REQUEST2 = + InsertAllRequest.builder(TABLE_ID) + .rows(ROWS) + .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .skipInvalidRows(SKIP_INVALID_ROWS) + .build(); + private static final InsertAllRequest DEPRECATED_INSERT_ALL_REQUEST3 = + InsertAllRequest.builder(TABLE_ID.getDataset(), TABLE_ID.getTable()) .rows(ROWS_WITH_ID) .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) .skipInvalidRows(SKIP_INVALID_ROWS) .build(); - private static final InsertAllRequest INSERT_ALL_REQUEST4 = + private static final InsertAllRequest DEPRECATED_INSERT_ALL_REQUEST4 = InsertAllRequest.builder(TABLE_ID, ROWS) .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) .skipInvalidRows(SKIP_INVALID_ROWS) .build(); - private static final InsertAllRequest INSERT_ALL_REQUEST5 = - InsertAllRequest.builder(TABLE_ID.dataset(), TABLE_ID.table(), ROWS_WITH_ID) + private static final InsertAllRequest DEPRECATED_INSERT_ALL_REQUEST5 = + InsertAllRequest.builder(TABLE_ID.getDataset(), TABLE_ID.getTable(), ROWS_WITH_ID) .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) .skipInvalidRows(SKIP_INVALID_ROWS) .build(); - private static final InsertAllRequest INSERT_ALL_REQUEST6 = + private static final InsertAllRequest DEPRECATED_INSERT_ALL_REQUEST6 = InsertAllRequest.builder(TABLE_ID, ROWS.get(0), ROWS.get(1)) .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) .skipInvalidRows(SKIP_INVALID_ROWS) .build(); - private static final InsertAllRequest INSERT_ALL_REQUEST7 = - InsertAllRequest.builder(TABLE_ID.dataset(), TABLE_ID.table(), ROWS_WITH_ID.get(0), + private static final InsertAllRequest DEPRECATED_INSERT_ALL_REQUEST7 = + InsertAllRequest.builder(TABLE_ID.getDataset(), TABLE_ID.getTable(), ROWS_WITH_ID.get(0), ROWS_WITH_ID.get(1)) .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) .skipInvalidRows(SKIP_INVALID_ROWS) .build(); - private static final InsertAllRequest INSERT_ALL_REQUEST8 = - InsertAllRequest.builder(TABLE_ID.dataset(), TABLE_ID.table()) + private static final InsertAllRequest DEPRECATED_INSERT_ALL_REQUEST8 = + InsertAllRequest.builder(TABLE_ID.getDataset(), TABLE_ID.getTable()) .addRow("id1", CONTENT1) .addRow("id2", CONTENT2) .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) .skipInvalidRows(SKIP_INVALID_ROWS) .build(); - private static final InsertAllRequest INSERT_ALL_REQUEST9 = InsertAllRequest.builder(TABLE_INFO) - .addRow("id1", CONTENT1) - .addRow("id2", CONTENT2) - .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) - .skipInvalidRows(SKIP_INVALID_ROWS) - .build(); - private static final InsertAllRequest INSERT_ALL_REQUEST10 = InsertAllRequest.builder(TABLE_INFO) - .addRow("id1", CONTENT1) - .addRow("id2", CONTENT2) - .ignoreUnknownValues(true) - .skipInvalidRows(false) - .build(); - private static final InsertAllRequest INSERT_ALL_REQUEST11 = InsertAllRequest.builder(TABLE_INFO) - .addRow("id1", CONTENT1) - .addRow("id2", CONTENT2) - .ignoreUnknownValues(true) - .skipInvalidRows(false) - .templateSuffix(TEMPLATE_SUFFIX) - .build(); + private static final InsertAllRequest DEPRECATED_INSERT_ALL_REQUEST9 = + InsertAllRequest.builder(TABLE_INFO) + .addRow("id1", CONTENT1) + .addRow("id2", CONTENT2) + .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .skipInvalidRows(SKIP_INVALID_ROWS) + .build(); + private static final InsertAllRequest DEPRECATED_INSERT_ALL_REQUEST10 = + InsertAllRequest.builder(TABLE_INFO) + .addRow("id1", CONTENT1) + .addRow("id2", CONTENT2) + .ignoreUnknownValues(true) + .skipInvalidRows(false) + .build(); + private static final InsertAllRequest DEPRECATED_INSERT_ALL_REQUEST11 = + InsertAllRequest.builder(TABLE_INFO) + .addRow("id1", CONTENT1) + .addRow("id2", CONTENT2) + .ignoreUnknownValues(true) + .skipInvalidRows(false) + .templateSuffix(TEMPLATE_SUFFIX) + .build(); @Test public void testBuilder() { - assertEquals(TABLE_ID, INSERT_ALL_REQUEST1.table()); - assertEquals(TABLE_ID, INSERT_ALL_REQUEST2.table()); - assertEquals(TABLE_ID, INSERT_ALL_REQUEST3.table()); - assertEquals(TABLE_ID, INSERT_ALL_REQUEST4.table()); - assertEquals(TABLE_ID, INSERT_ALL_REQUEST5.table()); - assertEquals(TABLE_ID, INSERT_ALL_REQUEST6.table()); - assertEquals(TABLE_ID, INSERT_ALL_REQUEST7.table()); - assertEquals(TABLE_ID, INSERT_ALL_REQUEST8.table()); - assertEquals(TABLE_ID, INSERT_ALL_REQUEST9.table()); - assertEquals(TABLE_ID, INSERT_ALL_REQUEST10.table()); - assertEquals(TABLE_ID, INSERT_ALL_REQUEST11.table()); - assertEquals(ROWS, INSERT_ALL_REQUEST1.rows()); - assertEquals(ROWS, INSERT_ALL_REQUEST2.rows()); - assertEquals(ROWS, INSERT_ALL_REQUEST4.rows()); - assertEquals(ROWS, INSERT_ALL_REQUEST6.rows()); - assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST3.rows()); - assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST5.rows()); - assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST7.rows()); - assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST8.rows()); - assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST9.rows()); - assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST10.rows()); - assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST11.rows()); + assertEquals(TABLE_ID, INSERT_ALL_REQUEST1.getTable()); + assertEquals(TABLE_ID, INSERT_ALL_REQUEST2.getTable()); + assertEquals(TABLE_ID, INSERT_ALL_REQUEST3.getTable()); + assertEquals(TABLE_ID, INSERT_ALL_REQUEST4.getTable()); + assertEquals(TABLE_ID, INSERT_ALL_REQUEST5.getTable()); + assertEquals(TABLE_ID, INSERT_ALL_REQUEST6.getTable()); + assertEquals(TABLE_ID, INSERT_ALL_REQUEST7.getTable()); + assertEquals(TABLE_ID, INSERT_ALL_REQUEST8.getTable()); + assertEquals(TABLE_ID, INSERT_ALL_REQUEST9.getTable()); + assertEquals(TABLE_ID, INSERT_ALL_REQUEST10.getTable()); + assertEquals(TABLE_ID, INSERT_ALL_REQUEST11.getTable()); + assertEquals(ROWS, INSERT_ALL_REQUEST1.getRows()); + assertEquals(ROWS, INSERT_ALL_REQUEST2.getRows()); + assertEquals(ROWS, INSERT_ALL_REQUEST4.getRows()); + assertEquals(ROWS, INSERT_ALL_REQUEST6.getRows()); + assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST3.getRows()); + assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST5.getRows()); + assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST7.getRows()); + assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST8.getRows()); + assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST9.getRows()); + assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST10.getRows()); + assertEquals(ROWS_WITH_ID, INSERT_ALL_REQUEST11.getRows()); assertEquals(SKIP_INVALID_ROWS, INSERT_ALL_REQUEST1.skipInvalidRows()); assertEquals(SKIP_INVALID_ROWS, INSERT_ALL_REQUEST2.skipInvalidRows()); assertEquals(SKIP_INVALID_ROWS, INSERT_ALL_REQUEST3.skipInvalidRows()); @@ -159,42 +231,101 @@ public void testBuilder() { assertEquals(IGNORE_UNKNOWN_VALUES, INSERT_ALL_REQUEST9.ignoreUnknownValues()); assertTrue(INSERT_ALL_REQUEST10.ignoreUnknownValues()); assertTrue(INSERT_ALL_REQUEST11.ignoreUnknownValues()); - assertNull(INSERT_ALL_REQUEST1.templateSuffix()); - assertNull(INSERT_ALL_REQUEST2.templateSuffix()); - assertNull(INSERT_ALL_REQUEST3.templateSuffix()); - assertNull(INSERT_ALL_REQUEST4.templateSuffix()); - assertNull(INSERT_ALL_REQUEST5.templateSuffix()); - assertNull(INSERT_ALL_REQUEST6.templateSuffix()); - assertNull(INSERT_ALL_REQUEST7.templateSuffix()); - assertNull(INSERT_ALL_REQUEST8.templateSuffix()); - assertNull(INSERT_ALL_REQUEST9.templateSuffix()); - assertNull(INSERT_ALL_REQUEST10.templateSuffix()); - assertEquals(TEMPLATE_SUFFIX, INSERT_ALL_REQUEST11.templateSuffix()); + assertNull(INSERT_ALL_REQUEST1.getTemplateSuffix()); + assertNull(INSERT_ALL_REQUEST2.getTemplateSuffix()); + assertNull(INSERT_ALL_REQUEST3.getTemplateSuffix()); + assertNull(INSERT_ALL_REQUEST4.getTemplateSuffix()); + assertNull(INSERT_ALL_REQUEST5.getTemplateSuffix()); + assertNull(INSERT_ALL_REQUEST6.getTemplateSuffix()); + assertNull(INSERT_ALL_REQUEST7.getTemplateSuffix()); + assertNull(INSERT_ALL_REQUEST8.getTemplateSuffix()); + assertNull(INSERT_ALL_REQUEST9.getTemplateSuffix()); + assertNull(INSERT_ALL_REQUEST10.getTemplateSuffix()); + assertEquals(TEMPLATE_SUFFIX, INSERT_ALL_REQUEST11.getTemplateSuffix()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(TABLE_ID, DEPRECATED_INSERT_ALL_REQUEST1.getTable()); + assertEquals(TABLE_ID, DEPRECATED_INSERT_ALL_REQUEST2.getTable()); + assertEquals(TABLE_ID, DEPRECATED_INSERT_ALL_REQUEST3.getTable()); + assertEquals(TABLE_ID, DEPRECATED_INSERT_ALL_REQUEST4.getTable()); + assertEquals(TABLE_ID, DEPRECATED_INSERT_ALL_REQUEST5.getTable()); + assertEquals(TABLE_ID, DEPRECATED_INSERT_ALL_REQUEST6.getTable()); + assertEquals(TABLE_ID, DEPRECATED_INSERT_ALL_REQUEST7.getTable()); + assertEquals(TABLE_ID, DEPRECATED_INSERT_ALL_REQUEST8.getTable()); + assertEquals(TABLE_ID, DEPRECATED_INSERT_ALL_REQUEST9.getTable()); + assertEquals(TABLE_ID, DEPRECATED_INSERT_ALL_REQUEST10.getTable()); + assertEquals(TABLE_ID, DEPRECATED_INSERT_ALL_REQUEST11.getTable()); + assertEquals(ROWS, DEPRECATED_INSERT_ALL_REQUEST1.rows()); + assertEquals(ROWS, DEPRECATED_INSERT_ALL_REQUEST2.rows()); + assertEquals(ROWS, DEPRECATED_INSERT_ALL_REQUEST4.rows()); + assertEquals(ROWS, DEPRECATED_INSERT_ALL_REQUEST6.rows()); + assertEquals(ROWS_WITH_ID, DEPRECATED_INSERT_ALL_REQUEST3.rows()); + assertEquals(ROWS_WITH_ID, DEPRECATED_INSERT_ALL_REQUEST5.rows()); + assertEquals(ROWS_WITH_ID, DEPRECATED_INSERT_ALL_REQUEST7.rows()); + assertEquals(ROWS_WITH_ID, DEPRECATED_INSERT_ALL_REQUEST8.rows()); + assertEquals(ROWS_WITH_ID, DEPRECATED_INSERT_ALL_REQUEST9.rows()); + assertEquals(ROWS_WITH_ID, DEPRECATED_INSERT_ALL_REQUEST10.rows()); + assertEquals(ROWS_WITH_ID, DEPRECATED_INSERT_ALL_REQUEST11.rows()); + assertEquals(SKIP_INVALID_ROWS, DEPRECATED_INSERT_ALL_REQUEST1.skipInvalidRows()); + assertEquals(SKIP_INVALID_ROWS, DEPRECATED_INSERT_ALL_REQUEST2.skipInvalidRows()); + assertEquals(SKIP_INVALID_ROWS, DEPRECATED_INSERT_ALL_REQUEST3.skipInvalidRows()); + assertEquals(SKIP_INVALID_ROWS, DEPRECATED_INSERT_ALL_REQUEST4.skipInvalidRows()); + assertEquals(SKIP_INVALID_ROWS, DEPRECATED_INSERT_ALL_REQUEST5.skipInvalidRows()); + assertEquals(SKIP_INVALID_ROWS, DEPRECATED_INSERT_ALL_REQUEST6.skipInvalidRows()); + assertEquals(SKIP_INVALID_ROWS, DEPRECATED_INSERT_ALL_REQUEST7.skipInvalidRows()); + assertEquals(SKIP_INVALID_ROWS, DEPRECATED_INSERT_ALL_REQUEST8.skipInvalidRows()); + assertEquals(SKIP_INVALID_ROWS, DEPRECATED_INSERT_ALL_REQUEST9.skipInvalidRows()); + assertFalse(DEPRECATED_INSERT_ALL_REQUEST10.skipInvalidRows()); + assertFalse(DEPRECATED_INSERT_ALL_REQUEST11.skipInvalidRows()); + assertEquals(IGNORE_UNKNOWN_VALUES, DEPRECATED_INSERT_ALL_REQUEST1.ignoreUnknownValues()); + assertEquals(IGNORE_UNKNOWN_VALUES, DEPRECATED_INSERT_ALL_REQUEST2.ignoreUnknownValues()); + assertEquals(IGNORE_UNKNOWN_VALUES, DEPRECATED_INSERT_ALL_REQUEST3.ignoreUnknownValues()); + assertEquals(IGNORE_UNKNOWN_VALUES, DEPRECATED_INSERT_ALL_REQUEST4.ignoreUnknownValues()); + assertEquals(IGNORE_UNKNOWN_VALUES, DEPRECATED_INSERT_ALL_REQUEST5.ignoreUnknownValues()); + assertEquals(IGNORE_UNKNOWN_VALUES, DEPRECATED_INSERT_ALL_REQUEST6.ignoreUnknownValues()); + assertEquals(IGNORE_UNKNOWN_VALUES, DEPRECATED_INSERT_ALL_REQUEST7.ignoreUnknownValues()); + assertEquals(IGNORE_UNKNOWN_VALUES, DEPRECATED_INSERT_ALL_REQUEST8.ignoreUnknownValues()); + assertEquals(IGNORE_UNKNOWN_VALUES, DEPRECATED_INSERT_ALL_REQUEST9.ignoreUnknownValues()); + assertTrue(DEPRECATED_INSERT_ALL_REQUEST10.ignoreUnknownValues()); + assertTrue(DEPRECATED_INSERT_ALL_REQUEST11.ignoreUnknownValues()); + assertNull(DEPRECATED_INSERT_ALL_REQUEST1.templateSuffix()); + assertNull(DEPRECATED_INSERT_ALL_REQUEST2.templateSuffix()); + assertNull(DEPRECATED_INSERT_ALL_REQUEST3.templateSuffix()); + assertNull(DEPRECATED_INSERT_ALL_REQUEST4.templateSuffix()); + assertNull(DEPRECATED_INSERT_ALL_REQUEST5.templateSuffix()); + assertNull(DEPRECATED_INSERT_ALL_REQUEST6.templateSuffix()); + assertNull(DEPRECATED_INSERT_ALL_REQUEST7.templateSuffix()); + assertNull(DEPRECATED_INSERT_ALL_REQUEST8.templateSuffix()); + assertNull(DEPRECATED_INSERT_ALL_REQUEST9.templateSuffix()); + assertNull(DEPRECATED_INSERT_ALL_REQUEST10.templateSuffix()); + assertEquals(TEMPLATE_SUFFIX, DEPRECATED_INSERT_ALL_REQUEST11.templateSuffix()); } @Test public void testOf() { InsertAllRequest request = InsertAllRequest.of(TABLE_ID, ROWS); - assertEquals(TABLE_ID, request.table()); - assertEquals(ROWS, request.rows()); + assertEquals(TABLE_ID, request.getTable()); + assertEquals(ROWS, request.getRows()); request = InsertAllRequest.of(TABLE_INFO, ROWS); - assertEquals(TABLE_ID, request.table()); - assertEquals(ROWS, request.rows()); - request = InsertAllRequest.of(TABLE_ID.dataset(), TABLE_ID.table(), ROWS); - assertEquals(TABLE_ID, request.table()); - assertEquals(ROWS, request.rows()); - request = InsertAllRequest.of(TABLE_ID.dataset(), TABLE_ID.table(), ROWS); - assertEquals(TABLE_ID, request.table()); - assertEquals(ROWS, request.rows()); + assertEquals(TABLE_ID, request.getTable()); + assertEquals(ROWS, request.getRows()); + request = InsertAllRequest.of(TABLE_ID.getDataset(), TABLE_ID.getTable(), ROWS); + assertEquals(TABLE_ID, request.getTable()); + assertEquals(ROWS, request.getRows()); + request = InsertAllRequest.of(TABLE_ID.getDataset(), TABLE_ID.getTable(), ROWS); + assertEquals(TABLE_ID, request.getTable()); + assertEquals(ROWS, request.getRows()); request = InsertAllRequest.of(TABLE_ID, ROWS.get(0), ROWS.get(1)); - assertEquals(TABLE_ID, request.table()); - assertEquals(ROWS, request.rows()); + assertEquals(TABLE_ID, request.getTable()); + assertEquals(ROWS, request.getRows()); request = InsertAllRequest.of(TABLE_INFO, ROWS.get(0), ROWS.get(1)); - assertEquals(TABLE_ID, request.table()); - assertEquals(ROWS, request.rows()); - request = InsertAllRequest.of(TABLE_ID.dataset(), TABLE_ID.table(), ROWS.get(0), ROWS.get(1)); - assertEquals(TABLE_ID, request.table()); - assertEquals(ROWS, request.rows()); + assertEquals(TABLE_ID, request.getTable()); + assertEquals(ROWS, request.getRows()); + request = InsertAllRequest.of(TABLE_ID.getDataset(), TABLE_ID.getTable(), ROWS.get(0), ROWS.get(1)); + assertEquals(TABLE_ID, request.getTable()); + assertEquals(ROWS, request.getRows()); } @Test @@ -214,10 +345,10 @@ private void compareInsertAllRequest(InsertAllRequest expected, InsertAllRequest assertEquals(expected, value); assertEquals(expected.toString(), value.toString()); assertEquals(expected.hashCode(), value.hashCode()); - assertEquals(expected.table(), value.table()); - assertEquals(expected.rows(), value.rows()); + assertEquals(expected.getTable(), value.getTable()); + assertEquals(expected.getRows(), value.getRows()); assertEquals(expected.ignoreUnknownValues(), value.ignoreUnknownValues()); assertEquals(expected.skipInvalidRows(), value.skipInvalidRows()); - assertEquals(expected.templateSuffix(), value.templateSuffix()); + assertEquals(expected.getTemplateSuffix(), value.getTemplateSuffix()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllResponseTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllResponseTest.java index dc30620200bc..932fa6825f6e 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllResponseTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllResponseTest.java @@ -49,6 +49,15 @@ public void testConstructor() { @Test public void testErrorsFor() { + assertEquals(ERRORS_MAP, INSERT_ALL_RESPONSE.getInsertErrors()); + assertEquals(ERRORS1, INSERT_ALL_RESPONSE.getErrorsFor(0L)); + assertEquals(ERRORS2, INSERT_ALL_RESPONSE.getErrorsFor(1L)); + assertNull(INSERT_ALL_RESPONSE.getErrorsFor(2L)); + } + + @Test + public void testErrorsForDeprecated() { + assertEquals(ERRORS_MAP, INSERT_ALL_RESPONSE.insertErrors()); assertEquals(ERRORS1, INSERT_ALL_RESPONSE.errorsFor(0L)); assertEquals(ERRORS2, INSERT_ALL_RESPONSE.errorsFor(1L)); assertNull(INSERT_ALL_RESPONSE.errorsFor(2L)); @@ -72,6 +81,6 @@ private void compareInsertAllResponse(InsertAllResponse expected, InsertAllRespo assertEquals(expected, value); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); - assertEquals(expected.insertErrors(), value.insertErrors()); + assertEquals(expected.getInsertErrors(), value.getInsertErrors()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobIdTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobIdTest.java index 79701720412e..92a601c6d167 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobIdTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobIdTest.java @@ -27,6 +27,14 @@ public class JobIdTest { @Test public void testOf() { + assertEquals(null, JOB.getProject()); + assertEquals("job", JOB.getJob()); + assertEquals("project", JOB_COMPLETE.getProject()); + assertEquals("job", JOB_COMPLETE.getJob()); + } + + @Test + public void testOfDeprecated() { assertEquals(null, JOB.project()); assertEquals("job", JOB.job()); assertEquals("project", JOB_COMPLETE.project()); @@ -54,8 +62,8 @@ private void compareJobs(JobId expected, JobId value) { assertEquals(expected, value); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); - assertEquals(expected.project(), value.project()); - assertEquals(expected.job(), value.job()); + assertEquals(expected.getProject(), value.getProject()); + assertEquals(expected.getJob(), value.getJob()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobInfoTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobInfoTest.java index b08660268a61..c9d669abf43d 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobInfoTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobInfoTest.java @@ -43,65 +43,65 @@ public class JobInfoTest { private static final String EMAIL = "email"; private static final JobId JOB_ID = JobId.of("job"); private static final JobStatus JOB_STATUS = new JobStatus(JobStatus.State.DONE); - private static final CopyStatistics COPY_JOB_STATISTICS = CopyStatistics.builder() - .creationTime(1L) - .endTime(3L) - .startTime(2L) + private static final CopyStatistics COPY_JOB_STATISTICS = CopyStatistics.newBuilder() + .setCreationTimestamp(1L) + .setEndTime(3L) + .setStartTime(2L) .build(); private static final ExtractStatistics EXTRACT_JOB_STATISTICS = - ExtractStatistics.builder() - .creationTime(1L) - .endTime(3L) - .startTime(2L) - .destinationUriFileCounts(ImmutableList.of(42L)) + ExtractStatistics.newBuilder() + .setCreationTimestamp(1L) + .setEndTime(3L) + .setStartTime(2L) + .setDestinationUriFileCounts(ImmutableList.of(42L)) .build(); private static final LoadStatistics LOAD_JOB_STATISTICS = - LoadStatistics.builder() - .creationTime(1L) - .endTime(3L) - .startTime(2L) - .inputFiles(42L) - .outputBytes(1024L) - .inputBytes(2048L) - .outputRows(24L) + LoadStatistics.newBuilder() + .setCreationTimestamp(1L) + .setEndTime(3L) + .setStartTime(2L) + .setInputFiles(42L) + .setOutputBytes(1024L) + .setInputBytes(2048L) + .setOutputRows(24L) .build(); private static final QueryStatistics QUERY_JOB_STATISTICS = - QueryStatistics.builder() - .creationTime(1L) - .endTime(3L) - .startTime(2L) - .totalBytesProcessed(2048L) - .totalBytesBilled(1024L) - .cacheHit(false) - .billingTier(42) + QueryStatistics.newBuilder() + .setCreationTimestamp(1L) + .setEndTime(3L) + .setStartTime(2L) + .setTotalBytesProcessed(2048L) + .setTotalBytesBilled(1024L) + .setCacheHit(false) + .setBillingTier(42) .build(); private static final TableId SOURCE_TABLE = TableId.of("dataset", "sourceTable"); private static final TableId DESTINATION_TABLE = TableId.of("dataset", "destinationTable"); private static final CreateDisposition CREATE_DISPOSITION = CreateDisposition.CREATE_IF_NEEDED; private static final WriteDisposition WRITE_DISPOSITION = WriteDisposition.WRITE_APPEND; private static final CopyJobConfiguration COPY_CONFIGURATION = - CopyJobConfiguration.builder(DESTINATION_TABLE, SOURCE_TABLE) - .createDisposition(CREATE_DISPOSITION) - .writeDisposition(WRITE_DISPOSITION) + CopyJobConfiguration.newBuilder(DESTINATION_TABLE, SOURCE_TABLE) + .setCreateDisposition(CREATE_DISPOSITION) + .setWriteDisposition(WRITE_DISPOSITION) .build(); private static final List DESTINATION_URIS = ImmutableList.of("uri1", "uri2"); private static final TableId TABLE_ID = TableId.of("dataset", "table"); private static final DatasetId DATASET_ID = DatasetId.of("dataset"); private static final List SOURCE_URIS = ImmutableList.of("uri1", "uri2"); private static final Field FIELD_SCHEMA1 = - Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) - .description("FieldDescription1") + Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) + .setDescription("FieldDescription1") .build(); private static final Field FIELD_SCHEMA2 = - Field.builder("IntegerField", Field.Type.integer()) - .mode(Field.Mode.REPEATED) - .description("FieldDescription2") + Field.newBuilder("IntegerField", Field.Type.integer()) + .setMode(Field.Mode.REPEATED) + .setDescription("FieldDescription2") .build(); private static final Field FIELD_SCHEMA3 = - Field.builder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) - .mode(Field.Mode.REQUIRED) - .description("FieldDescription3") + Field.newBuilder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) + .setMode(Field.Mode.REQUIRED) + .setDescription("FieldDescription3") .build(); private static final Schema TABLE_SCHEMA = Schema.of(FIELD_SCHEMA1, FIELD_SCHEMA2, FIELD_SCHEMA3); private static final String FIELD_DELIMITER = ","; @@ -109,31 +109,31 @@ public class JobInfoTest { private static final Boolean PRINT_HEADER = true; private static final String COMPRESSION = "GZIP"; private static final ExtractJobConfiguration EXTRACT_CONFIGURATION = - ExtractJobConfiguration.builder(TABLE_ID, DESTINATION_URIS) - .printHeader(PRINT_HEADER) - .fieldDelimiter(FIELD_DELIMITER) - .compression(COMPRESSION) - .format(FORMAT) + ExtractJobConfiguration.newBuilder(TABLE_ID, DESTINATION_URIS) + .setPrintHeader(PRINT_HEADER) + .setFieldDelimiter(FIELD_DELIMITER) + .setCompression(COMPRESSION) + .setFormat(FORMAT) .build(); private static final List PROJECTION_FIELDS = ImmutableList.of("field1", "field2"); private static final Integer MAX_BAD_RECORDS = 42; private static final Boolean IGNORE_UNKNOWN_VALUES = true; - private static final CsvOptions CSV_OPTIONS = CsvOptions.builder().build(); + private static final CsvOptions CSV_OPTIONS = CsvOptions.newBuilder().build(); private static final ExternalTableDefinition TABLE_CONFIGURATION = - ExternalTableDefinition.builder(SOURCE_URIS, TABLE_SCHEMA, CSV_OPTIONS) - .compression(COMPRESSION) - .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) - .maxBadRecords(MAX_BAD_RECORDS) + ExternalTableDefinition.newBuilder(SOURCE_URIS, TABLE_SCHEMA, CSV_OPTIONS) + .setCompression(COMPRESSION) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setMaxBadRecords(MAX_BAD_RECORDS) .build(); private static final LoadJobConfiguration LOAD_CONFIGURATION = - LoadJobConfiguration.builder(TABLE_ID, SOURCE_URIS) - .createDisposition(CREATE_DISPOSITION) - .writeDisposition(WRITE_DISPOSITION) - .formatOptions(CSV_OPTIONS) - .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) - .maxBadRecords(MAX_BAD_RECORDS) - .projectionFields(PROJECTION_FIELDS) - .schema(TABLE_SCHEMA) + LoadJobConfiguration.newBuilder(TABLE_ID, SOURCE_URIS) + .setCreateDisposition(CREATE_DISPOSITION) + .setWriteDisposition(WRITE_DISPOSITION) + .setFormatOptions(CSV_OPTIONS) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setMaxBadRecords(MAX_BAD_RECORDS) + .setProjectionFields(PROJECTION_FIELDS) + .setSchema(TABLE_SCHEMA) .build(); private static final String QUERY = "BigQuery SQL"; private static final Map TABLE_DEFINITIONS = @@ -146,61 +146,100 @@ public class JobInfoTest { private static final List USER_DEFINED_FUNCTIONS = ImmutableList.of( UserDefinedFunction.inline("Function"), UserDefinedFunction.fromUri("URI")); private static final QueryJobConfiguration QUERY_CONFIGURATION = - QueryJobConfiguration.builder(QUERY) - .useQueryCache(USE_QUERY_CACHE) - .tableDefinitions(TABLE_DEFINITIONS) - .allowLargeResults(ALLOW_LARGE_RESULTS) - .createDisposition(CREATE_DISPOSITION) - .defaultDataset(DATASET_ID) - .destinationTable(TABLE_ID) - .writeDisposition(WRITE_DISPOSITION) - .priority(PRIORITY) - .flattenResults(FLATTEN_RESULTS) - .userDefinedFunctions(USER_DEFINED_FUNCTIONS) - .dryRun(true) + QueryJobConfiguration.newBuilder(QUERY) + .setUseQueryCache(USE_QUERY_CACHE) + .setTableDefinitions(TABLE_DEFINITIONS) + .setAllowLargeResults(ALLOW_LARGE_RESULTS) + .setCreateDisposition(CREATE_DISPOSITION) + .setDefaultDataset(DATASET_ID) + .setDestinationTable(TABLE_ID) + .setWriteDisposition(WRITE_DISPOSITION) + .setPriority(PRIORITY) + .setFlattenResults(FLATTEN_RESULTS) + .setUserDefinedFunctions(USER_DEFINED_FUNCTIONS) + .setDryRun(true) .build(); - private static final JobInfo COPY_JOB = JobInfo.builder(COPY_CONFIGURATION) + private static final JobInfo COPY_JOB = JobInfo.newBuilder(COPY_CONFIGURATION) + .setJobId(JOB_ID) + .setStatistics(COPY_JOB_STATISTICS) + .setJobId(JOB_ID) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setSelfLink(SELF_LINK) + .setUserEmail(EMAIL) + .setStatus(JOB_STATUS) + .build(); + private static final JobInfo EXTRACT_JOB = JobInfo.newBuilder(EXTRACT_CONFIGURATION) + .setJobId(JOB_ID) + .setStatistics(EXTRACT_JOB_STATISTICS) + .setJobId(JOB_ID) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setSelfLink(SELF_LINK) + .setUserEmail(EMAIL) + .setStatus(JOB_STATUS) + .build(); + private static final JobInfo LOAD_JOB = JobInfo.newBuilder(LOAD_CONFIGURATION) + .setJobId(JOB_ID) + .setStatistics(LOAD_JOB_STATISTICS) + .setJobId(JOB_ID) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setSelfLink(SELF_LINK) + .setUserEmail(EMAIL) + .setStatus(JOB_STATUS) + .build(); + private static final JobInfo QUERY_JOB = JobInfo.newBuilder(QUERY_CONFIGURATION) + .setJobId(JOB_ID) + .setStatistics(QUERY_JOB_STATISTICS) + .setJobId(JOB_ID) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setSelfLink(SELF_LINK) + .setUserEmail(EMAIL) + .setStatus(JOB_STATUS) + .build(); + private static final JobInfo DEPRECATED_COPY_JOB = JobInfo.builder(COPY_CONFIGURATION) .jobId(JOB_ID) - .statistics(COPY_JOB_STATISTICS) + .setStatistics(COPY_JOB_STATISTICS) .jobId(JOB_ID) - .etag(ETAG) - .generatedId(GENERATED_ID) - .selfLink(SELF_LINK) - .userEmail(EMAIL) - .status(JOB_STATUS) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setSelfLink(SELF_LINK) + .setUserEmail(EMAIL) + .setStatus(JOB_STATUS) .build(); - private static final JobInfo EXTRACT_JOB = JobInfo.builder(EXTRACT_CONFIGURATION) + private static final JobInfo DEPRECATED_EXTRACT_JOB = JobInfo.builder(EXTRACT_CONFIGURATION) .jobId(JOB_ID) - .statistics(EXTRACT_JOB_STATISTICS) + .setStatistics(EXTRACT_JOB_STATISTICS) .jobId(JOB_ID) - .etag(ETAG) - .generatedId(GENERATED_ID) - .selfLink(SELF_LINK) - .userEmail(EMAIL) - .status(JOB_STATUS) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setSelfLink(SELF_LINK) + .setUserEmail(EMAIL) + .setStatus(JOB_STATUS) .build(); - private static final JobInfo LOAD_JOB = JobInfo.builder(LOAD_CONFIGURATION) + private static final JobInfo DEPRECATED_LOAD_JOB = JobInfo.builder(LOAD_CONFIGURATION) .jobId(JOB_ID) - .statistics(LOAD_JOB_STATISTICS) + .setStatistics(LOAD_JOB_STATISTICS) .jobId(JOB_ID) - .etag(ETAG) - .generatedId(GENERATED_ID) - .selfLink(SELF_LINK) - .userEmail(EMAIL) - .status(JOB_STATUS) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setSelfLink(SELF_LINK) + .setUserEmail(EMAIL) + .setStatus(JOB_STATUS) .build(); - private static final JobInfo QUERY_JOB = JobInfo.builder(QUERY_CONFIGURATION) + private static final JobInfo DEPRECATED_QUERY_JOB = JobInfo.builder(QUERY_CONFIGURATION) .jobId(JOB_ID) - .statistics(QUERY_JOB_STATISTICS) + .setStatistics(QUERY_JOB_STATISTICS) .jobId(JOB_ID) - .etag(ETAG) - .generatedId(GENERATED_ID) - .selfLink(SELF_LINK) - .userEmail(EMAIL) - .status(JOB_STATUS) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setSelfLink(SELF_LINK) + .setUserEmail(EMAIL) + .setStatus(JOB_STATUS) .build(); - @Test public void testToBuilder() { compareJobInfo(COPY_JOB, COPY_JOB.toBuilder().build()); @@ -208,54 +247,53 @@ public void testToBuilder() { compareJobInfo(LOAD_JOB, LOAD_JOB.toBuilder().build()); compareJobInfo(QUERY_JOB, QUERY_JOB.toBuilder().build()); JobInfo job = COPY_JOB.toBuilder() - .userEmail("newEmail") + .setUserEmail("newEmail") .build(); - assertEquals("newEmail", job.userEmail()); - job = job.toBuilder().userEmail(EMAIL).build(); + assertEquals("newEmail", job.getUserEmail()); + job = job.toBuilder().setUserEmail(EMAIL).build(); compareJobInfo(COPY_JOB, job); job = EXTRACT_JOB.toBuilder() - .userEmail("newEmail") + .setUserEmail("newEmail") .build(); - assertEquals("newEmail", job.userEmail()); - job = job.toBuilder().userEmail(EMAIL).build(); + assertEquals("newEmail", job.getUserEmail()); + job = job.toBuilder().setUserEmail(EMAIL).build(); compareJobInfo(EXTRACT_JOB, job); job = LOAD_JOB.toBuilder() - .userEmail("newEmail") + .setUserEmail("newEmail") .build(); - assertEquals("newEmail", job.userEmail()); - job = job.toBuilder().userEmail(EMAIL).build(); + assertEquals("newEmail", job.getUserEmail()); + job = job.toBuilder().setUserEmail(EMAIL).build(); compareJobInfo(LOAD_JOB, job); job = QUERY_JOB.toBuilder() - .userEmail("newEmail") + .setUserEmail("newEmail") .build(); - assertEquals("newEmail", job.userEmail()); - job = job.toBuilder().userEmail(EMAIL).build(); + assertEquals("newEmail", job.getUserEmail()); + job = job.toBuilder().setUserEmail(EMAIL).build(); compareJobInfo(QUERY_JOB, job); } @Test public void testOf() { JobInfo job = JobInfo.of(COPY_CONFIGURATION); - assertEquals(COPY_CONFIGURATION, job.configuration()); + assertEquals(COPY_CONFIGURATION, job.getConfiguration()); job = JobInfo.of(EXTRACT_CONFIGURATION); - assertEquals(EXTRACT_CONFIGURATION, job.configuration()); + assertEquals(EXTRACT_CONFIGURATION, job.getConfiguration()); job = JobInfo.of(LOAD_CONFIGURATION); - assertEquals(LOAD_CONFIGURATION, job.configuration()); + assertEquals(LOAD_CONFIGURATION, job.getConfiguration()); job = JobInfo.of(QUERY_CONFIGURATION); - assertEquals(QUERY_CONFIGURATION, job.configuration()); + assertEquals(QUERY_CONFIGURATION, job.getConfiguration()); job = JobInfo.of(JOB_ID, COPY_CONFIGURATION); - assertEquals(JOB_ID, job.jobId()); - assertEquals(COPY_CONFIGURATION, job.configuration()); + assertEquals(JOB_ID, job.getJobId()); + assertEquals(COPY_CONFIGURATION, job.getConfiguration()); job = JobInfo.of(JOB_ID, EXTRACT_CONFIGURATION); - assertEquals(JOB_ID, job.jobId()); - assertEquals(EXTRACT_CONFIGURATION, job.configuration()); + assertEquals(JOB_ID, job.getJobId()); + assertEquals(EXTRACT_CONFIGURATION, job.getConfiguration()); job = JobInfo.of(JOB_ID, LOAD_CONFIGURATION); - assertEquals(JOB_ID, job.jobId()); - assertEquals(LOAD_CONFIGURATION, job.configuration()); + assertEquals(JOB_ID, job.getJobId()); + assertEquals(LOAD_CONFIGURATION, job.getConfiguration()); job = JobInfo.of(JOB_ID, QUERY_CONFIGURATION); - assertEquals(JOB_ID, job.jobId()); - assertEquals(QUERY_CONFIGURATION, job.configuration()); - + assertEquals(JOB_ID, job.getJobId()); + assertEquals(QUERY_CONFIGURATION, job.getConfiguration()); } @Test @@ -266,41 +304,80 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(ETAG, COPY_JOB.etag()); - assertEquals(GENERATED_ID, COPY_JOB.generatedId()); - assertEquals(SELF_LINK, COPY_JOB.selfLink()); - assertEquals(EMAIL, COPY_JOB.userEmail()); - assertEquals(JOB_ID, COPY_JOB.jobId()); - assertEquals(JOB_STATUS, COPY_JOB.status()); - assertEquals(COPY_CONFIGURATION, COPY_JOB.configuration()); - assertEquals(COPY_JOB_STATISTICS, COPY_JOB.statistics()); + assertEquals(ETAG, COPY_JOB.getEtag()); + assertEquals(GENERATED_ID, COPY_JOB.getGeneratedId()); + assertEquals(SELF_LINK, COPY_JOB.getSelfLink()); + assertEquals(EMAIL, COPY_JOB.getUserEmail()); + assertEquals(JOB_ID, COPY_JOB.getJobId()); + assertEquals(JOB_STATUS, COPY_JOB.getStatus()); + assertEquals(COPY_CONFIGURATION, COPY_JOB.getConfiguration()); + assertEquals(COPY_JOB_STATISTICS, COPY_JOB.getStatistics()); - assertEquals(ETAG, EXTRACT_JOB.etag()); - assertEquals(GENERATED_ID, EXTRACT_JOB.generatedId()); - assertEquals(SELF_LINK, EXTRACT_JOB.selfLink()); - assertEquals(EMAIL, EXTRACT_JOB.userEmail()); - assertEquals(JOB_ID, EXTRACT_JOB.jobId()); - assertEquals(JOB_STATUS, EXTRACT_JOB.status()); - assertEquals(EXTRACT_CONFIGURATION, EXTRACT_JOB.configuration()); - assertEquals(EXTRACT_JOB_STATISTICS, EXTRACT_JOB.statistics()); + assertEquals(ETAG, EXTRACT_JOB.getEtag()); + assertEquals(GENERATED_ID, EXTRACT_JOB.getGeneratedId()); + assertEquals(SELF_LINK, EXTRACT_JOB.getSelfLink()); + assertEquals(EMAIL, EXTRACT_JOB.getUserEmail()); + assertEquals(JOB_ID, EXTRACT_JOB.getJobId()); + assertEquals(JOB_STATUS, EXTRACT_JOB.getStatus()); + assertEquals(EXTRACT_CONFIGURATION, EXTRACT_JOB.getConfiguration()); + assertEquals(EXTRACT_JOB_STATISTICS, EXTRACT_JOB.getStatistics()); - assertEquals(ETAG, LOAD_JOB.etag()); - assertEquals(GENERATED_ID, LOAD_JOB.generatedId()); - assertEquals(SELF_LINK, LOAD_JOB.selfLink()); - assertEquals(EMAIL, LOAD_JOB.userEmail()); - assertEquals(JOB_ID, LOAD_JOB.jobId()); - assertEquals(JOB_STATUS, LOAD_JOB.status()); - assertEquals(LOAD_CONFIGURATION, LOAD_JOB.configuration()); - assertEquals(LOAD_JOB_STATISTICS, LOAD_JOB.statistics()); + assertEquals(ETAG, LOAD_JOB.getEtag()); + assertEquals(GENERATED_ID, LOAD_JOB.getGeneratedId()); + assertEquals(SELF_LINK, LOAD_JOB.getSelfLink()); + assertEquals(EMAIL, LOAD_JOB.getUserEmail()); + assertEquals(JOB_ID, LOAD_JOB.getJobId()); + assertEquals(JOB_STATUS, LOAD_JOB.getStatus()); + assertEquals(LOAD_CONFIGURATION, LOAD_JOB.getConfiguration()); + assertEquals(LOAD_JOB_STATISTICS, LOAD_JOB.getStatistics()); - assertEquals(ETAG, QUERY_JOB.etag()); - assertEquals(GENERATED_ID, QUERY_JOB.generatedId()); - assertEquals(SELF_LINK, QUERY_JOB.selfLink()); - assertEquals(EMAIL, QUERY_JOB.userEmail()); - assertEquals(JOB_ID, QUERY_JOB.jobId()); - assertEquals(JOB_STATUS, QUERY_JOB.status()); - assertEquals(QUERY_CONFIGURATION, QUERY_JOB.configuration()); - assertEquals(QUERY_JOB_STATISTICS, QUERY_JOB.statistics()); + assertEquals(ETAG, QUERY_JOB.getEtag()); + assertEquals(GENERATED_ID, QUERY_JOB.getGeneratedId()); + assertEquals(SELF_LINK, QUERY_JOB.getSelfLink()); + assertEquals(EMAIL, QUERY_JOB.getUserEmail()); + assertEquals(JOB_ID, QUERY_JOB.getJobId()); + assertEquals(JOB_STATUS, QUERY_JOB.getStatus()); + assertEquals(QUERY_CONFIGURATION, QUERY_JOB.getConfiguration()); + assertEquals(QUERY_JOB_STATISTICS, QUERY_JOB.getStatistics()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(ETAG, DEPRECATED_COPY_JOB.etag()); + assertEquals(GENERATED_ID, DEPRECATED_COPY_JOB.generatedId()); + assertEquals(SELF_LINK, DEPRECATED_COPY_JOB.selfLink()); + assertEquals(EMAIL, DEPRECATED_COPY_JOB.userEmail()); + assertEquals(JOB_ID, DEPRECATED_COPY_JOB.jobId()); + assertEquals(JOB_STATUS, DEPRECATED_COPY_JOB.status()); + assertEquals(COPY_CONFIGURATION, DEPRECATED_COPY_JOB.configuration()); + assertEquals(COPY_JOB_STATISTICS, DEPRECATED_COPY_JOB.statistics()); + + assertEquals(ETAG, DEPRECATED_EXTRACT_JOB.etag()); + assertEquals(GENERATED_ID, DEPRECATED_EXTRACT_JOB.generatedId()); + assertEquals(SELF_LINK, DEPRECATED_EXTRACT_JOB.selfLink()); + assertEquals(EMAIL, DEPRECATED_EXTRACT_JOB.userEmail()); + assertEquals(JOB_ID, DEPRECATED_EXTRACT_JOB.jobId()); + assertEquals(JOB_STATUS, DEPRECATED_EXTRACT_JOB.status()); + assertEquals(EXTRACT_CONFIGURATION, DEPRECATED_EXTRACT_JOB.configuration()); + assertEquals(EXTRACT_JOB_STATISTICS, DEPRECATED_EXTRACT_JOB.statistics()); + + assertEquals(ETAG, DEPRECATED_LOAD_JOB.etag()); + assertEquals(GENERATED_ID, DEPRECATED_LOAD_JOB.generatedId()); + assertEquals(SELF_LINK, DEPRECATED_LOAD_JOB.selfLink()); + assertEquals(EMAIL, DEPRECATED_LOAD_JOB.userEmail()); + assertEquals(JOB_ID, DEPRECATED_LOAD_JOB.jobId()); + assertEquals(JOB_STATUS, DEPRECATED_LOAD_JOB.status()); + assertEquals(LOAD_CONFIGURATION, DEPRECATED_LOAD_JOB.configuration()); + assertEquals(LOAD_JOB_STATISTICS, DEPRECATED_LOAD_JOB.statistics()); + + assertEquals(ETAG, DEPRECATED_QUERY_JOB.etag()); + assertEquals(GENERATED_ID, DEPRECATED_QUERY_JOB.generatedId()); + assertEquals(SELF_LINK, DEPRECATED_QUERY_JOB.selfLink()); + assertEquals(EMAIL, DEPRECATED_QUERY_JOB.userEmail()); + assertEquals(JOB_ID, DEPRECATED_QUERY_JOB.jobId()); + assertEquals(JOB_STATUS, DEPRECATED_QUERY_JOB.status()); + assertEquals(QUERY_CONFIGURATION, DEPRECATED_QUERY_JOB.configuration()); + assertEquals(QUERY_JOB_STATISTICS, DEPRECATED_QUERY_JOB.statistics()); } @Test @@ -309,71 +386,72 @@ public void testToPbAndFromPb() { assertNull(COPY_JOB.toPb().getConfiguration().getExtract()); assertNull(COPY_JOB.toPb().getConfiguration().getLoad()); assertNull(COPY_JOB.toPb().getConfiguration().getQuery()); - assertEquals(COPY_JOB_STATISTICS, JobStatistics.fromPb(COPY_JOB.statistics().toPb())); + assertEquals(COPY_JOB_STATISTICS, JobStatistics.fromPb(COPY_JOB.getStatistics().toPb())); compareJobInfo(COPY_JOB, JobInfo.fromPb(COPY_JOB.toPb())); - assertTrue(JobInfo.fromPb(COPY_JOB.toPb()).configuration() instanceof CopyJobConfiguration); + assertTrue(JobInfo.fromPb(COPY_JOB.toPb()).getConfiguration() instanceof CopyJobConfiguration); assertNull(EXTRACT_JOB.toPb().getConfiguration().getCopy()); assertNotNull(EXTRACT_JOB.toPb().getConfiguration().getExtract()); assertNull(EXTRACT_JOB.toPb().getConfiguration().getLoad()); assertNull(EXTRACT_JOB.toPb().getConfiguration().getQuery()); - assertEquals(EXTRACT_JOB_STATISTICS, JobStatistics.fromPb(EXTRACT_JOB.statistics().toPb())); + assertEquals(EXTRACT_JOB_STATISTICS, JobStatistics.fromPb(EXTRACT_JOB.getStatistics().toPb())); compareJobInfo(EXTRACT_JOB, JobInfo.fromPb(EXTRACT_JOB.toPb())); assertTrue( - JobInfo.fromPb(EXTRACT_JOB.toPb()).configuration() instanceof ExtractJobConfiguration); - assertTrue(JobInfo.fromPb(EXTRACT_JOB.toPb()).statistics() instanceof ExtractStatistics); + JobInfo.fromPb(EXTRACT_JOB.toPb()).getConfiguration() instanceof ExtractJobConfiguration); + assertTrue(JobInfo.fromPb(EXTRACT_JOB.toPb()).getStatistics() instanceof ExtractStatistics); assertNull(LOAD_JOB.toPb().getConfiguration().getCopy()); assertNull(LOAD_JOB.toPb().getConfiguration().getExtract()); assertNotNull(LOAD_JOB.toPb().getConfiguration().getLoad()); assertNull(LOAD_JOB.toPb().getConfiguration().getQuery()); - assertEquals(LOAD_JOB_STATISTICS, JobStatistics.fromPb(LOAD_JOB.statistics().toPb())); + assertEquals(LOAD_JOB_STATISTICS, JobStatistics.fromPb(LOAD_JOB.getStatistics().toPb())); compareJobInfo(LOAD_JOB, JobInfo.fromPb(LOAD_JOB.toPb())); - assertTrue(JobInfo.fromPb(LOAD_JOB.toPb()).configuration() instanceof LoadJobConfiguration); - assertTrue(JobInfo.fromPb(LOAD_JOB.toPb()).statistics() instanceof LoadStatistics); + assertTrue(JobInfo.fromPb(LOAD_JOB.toPb()).getConfiguration() instanceof LoadJobConfiguration); + assertTrue(JobInfo.fromPb(LOAD_JOB.toPb()).getStatistics() instanceof LoadStatistics); assertNull(QUERY_JOB.toPb().getConfiguration().getCopy()); assertNull(QUERY_JOB.toPb().getConfiguration().getExtract()); assertNull(QUERY_JOB.toPb().getConfiguration().getLoad()); assertNotNull(QUERY_JOB.toPb().getConfiguration().getQuery()); - assertEquals(QUERY_JOB_STATISTICS, JobStatistics.fromPb(QUERY_JOB.statistics().toPb())); + assertEquals(QUERY_JOB_STATISTICS, JobStatistics.fromPb(QUERY_JOB.getStatistics().toPb())); compareJobInfo(QUERY_JOB, JobInfo.fromPb(QUERY_JOB.toPb())); - assertTrue(JobInfo.fromPb(QUERY_JOB.toPb()).configuration() instanceof QueryJobConfiguration); - assertTrue(JobInfo.fromPb(QUERY_JOB.toPb()).statistics() instanceof QueryStatistics); + assertTrue( + JobInfo.fromPb(QUERY_JOB.toPb()).getConfiguration() instanceof QueryJobConfiguration); + assertTrue(JobInfo.fromPb(QUERY_JOB.toPb()).getStatistics() instanceof QueryStatistics); } @Test public void testSetProjectId() { JobInfo jobInfo = COPY_JOB.setProjectId("p"); - assertEquals("p", jobInfo.jobId().project()); - CopyJobConfiguration copyConfiguration = jobInfo.configuration(); - assertEquals("p", copyConfiguration.destinationTable().project()); - for (TableId sourceTable : copyConfiguration.sourceTables()) { - assertEquals("p", sourceTable.project()); + assertEquals("p", jobInfo.getJobId().getProject()); + CopyJobConfiguration copyConfiguration = jobInfo.getConfiguration(); + assertEquals("p", copyConfiguration.getDestinationTable().getProject()); + for (TableId sourceTable : copyConfiguration.getSourceTables()) { + assertEquals("p", sourceTable.getProject()); } jobInfo = EXTRACT_JOB.setProjectId("p"); - assertEquals("p", jobInfo.jobId().project()); - ExtractJobConfiguration extractConfiguration = jobInfo.configuration(); - assertEquals("p", extractConfiguration.sourceTable().project()); + assertEquals("p", jobInfo.getJobId().getProject()); + ExtractJobConfiguration extractConfiguration = jobInfo.getConfiguration(); + assertEquals("p", extractConfiguration.getSourceTable().getProject()); jobInfo = LOAD_JOB.setProjectId("p"); - assertEquals("p", jobInfo.jobId().project()); - LoadJobConfiguration loadConfiguration = jobInfo.configuration(); - assertEquals("p", loadConfiguration.destinationTable().project()); + assertEquals("p", jobInfo.getJobId().getProject()); + LoadJobConfiguration loadConfiguration = jobInfo.getConfiguration(); + assertEquals("p", loadConfiguration.getDestinationTable().getProject()); jobInfo = QUERY_JOB.setProjectId("p"); - assertEquals("p", jobInfo.jobId().project()); - QueryJobConfiguration queryConfiguration = jobInfo.configuration(); - assertEquals("p", queryConfiguration.defaultDataset().project()); - assertEquals("p", queryConfiguration.destinationTable().project()); + assertEquals("p", jobInfo.getJobId().getProject()); + QueryJobConfiguration queryConfiguration = jobInfo.getConfiguration(); + assertEquals("p", queryConfiguration.getDefaultDataset().getProject()); + assertEquals("p", queryConfiguration.getDestinationTable().getProject()); } private void compareJobInfo(JobInfo expected, JobInfo value) { assertEquals(expected, value); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); - assertEquals(expected.etag(), value.etag()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.jobId(), value.jobId()); - assertEquals(expected.selfLink(), value.selfLink()); - assertEquals(expected.status(), value.status()); - assertEquals(expected.statistics(), value.statistics()); - assertEquals(expected.userEmail(), value.userEmail()); - assertEquals(expected.configuration(), value.configuration()); + assertEquals(expected.getEtag(), value.getEtag()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getJobId(), value.getJobId()); + assertEquals(expected.getSelfLink(), value.getSelfLink()); + assertEquals(expected.getStatus(), value.getStatus()); + assertEquals(expected.getStatistics(), value.getStatistics()); + assertEquals(expected.getUserEmail(), value.getUserEmail()); + assertEquals(expected.getConfiguration(), value.getConfiguration()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobStatisticsTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobStatisticsTest.java index c4c8c5ae6f4b..46e47af7eaa7 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobStatisticsTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobStatisticsTest.java @@ -43,71 +43,118 @@ public class JobStatisticsTest { private static final Long CREATION_TIME = 10L; private static final Long END_TIME = 20L; private static final Long START_TIME = 15L; - private static final CopyStatistics COPY_STATISTICS = CopyStatistics.builder() - .creationTime(CREATION_TIME) - .endTime(END_TIME) - .startTime(START_TIME) + private static final CopyStatistics COPY_STATISTICS = CopyStatistics.newBuilder() + .setCreationTimestamp(CREATION_TIME) + .setEndTime(END_TIME) + .setStartTime(START_TIME) .build(); - private static final ExtractStatistics EXTRACT_STATISTICS = ExtractStatistics.builder() - .creationTime(CREATION_TIME) - .endTime(END_TIME) - .startTime(START_TIME) - .destinationUriFileCounts(FILE_COUNT) + private static final ExtractStatistics EXTRACT_STATISTICS = ExtractStatistics.newBuilder() + .setCreationTimestamp(CREATION_TIME) + .setEndTime(END_TIME) + .setStartTime(START_TIME) + .setDestinationUriFileCounts(FILE_COUNT) .build(); - private static final LoadStatistics LOAD_STATISTICS = LoadStatistics.builder() - .creationTime(CREATION_TIME) - .endTime(END_TIME) - .startTime(START_TIME) - .inputBytes(INPUT_BYTES) - .inputFiles(INPUT_FILES) - .outputBytes(OUTPUT_BYTES) - .outputRows(OUTPUT_ROWS) + private static final LoadStatistics LOAD_STATISTICS = LoadStatistics.newBuilder() + .setCreationTimestamp(CREATION_TIME) + .setEndTime(END_TIME) + .setStartTime(START_TIME) + .setInputBytes(INPUT_BYTES) + .setInputFiles(INPUT_FILES) + .setOutputBytes(OUTPUT_BYTES) + .setOutputRows(OUTPUT_ROWS) .build(); - private static final LoadStatistics LOAD_STATISTICS_INCOMPLETE = LoadStatistics.builder() - .creationTime(CREATION_TIME) - .endTime(END_TIME) - .startTime(START_TIME) - .inputBytes(INPUT_BYTES) - .inputFiles(INPUT_FILES) + private static final LoadStatistics LOAD_STATISTICS_INCOMPLETE = LoadStatistics.newBuilder() + .setCreationTimestamp(CREATION_TIME) + .setEndTime(END_TIME) + .setStartTime(START_TIME) + .setInputBytes(INPUT_BYTES) + .setInputFiles(INPUT_FILES) .build(); private static final List SUBSTEPS1 = ImmutableList.of("substep1", "substep2"); private static final List SUBSTEPS2 = ImmutableList.of("substep3", "substep4"); private static final QueryStep QUERY_STEP1 = new QueryStep("KIND", SUBSTEPS1); private static final QueryStep QUERY_STEP2 = new QueryStep("KIND", SUBSTEPS2); - private static final QueryStage QUERY_STAGE = QueryStage.builder() - .computeRatioAvg(1.1) - .computeRatioMax(2.2) - .generatedId(42L) - .name("stage") - .readRatioAvg(3.3) - .readRatioMax(4.4) - .recordsRead(5L) - .recordsWritten(6L) - .steps(ImmutableList.of(QUERY_STEP1, QUERY_STEP2)) - .waitRatioAvg(7.7) - .waitRatioMax(8.8) - .writeRatioAvg(9.9) - .writeRatioMax(10.10) + private static final QueryStage QUERY_STAGE = QueryStage.newBuilder() + .setComputeRationAvg(1.1) + .setComputeRatioMax(2.2) + .setGeneratedId(42L) + .setName("stage") + .setReadRatioAvg(3.3) + .setReadRatioMax(4.4) + .setRecordsRead(5L) + .setRecordsWritten(6L) + .setSteps(ImmutableList.of(QUERY_STEP1, QUERY_STEP2)) + .setWaitRatioAvg(7.7) + .setWaitRatioMax(8.8) + .setWriteRatioAvg(9.9) + .setWriteRatioMax(10.10) .build(); private static final List QUERY_PLAN = ImmutableList.of(QUERY_STAGE); - private static final QueryStatistics QUERY_STATISTICS = QueryStatistics.builder() - .creationTime(CREATION_TIME) - .endTime(END_TIME) - .startTime(START_TIME) - .billingTier(BILLING_TIER) - .cacheHit(CACHE_HIT) - .totalBytesBilled(TOTAL_BYTES_BILLED) - .totalBytesProcessed(TOTAL_BYTES_PROCESSED) - .queryPlan(QUERY_PLAN) + private static final QueryStatistics QUERY_STATISTICS = QueryStatistics.newBuilder() + .setCreationTimestamp(CREATION_TIME) + .setEndTime(END_TIME) + .setStartTime(START_TIME) + .setBillingTier(BILLING_TIER) + .setCacheHit(CACHE_HIT) + .setTotalBytesBilled(TOTAL_BYTES_BILLED) + .setTotalBytesProcessed(TOTAL_BYTES_PROCESSED) + .setQueryPlan(QUERY_PLAN) .build(); - private static final QueryStatistics QUERY_STATISTICS_INCOMPLETE = QueryStatistics.builder() - .creationTime(CREATION_TIME) - .endTime(END_TIME) - .startTime(START_TIME) - .billingTier(BILLING_TIER) - .cacheHit(CACHE_HIT) + private static final QueryStatistics QUERY_STATISTICS_INCOMPLETE = QueryStatistics.newBuilder() + .setCreationTimestamp(CREATION_TIME) + .setEndTime(END_TIME) + .setStartTime(START_TIME) + .setBillingTier(BILLING_TIER) + .setCacheHit(CACHE_HIT) .build(); + @Test + public void testBuilderDeprecated() { + assertEquals(CREATION_TIME, COPY_STATISTICS.getCreationTime()); + assertEquals(START_TIME, COPY_STATISTICS.getStartTime()); + assertEquals(END_TIME, COPY_STATISTICS.getEndTime()); + + assertEquals(CREATION_TIME, EXTRACT_STATISTICS.getCreationTime()); + assertEquals(START_TIME, EXTRACT_STATISTICS.getStartTime()); + assertEquals(END_TIME, EXTRACT_STATISTICS.getEndTime()); + assertEquals(FILE_COUNT, EXTRACT_STATISTICS.getDestinationUriFileCounts()); + + assertEquals(CREATION_TIME, LOAD_STATISTICS.getCreationTime()); + assertEquals(START_TIME, LOAD_STATISTICS.getStartTime()); + assertEquals(END_TIME, LOAD_STATISTICS.getEndTime()); + assertEquals(INPUT_BYTES, LOAD_STATISTICS.getInputBytes()); + assertEquals(INPUT_FILES, LOAD_STATISTICS.getInputFiles()); + assertEquals(OUTPUT_BYTES, LOAD_STATISTICS.getOutputBytes()); + assertEquals(OUTPUT_ROWS, LOAD_STATISTICS.getOutputRows()); + + assertEquals(CREATION_TIME, QUERY_STATISTICS.getCreationTime()); + assertEquals(START_TIME, QUERY_STATISTICS.getStartTime()); + assertEquals(END_TIME, QUERY_STATISTICS.getEndTime()); + assertEquals(BILLING_TIER, QUERY_STATISTICS.getBillingTier()); + assertEquals(CACHE_HIT, QUERY_STATISTICS.getCacheHit()); + assertEquals(TOTAL_BYTES_BILLED, QUERY_STATISTICS.getTotalBytesBilled()); + assertEquals(TOTAL_BYTES_PROCESSED, QUERY_STATISTICS.getTotalBytesProcessed()); + assertEquals(TOTAL_BYTES_PROCESSED, QUERY_STATISTICS.getTotalBytesProcessed()); + assertEquals(QUERY_PLAN, QUERY_STATISTICS.getQueryPlan()); + + assertEquals(CREATION_TIME, LOAD_STATISTICS_INCOMPLETE.getCreationTime()); + assertEquals(START_TIME, LOAD_STATISTICS_INCOMPLETE.getStartTime()); + assertEquals(END_TIME, LOAD_STATISTICS_INCOMPLETE.getEndTime()); + assertEquals(INPUT_BYTES, LOAD_STATISTICS_INCOMPLETE.getInputBytes()); + assertEquals(INPUT_FILES, LOAD_STATISTICS_INCOMPLETE.getInputFiles()); + assertEquals(null, LOAD_STATISTICS_INCOMPLETE.getOutputBytes()); + assertEquals(null, LOAD_STATISTICS_INCOMPLETE.getOutputRows()); + + assertEquals(CREATION_TIME, QUERY_STATISTICS_INCOMPLETE.getCreationTime()); + assertEquals(START_TIME, QUERY_STATISTICS_INCOMPLETE.getStartTime()); + assertEquals(END_TIME, QUERY_STATISTICS_INCOMPLETE.getEndTime()); + assertEquals(BILLING_TIER, QUERY_STATISTICS_INCOMPLETE.getBillingTier()); + assertEquals(CACHE_HIT, QUERY_STATISTICS_INCOMPLETE.getCacheHit()); + assertEquals(null, QUERY_STATISTICS_INCOMPLETE.getTotalBytesBilled()); + assertEquals(null, QUERY_STATISTICS_INCOMPLETE.getTotalBytesProcessed()); + assertEquals(null, QUERY_STATISTICS_INCOMPLETE.getQueryPlan()); + } + @Test public void testBuilder() { assertEquals(CREATION_TIME, COPY_STATISTICS.creationTime()); @@ -172,34 +219,34 @@ public void testToPbAndFromPb() { private void compareExtractStatistics(ExtractStatistics expected, ExtractStatistics value) { assertEquals(expected, value); compareStatistics(expected, value); - assertEquals(expected.destinationUriFileCounts(), value.destinationUriFileCounts()); + assertEquals(expected.getDestinationUriFileCounts(), value.getDestinationUriFileCounts()); } private void compareLoadStatistics(LoadStatistics expected, LoadStatistics value) { assertEquals(expected, value); compareStatistics(expected, value); - assertEquals(expected.inputBytes(), value.inputBytes()); - assertEquals(expected.inputFiles(), value.inputFiles()); - assertEquals(expected.outputBytes(), value.outputBytes()); - assertEquals(expected.outputRows(), value.outputRows()); + assertEquals(expected.getInputBytes(), value.getInputBytes()); + assertEquals(expected.getInputFiles(), value.getInputFiles()); + assertEquals(expected.getOutputBytes(), value.getOutputBytes()); + assertEquals(expected.getOutputRows(), value.getOutputRows()); } private void compareQueryStatistics(QueryStatistics expected, QueryStatistics value) { assertEquals(expected, value); compareStatistics(expected, value); - assertEquals(expected.billingTier(), value.billingTier()); - assertEquals(expected.cacheHit(), value.cacheHit()); - assertEquals(expected.totalBytesBilled(), value.totalBytesBilled()); - assertEquals(expected.totalBytesProcessed(), value.totalBytesProcessed()); - assertEquals(expected.queryPlan(), value.queryPlan()); + assertEquals(expected.getBillingTier(), value.getBillingTier()); + assertEquals(expected.getCacheHit(), value.getCacheHit()); + assertEquals(expected.getTotalBytesBilled(), value.getTotalBytesBilled()); + assertEquals(expected.getTotalBytesProcessed(), value.getTotalBytesProcessed()); + assertEquals(expected.getQueryPlan(), value.getQueryPlan()); } private void compareStatistics(JobStatistics expected, JobStatistics value) { assertEquals(expected, value); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); - assertEquals(expected.creationTime(), value.creationTime()); - assertEquals(expected.endTime(), value.endTime()); - assertEquals(expected.startTime(), value.startTime()); + assertEquals(expected.getCreationTime(), value.getCreationTime()); + assertEquals(expected.getEndTime(), value.getEndTime()); + assertEquals(expected.getStartTime(), value.getStartTime()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobStatusTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobStatusTest.java index 78a4345a339b..34bf1bb10997 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobStatusTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobStatusTest.java @@ -38,6 +38,21 @@ public class JobStatusTest { @Test public void testConstructor() { + assertEquals(STATE, JOB_STATUS.getState()); + assertEquals(ERROR, JOB_STATUS.getError()); + assertEquals(ALL_ERRORS, JOB_STATUS.getExecutionErrors()); + + assertEquals(STATE, JOB_STATUS_INCOMPLETE1.getState()); + assertEquals(ERROR, JOB_STATUS_INCOMPLETE1.getError()); + assertEquals(null, JOB_STATUS_INCOMPLETE1.getExecutionErrors()); + + assertEquals(STATE, JOB_STATUS_INCOMPLETE2.getState()); + assertEquals(null, JOB_STATUS_INCOMPLETE2.getError()); + assertEquals(null, JOB_STATUS_INCOMPLETE2.getExecutionErrors()); + } + + @Test + public void testConstructorDeprecated() { assertEquals(STATE, JOB_STATUS.state()); assertEquals(ERROR, JOB_STATUS.error()); assertEquals(ALL_ERRORS, JOB_STATUS.executionErrors()); @@ -60,8 +75,8 @@ public void testToPbAndFromPb() { private void compareStatus(JobStatus expected, JobStatus value) { assertEquals(expected, value); - assertEquals(expected.state(), value.state()); - assertEquals(expected.error(), value.error()); - assertEquals(expected.executionErrors(), value.executionErrors()); + assertEquals(expected.getState(), value.getState()); + assertEquals(expected.getError(), value.getError()); + assertEquals(expected.getExecutionErrors(), value.getExecutionErrors()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobTest.java index fb47b54428c0..2c15b86fad97 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobTest.java @@ -50,22 +50,22 @@ public class JobTest { private static final String SELF_LINK = "selfLink"; private static final String EMAIL = "email"; private static final JobStatus JOB_STATUS = new JobStatus(JobStatus.State.DONE); - private static final JobStatistics COPY_JOB_STATISTICS = CopyStatistics.builder() - .creationTime(1L) - .endTime(3L) - .startTime(2L) + private static final JobStatistics COPY_JOB_STATISTICS = CopyStatistics.newBuilder() + .setCreationTimestamp(1L) + .setEndTime(3L) + .setStartTime(2L) .build(); private static final CopyJobConfiguration COPY_CONFIGURATION = CopyJobConfiguration.of(TABLE_ID1, TABLE_ID2); - private static final JobInfo JOB_INFO = JobInfo.builder(COPY_CONFIGURATION) - .jobId(JOB_ID) - .statistics(COPY_JOB_STATISTICS) - .jobId(JOB_ID) - .etag(ETAG) - .generatedId(GENERATED_ID) - .selfLink(SELF_LINK) - .userEmail(EMAIL) - .status(JOB_STATUS) + private static final JobInfo JOB_INFO = JobInfo.newBuilder(COPY_CONFIGURATION) + .setJobId(JOB_ID) + .setStatistics(COPY_JOB_STATISTICS) + .setJobId(JOB_ID) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setSelfLink(SELF_LINK) + .setUserEmail(EMAIL) + .setStatus(JOB_STATUS) .build(); private BigQuery serviceMockReturnsOptions = createStrictMock(BigQuery.class); @@ -95,17 +95,42 @@ public void tearDown() throws Exception { @Test public void testBuilder() { + initializeExpectedJob(2); + replay(bigquery); + Job builtJob = new Job.Builder(serviceMockReturnsOptions, COPY_CONFIGURATION) + .setJobId(JOB_ID) + .setStatistics(COPY_JOB_STATISTICS) + .setJobId(JOB_ID) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setSelfLink(SELF_LINK) + .setUserEmail(EMAIL) + .setStatus(JOB_STATUS) + .build(); + assertEquals(ETAG, builtJob.getEtag()); + assertEquals(GENERATED_ID, builtJob.getGeneratedId()); + assertEquals(SELF_LINK, builtJob.getSelfLink()); + assertEquals(EMAIL, builtJob.getUserEmail()); + assertEquals(JOB_ID, builtJob.getJobId()); + assertEquals(JOB_STATUS, builtJob.getStatus()); + assertEquals(COPY_CONFIGURATION, builtJob.getConfiguration()); + assertEquals(COPY_JOB_STATISTICS, builtJob.getStatistics()); + assertSame(serviceMockReturnsOptions, builtJob.getBigquery()); + } + + @Test + public void testBuilderDeprecated() { initializeExpectedJob(2); replay(bigquery); Job builtJob = new Job.Builder(serviceMockReturnsOptions, COPY_CONFIGURATION) .jobId(JOB_ID) - .statistics(COPY_JOB_STATISTICS) + .setStatistics(COPY_JOB_STATISTICS) .jobId(JOB_ID) - .etag(ETAG) - .generatedId(GENERATED_ID) - .selfLink(SELF_LINK) - .userEmail(EMAIL) - .status(JOB_STATUS) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) + .setSelfLink(SELF_LINK) + .setUserEmail(EMAIL) + .setStatus(JOB_STATUS) .build(); assertEquals(ETAG, builtJob.etag()); assertEquals(GENERATED_ID, builtJob.generatedId()); @@ -130,7 +155,7 @@ public void testExists_True() throws Exception { initializeExpectedJob(1); BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields()}; expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(expectedJob); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(expectedJob); replay(bigquery); initializeJob(); assertTrue(job.exists()); @@ -141,7 +166,7 @@ public void testExists_False() throws Exception { initializeExpectedJob(1); BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields()}; expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(null); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(null); replay(bigquery); initializeJob(); assertFalse(job.exists()); @@ -152,10 +177,10 @@ public void testIsDone_True() throws Exception { initializeExpectedJob(2); BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields(BigQuery.JobField.STATUS)}; JobStatus status = createStrictMock(JobStatus.class); - expect(status.state()).andReturn(JobStatus.State.DONE); + expect(status.getState()).andReturn(JobStatus.State.DONE); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)) - .andReturn(expectedJob.toBuilder().status(status).build()); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)) + .andReturn(expectedJob.toBuilder().setStatus(status).build()); replay(status, bigquery); initializeJob(); assertTrue(job.isDone()); @@ -167,10 +192,10 @@ public void testIsDone_False() throws Exception { initializeExpectedJob(2); BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields(BigQuery.JobField.STATUS)}; JobStatus status = createStrictMock(JobStatus.class); - expect(status.state()).andReturn(JobStatus.State.RUNNING); + expect(status.getState()).andReturn(JobStatus.State.RUNNING); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)) - .andReturn(expectedJob.toBuilder().status(status).build()); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)) + .andReturn(expectedJob.toBuilder().setStatus(status).build()); replay(status, bigquery); initializeJob(); assertFalse(job.isDone()); @@ -182,7 +207,7 @@ public void testIsDone_NotExists() throws Exception { initializeExpectedJob(1); BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields(BigQuery.JobField.STATUS)}; expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(null); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(null); replay(bigquery); initializeJob(); assertTrue(job.isDone()); @@ -193,12 +218,12 @@ public void testWaitFor() throws InterruptedException, TimeoutException { initializeExpectedJob(2); BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields(BigQuery.JobField.STATUS)}; JobStatus status = createStrictMock(JobStatus.class); - expect(status.state()).andReturn(JobStatus.State.DONE); + expect(status.getState()).andReturn(JobStatus.State.DONE); expect(bigquery.options()).andReturn(mockOptions); expect(mockOptions.clock()).andReturn(Clock.defaultClock()); - Job completedJob = expectedJob.toBuilder().status(status).build(); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(completedJob); - expect(bigquery.getJob(JOB_INFO.jobId())).andReturn(completedJob); + Job completedJob = expectedJob.toBuilder().setStatus(status).build(); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(completedJob); + expect(bigquery.getJob(JOB_INFO.getJobId())).andReturn(completedJob); replay(status, bigquery, mockOptions); initializeJob(); assertSame(completedJob, job.waitFor()); @@ -211,8 +236,8 @@ public void testWaitFor_Null() throws InterruptedException, TimeoutException { BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields(BigQuery.JobField.STATUS)}; expect(bigquery.options()).andReturn(mockOptions); expect(mockOptions.clock()).andReturn(Clock.defaultClock()); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(null); - expect(bigquery.getJob(JOB_INFO.jobId())).andReturn(null); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(null); + expect(bigquery.getJob(JOB_INFO.getJobId())).andReturn(null); replay(bigquery, mockOptions); initializeJob(); assertNull(job.waitFor()); @@ -227,15 +252,15 @@ public void testWaitForWithCheckingPeriod() throws InterruptedException, Timeout timeUnit.sleep(42); EasyMock.expectLastCall(); JobStatus status = createStrictMock(JobStatus.class); - expect(status.state()).andReturn(JobStatus.State.RUNNING); - expect(status.state()).andReturn(JobStatus.State.DONE); + expect(status.getState()).andReturn(JobStatus.State.RUNNING); + expect(status.getState()).andReturn(JobStatus.State.DONE); expect(bigquery.options()).andReturn(mockOptions); expect(mockOptions.clock()).andReturn(Clock.defaultClock()); - Job runningJob = expectedJob.toBuilder().status(status).build(); - Job completedJob = expectedJob.toBuilder().status(status).build(); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(runningJob); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(completedJob); - expect(bigquery.getJob(JOB_INFO.jobId())).andReturn(completedJob); + Job runningJob = expectedJob.toBuilder().setStatus(status).build(); + Job completedJob = expectedJob.toBuilder().setStatus(status).build(); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(runningJob); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(completedJob); + expect(bigquery.getJob(JOB_INFO.getJobId())).andReturn(completedJob); replay(status, bigquery, timeUnit, mockOptions); initializeJob(); assertSame(completedJob, job.waitFor(WaitForOption.checkEvery(42, timeUnit))); @@ -251,10 +276,10 @@ public void testWaitForWithCheckingPeriod_Null() throws InterruptedException, Ti EasyMock.expectLastCall(); expect(bigquery.options()).andReturn(mockOptions); expect(mockOptions.clock()).andReturn(Clock.defaultClock()); - Job runningJob = expectedJob.toBuilder().status(new JobStatus(JobStatus.State.RUNNING)).build(); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(runningJob); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(null); - expect(bigquery.getJob(JOB_INFO.jobId())).andReturn(null); + Job runningJob = expectedJob.toBuilder().setStatus(new JobStatus(JobStatus.State.RUNNING)).build(); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(runningJob); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(null); + expect(bigquery.getJob(JOB_INFO.getJobId())).andReturn(null); replay(bigquery, timeUnit, mockOptions); initializeJob(); assertNull(job.waitFor(WaitForOption.checkEvery(42, timeUnit))); @@ -273,13 +298,13 @@ public void testWaitForWithTimeout() throws InterruptedException, TimeoutExcepti expect(clock.millis()).andReturn(1L); expect(clock.millis()).andReturn(3L); JobStatus status = createStrictMock(JobStatus.class); - expect(status.state()).andReturn(JobStatus.State.RUNNING); - expect(status.state()).andReturn(JobStatus.State.RUNNING); + expect(status.getState()).andReturn(JobStatus.State.RUNNING); + expect(status.getState()).andReturn(JobStatus.State.RUNNING); expect(bigquery.options()).andReturn(mockOptions); expect(mockOptions.clock()).andReturn(clock); - Job runningJob = expectedJob.toBuilder().status(status).build(); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(runningJob); - expect(bigquery.getJob(JOB_INFO.jobId(), expectedOptions)).andReturn(runningJob); + Job runningJob = expectedJob.toBuilder().setStatus(status).build(); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(runningJob); + expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(runningJob); replay(status, bigquery, timeUnit, clock, mockOptions); initializeJob(); thrown.expect(TimeoutException.class); @@ -291,10 +316,10 @@ public void testWaitForWithTimeout() throws InterruptedException, TimeoutExcepti @Test public void testReload() throws Exception { initializeExpectedJob(4); - JobInfo updatedInfo = JOB_INFO.toBuilder().etag("etag").build(); + JobInfo updatedInfo = JOB_INFO.toBuilder().setEtag("etag").build(); Job expectedJob = new Job(serviceMockReturnsOptions, new JobInfo.BuilderImpl(updatedInfo)); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getJob(JOB_INFO.jobId())).andReturn(expectedJob); + expect(bigquery.getJob(JOB_INFO.getJobId())).andReturn(expectedJob); replay(bigquery); initializeJob(); Job updatedJob = job.reload(); @@ -305,7 +330,7 @@ public void testReload() throws Exception { public void testReloadNull() throws Exception { initializeExpectedJob(1); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getJob(JOB_INFO.jobId())).andReturn(null); + expect(bigquery.getJob(JOB_INFO.getJobId())).andReturn(null); replay(bigquery); initializeJob(); assertNull(job.reload()); @@ -314,10 +339,10 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedJob(4); - JobInfo updatedInfo = JOB_INFO.toBuilder().etag("etag").build(); + JobInfo updatedInfo = JOB_INFO.toBuilder().setEtag("etag").build(); Job expectedJob = new Job(serviceMockReturnsOptions, new JobInfo.BuilderImpl(updatedInfo)); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getJob(JOB_INFO.jobId(), BigQuery.JobOption.fields())) + expect(bigquery.getJob(JOB_INFO.getJobId(), BigQuery.JobOption.fields())) .andReturn(expectedJob); replay(bigquery); initializeJob(); @@ -329,7 +354,7 @@ public void testReloadWithOptions() throws Exception { public void testCancel() throws Exception { initializeExpectedJob(1); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.cancel(JOB_INFO.jobId())).andReturn(true); + expect(bigquery.cancel(JOB_INFO.getJobId())).andReturn(true); replay(bigquery); initializeJob(); assertTrue(job.cancel()); @@ -339,7 +364,7 @@ public void testCancel() throws Exception { public void testBigquery() { initializeExpectedJob(1); replay(bigquery); - assertSame(serviceMockReturnsOptions, expectedJob.bigquery()); + assertSame(serviceMockReturnsOptions, expectedJob.getBigquery()); } @Test @@ -352,20 +377,20 @@ public void testToAndFromPb() { private void compareJob(Job expected, Job value) { assertEquals(expected, value); compareJobInfo(expected, value); - assertEquals(expected.bigquery().options(), value.bigquery().options()); + assertEquals(expected.getBigquery().options(), value.getBigquery().options()); } private void compareJobInfo(JobInfo expected, JobInfo value) { assertEquals(expected, value); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); - assertEquals(expected.etag(), value.etag()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.jobId(), value.jobId()); - assertEquals(expected.selfLink(), value.selfLink()); - assertEquals(expected.status(), value.status()); - assertEquals(expected.statistics(), value.statistics()); - assertEquals(expected.userEmail(), value.userEmail()); - assertEquals(expected.configuration(), value.configuration()); + assertEquals(expected.getEtag(), value.getEtag()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getJobId(), value.getJobId()); + assertEquals(expected.getSelfLink(), value.getSelfLink()); + assertEquals(expected.getStatus(), value.getStatus()); + assertEquals(expected.getStatistics(), value.getStatistics()); + assertEquals(expected.getUserEmail(), value.getUserEmail()); + assertEquals(expected.getConfiguration(), value.getConfiguration()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/LoadJobConfigurationTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/LoadJobConfigurationTest.java index 9980f85426d8..548e8ebcdacc 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/LoadJobConfigurationTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/LoadJobConfigurationTest.java @@ -29,10 +29,10 @@ public class LoadJobConfigurationTest { - private static final CsvOptions CSV_OPTIONS = CsvOptions.builder() - .allowJaggedRows(true) - .allowQuotedNewLines(false) - .encoding(StandardCharsets.UTF_8) + private static final CsvOptions CSV_OPTIONS = CsvOptions.newBuilder() + .setAllowJaggedRows(true) + .setAllowQuotedNewLines(false) + .setEncoding(StandardCharsets.UTF_8) .build(); private static final TableId TABLE_ID = TableId.of("dataset", "table"); private static final CreateDisposition CREATE_DISPOSITION = CreateDisposition.CREATE_IF_NEEDED; @@ -41,13 +41,23 @@ public class LoadJobConfigurationTest { private static final String FORMAT = "CSV"; private static final Boolean IGNORE_UNKNOWN_VALUES = true; private static final List PROJECTION_FIELDS = ImmutableList.of("field1", "field2"); - private static final Field FIELD_SCHEMA = Field.builder("IntegerField", Field.Type.integer()) - .mode(Field.Mode.REQUIRED) - .description("FieldDescription") + private static final Field FIELD_SCHEMA = Field.newBuilder("IntegerField", Field.Type.integer()) + .setMode(Field.Mode.REQUIRED) + .setDescription("FieldDescription") .build(); private static final List SOURCE_URIS = ImmutableList.of("uri1", "uri2"); private static final Schema TABLE_SCHEMA = Schema.of(FIELD_SCHEMA); private static final LoadJobConfiguration LOAD_CONFIGURATION = + LoadJobConfiguration.newBuilder(TABLE_ID, SOURCE_URIS) + .setCreateDisposition(CREATE_DISPOSITION) + .setWriteDisposition(WRITE_DISPOSITION) + .setFormatOptions(CSV_OPTIONS) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setMaxBadRecords(MAX_BAD_RECORDS) + .setProjectionFields(PROJECTION_FIELDS) + .setSchema(TABLE_SCHEMA) + .build(); + private static final LoadJobConfiguration DEPRECATED_LOAD_CONFIGURATION = LoadJobConfiguration.builder(TABLE_ID, SOURCE_URIS) .createDisposition(CREATE_DISPOSITION) .writeDisposition(WRITE_DISPOSITION) @@ -62,31 +72,31 @@ public class LoadJobConfigurationTest { public void testToBuilder() { compareLoadJobConfiguration(LOAD_CONFIGURATION, LOAD_CONFIGURATION.toBuilder().build()); LoadJobConfiguration configuration = LOAD_CONFIGURATION.toBuilder() - .destinationTable(TableId.of("dataset", "newTable")) + .setDestinationTable(TableId.of("dataset", "newTable")) .build(); - assertEquals("newTable", configuration.destinationTable().table()); - configuration = configuration.toBuilder().destinationTable(TABLE_ID).build(); + assertEquals("newTable", configuration.getDestinationTable().getTable()); + configuration = configuration.toBuilder().setDestinationTable(TABLE_ID).build(); compareLoadJobConfiguration(LOAD_CONFIGURATION, configuration); } @Test public void testOf() { LoadJobConfiguration configuration = LoadJobConfiguration.of(TABLE_ID, SOURCE_URIS); - assertEquals(TABLE_ID, configuration.destinationTable()); - assertEquals(SOURCE_URIS, configuration.sourceUris()); + assertEquals(TABLE_ID, configuration.getDestinationTable()); + assertEquals(SOURCE_URIS, configuration.getSourceUris()); configuration = LoadJobConfiguration.of(TABLE_ID, SOURCE_URIS, CSV_OPTIONS); - assertEquals(TABLE_ID, configuration.destinationTable()); - assertEquals(FORMAT, configuration.format()); - assertEquals(CSV_OPTIONS, configuration.csvOptions()); - assertEquals(SOURCE_URIS, configuration.sourceUris()); + assertEquals(TABLE_ID, configuration.getDestinationTable()); + assertEquals(FORMAT, configuration.getFormat()); + assertEquals(CSV_OPTIONS, configuration.getCsvOptions()); + assertEquals(SOURCE_URIS, configuration.getSourceUris()); configuration = LoadJobConfiguration.of(TABLE_ID, "uri1"); - assertEquals(TABLE_ID, configuration.destinationTable()); - assertEquals(ImmutableList.of("uri1"), configuration.sourceUris()); + assertEquals(TABLE_ID, configuration.getDestinationTable()); + assertEquals(ImmutableList.of("uri1"), configuration.getSourceUris()); configuration = LoadJobConfiguration.of(TABLE_ID, "uri1", CSV_OPTIONS); - assertEquals(TABLE_ID, configuration.destinationTable()); - assertEquals(FORMAT, configuration.format()); - assertEquals(CSV_OPTIONS, configuration.csvOptions()); - assertEquals(ImmutableList.of("uri1"), configuration.sourceUris()); + assertEquals(TABLE_ID, configuration.getDestinationTable()); + assertEquals(FORMAT, configuration.getFormat()); + assertEquals(CSV_OPTIONS, configuration.getCsvOptions()); + assertEquals(ImmutableList.of("uri1"), configuration.getSourceUris()); } @Test @@ -97,15 +107,28 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(TABLE_ID, LOAD_CONFIGURATION.destinationTable()); - assertEquals(CREATE_DISPOSITION, LOAD_CONFIGURATION.createDisposition()); - assertEquals(WRITE_DISPOSITION, LOAD_CONFIGURATION.writeDisposition()); - assertEquals(CSV_OPTIONS, LOAD_CONFIGURATION.csvOptions()); - assertEquals(FORMAT, LOAD_CONFIGURATION.format()); + assertEquals(TABLE_ID, DEPRECATED_LOAD_CONFIGURATION.destinationTable()); + assertEquals(CREATE_DISPOSITION, DEPRECATED_LOAD_CONFIGURATION.createDisposition()); + assertEquals(WRITE_DISPOSITION, DEPRECATED_LOAD_CONFIGURATION.writeDisposition()); + assertEquals(CSV_OPTIONS, DEPRECATED_LOAD_CONFIGURATION.csvOptions()); + assertEquals(FORMAT, DEPRECATED_LOAD_CONFIGURATION.format()); + assertEquals(IGNORE_UNKNOWN_VALUES, DEPRECATED_LOAD_CONFIGURATION.ignoreUnknownValues()); + assertEquals(MAX_BAD_RECORDS, DEPRECATED_LOAD_CONFIGURATION.maxBadRecords()); + assertEquals(PROJECTION_FIELDS, DEPRECATED_LOAD_CONFIGURATION.projectionFields()); + assertEquals(TABLE_SCHEMA, DEPRECATED_LOAD_CONFIGURATION.schema()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(TABLE_ID, LOAD_CONFIGURATION.getDestinationTable()); + assertEquals(CREATE_DISPOSITION, LOAD_CONFIGURATION.getCreateDisposition()); + assertEquals(WRITE_DISPOSITION, LOAD_CONFIGURATION.getWriteDisposition()); + assertEquals(CSV_OPTIONS, LOAD_CONFIGURATION.getCsvOptions()); + assertEquals(FORMAT, LOAD_CONFIGURATION.getFormat()); assertEquals(IGNORE_UNKNOWN_VALUES, LOAD_CONFIGURATION.ignoreUnknownValues()); - assertEquals(MAX_BAD_RECORDS, LOAD_CONFIGURATION.maxBadRecords()); - assertEquals(PROJECTION_FIELDS, LOAD_CONFIGURATION.projectionFields()); - assertEquals(TABLE_SCHEMA, LOAD_CONFIGURATION.schema()); + assertEquals(MAX_BAD_RECORDS, LOAD_CONFIGURATION.getMaxBadRecords()); + assertEquals(PROJECTION_FIELDS, LOAD_CONFIGURATION.getProjectionFields()); + assertEquals(TABLE_SCHEMA, LOAD_CONFIGURATION.getSchema()); } @Test @@ -119,7 +142,7 @@ public void testToPbAndFromPb() { @Test public void testSetProjectId() { LoadConfiguration configuration = LOAD_CONFIGURATION.setProjectId("p"); - assertEquals("p", configuration.destinationTable().project()); + assertEquals("p", configuration.getDestinationTable().getProject()); } private void compareLoadJobConfiguration(LoadJobConfiguration expected, @@ -127,14 +150,14 @@ private void compareLoadJobConfiguration(LoadJobConfiguration expected, assertEquals(expected, value); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); - assertEquals(expected.destinationTable(), value.destinationTable()); - assertEquals(expected.createDisposition(), value.createDisposition()); - assertEquals(expected.writeDisposition(), value.writeDisposition()); - assertEquals(expected.csvOptions(), value.csvOptions()); - assertEquals(expected.format(), value.format()); + assertEquals(expected.getDestinationTable(), value.getDestinationTable()); + assertEquals(expected.getCreateDisposition(), value.getCreateDisposition()); + assertEquals(expected.getWriteDisposition(), value.getWriteDisposition()); + assertEquals(expected.getCsvOptions(), value.getCsvOptions()); + assertEquals(expected.getFormat(), value.getFormat()); assertEquals(expected.ignoreUnknownValues(), value.ignoreUnknownValues()); - assertEquals(expected.maxBadRecords(), value.maxBadRecords()); - assertEquals(expected.projectionFields(), value.projectionFields()); - assertEquals(expected.schema(), value.schema()); + assertEquals(expected.getMaxBadRecords(), value.getMaxBadRecords()); + assertEquals(expected.getProjectionFields(), value.getProjectionFields()); + assertEquals(expected.getSchema(), value.getSchema()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/OptionTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/OptionTest.java index 2e40d63ff80c..0614e469de4b 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/OptionTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/OptionTest.java @@ -54,11 +54,11 @@ public void testHashCode() { @Test public void testConstructor() { - assertEquals(RPC_OPTION, OPTION.rpcOption()); - assertEquals(VALUE, OPTION.value()); + assertEquals(RPC_OPTION, OPTION.getRpcOption()); + assertEquals(VALUE, OPTION.getValue()); Option option = new Option(RPC_OPTION, null) {}; - assertEquals(RPC_OPTION, option.rpcOption()); - assertNull(option.value()); + assertEquals(RPC_OPTION, option.getRpcOption()); + assertNull(option.getValue()); thrown.expect(NullPointerException.class); new Option(null, VALUE) {}; } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryJobConfigurationTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryJobConfigurationTest.java index bafb7f00d934..b847ae9688ca 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryJobConfigurationTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryJobConfigurationTest.java @@ -39,30 +39,30 @@ public class QueryJobConfigurationTest { private static final TableId TABLE_ID = TableId.of("dataset", "table"); private static final List SOURCE_URIS = ImmutableList.of("uri1", "uri2"); private static final Field FIELD_SCHEMA1 = - Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) - .description("FieldDescription1") + Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) + .setDescription("FieldDescription1") .build(); private static final Field FIELD_SCHEMA2 = - Field.builder("IntegerField", Field.Type.integer()) - .mode(Field.Mode.REPEATED) - .description("FieldDescription2") + Field.newBuilder("IntegerField", Field.Type.integer()) + .setMode(Field.Mode.REPEATED) + .setDescription("FieldDescription2") .build(); private static final Field FIELD_SCHEMA3 = - Field.builder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) - .mode(Field.Mode.REQUIRED) - .description("FieldDescription3") + Field.newBuilder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) + .setMode(Field.Mode.REQUIRED) + .setDescription("FieldDescription3") .build(); private static final Schema TABLE_SCHEMA = Schema.of(FIELD_SCHEMA1, FIELD_SCHEMA2, FIELD_SCHEMA3); private static final Integer MAX_BAD_RECORDS = 42; private static final Boolean IGNORE_UNKNOWN_VALUES = true; private static final String COMPRESSION = "GZIP"; - private static final CsvOptions CSV_OPTIONS = CsvOptions.builder().build(); + private static final CsvOptions CSV_OPTIONS = CsvOptions.newBuilder().build(); private static final ExternalTableDefinition TABLE_CONFIGURATION = - ExternalTableDefinition.builder(SOURCE_URIS, TABLE_SCHEMA, CSV_OPTIONS) - .compression(COMPRESSION) - .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) - .maxBadRecords(MAX_BAD_RECORDS) + ExternalTableDefinition.newBuilder(SOURCE_URIS, TABLE_SCHEMA, CSV_OPTIONS) + .setCompression(COMPRESSION) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setMaxBadRecords(MAX_BAD_RECORDS) .build(); private static final Map TABLE_DEFINITIONS = ImmutableMap.of("tableName", TABLE_CONFIGURATION); @@ -76,6 +76,21 @@ public class QueryJobConfigurationTest { private static final List USER_DEFINED_FUNCTIONS = ImmutableList.of( UserDefinedFunction.inline("Function"), UserDefinedFunction.fromUri("URI")); private static final QueryJobConfiguration QUERY_JOB_CONFIGURATION = + QueryJobConfiguration.newBuilder(QUERY) + .setUseQueryCache(USE_QUERY_CACHE) + .setTableDefinitions(TABLE_DEFINITIONS) + .setAllowLargeResults(ALLOW_LARGE_RESULTS) + .setCreateDisposition(CREATE_DISPOSITION) + .setDefaultDataset(DATASET_ID) + .setDestinationTable(TABLE_ID) + .setWriteDisposition(WRITE_DISPOSITION) + .setPriority(PRIORITY) + .setFlattenResults(FLATTEN_RESULTS) + .setUserDefinedFunctions(USER_DEFINED_FUNCTIONS) + .setDryRun(true) + .setUseLegacySql(USE_LEGACY_SQL) + .build(); + private static final QueryJobConfiguration DEPRECATED_QUERY_JOB_CONFIGURATION = QueryJobConfiguration.builder(QUERY) .useQueryCache(USE_QUERY_CACHE) .tableDefinitions(TABLE_DEFINITIONS) @@ -96,17 +111,17 @@ public void testToBuilder() { compareQueryJobConfiguration(QUERY_JOB_CONFIGURATION, QUERY_JOB_CONFIGURATION.toBuilder().build()); QueryJobConfiguration job = QUERY_JOB_CONFIGURATION.toBuilder() - .query("New BigQuery SQL") + .setQuery("New BigQuery SQL") .build(); - assertEquals("New BigQuery SQL", job.query()); - job = job.toBuilder().query(QUERY).build(); + assertEquals("New BigQuery SQL", job.getQuery()); + job = job.toBuilder().setQuery(QUERY).build(); compareQueryJobConfiguration(QUERY_JOB_CONFIGURATION, job); } @Test public void testOf() { QueryJobConfiguration job = QueryJobConfiguration.of(QUERY); - assertEquals(QUERY, job.query()); + assertEquals(QUERY, job.getQuery()); } @Test @@ -117,6 +132,24 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { + assertEquals(ALLOW_LARGE_RESULTS, DEPRECATED_QUERY_JOB_CONFIGURATION.allowLargeResults()); + assertEquals(CREATE_DISPOSITION, DEPRECATED_QUERY_JOB_CONFIGURATION.getCreateDisposition()); + assertEquals(DATASET_ID, DEPRECATED_QUERY_JOB_CONFIGURATION.getDefaultDataset()); + assertEquals(TABLE_ID, DEPRECATED_QUERY_JOB_CONFIGURATION.getDestinationTable()); + assertEquals(FLATTEN_RESULTS, DEPRECATED_QUERY_JOB_CONFIGURATION.flattenResults()); + assertEquals(PRIORITY, DEPRECATED_QUERY_JOB_CONFIGURATION.getPriority()); + assertEquals(QUERY, DEPRECATED_QUERY_JOB_CONFIGURATION.getQuery()); + assertEquals(TABLE_DEFINITIONS, DEPRECATED_QUERY_JOB_CONFIGURATION.getTableDefinitions()); + assertEquals(USE_QUERY_CACHE, DEPRECATED_QUERY_JOB_CONFIGURATION.useQueryCache()); + assertEquals(USER_DEFINED_FUNCTIONS, + DEPRECATED_QUERY_JOB_CONFIGURATION.getUserDefinedFunctions()); + assertEquals(WRITE_DISPOSITION, DEPRECATED_QUERY_JOB_CONFIGURATION.getWriteDisposition()); + assertTrue(DEPRECATED_QUERY_JOB_CONFIGURATION.dryRun()); + assertTrue(DEPRECATED_QUERY_JOB_CONFIGURATION.useLegacySql()); + } + + @Test + public void testBuilderDeprecated() { assertEquals(ALLOW_LARGE_RESULTS, QUERY_JOB_CONFIGURATION.allowLargeResults()); assertEquals(CREATE_DISPOSITION, QUERY_JOB_CONFIGURATION.createDisposition()); assertEquals(DATASET_ID, QUERY_JOB_CONFIGURATION.defaultDataset()); @@ -147,8 +180,8 @@ public void testToPbAndFromPb() { @Test public void testSetProjectId() { QueryJobConfiguration configuration = QUERY_JOB_CONFIGURATION.setProjectId("p"); - assertEquals("p", configuration.defaultDataset().project()); - assertEquals("p", configuration.destinationTable().project()); + assertEquals("p", configuration.getDefaultDataset().getProject()); + assertEquals("p", configuration.getDestinationTable().getProject()); } private void compareQueryJobConfiguration(QueryJobConfiguration expected, @@ -158,16 +191,16 @@ private void compareQueryJobConfiguration(QueryJobConfiguration expected, assertEquals(expected.toString(), value.toString()); assertEquals(expected.dryRun(), value.dryRun()); assertEquals(expected.allowLargeResults(), value.allowLargeResults()); - assertEquals(expected.createDisposition(), value.createDisposition()); - assertEquals(expected.defaultDataset(), value.defaultDataset()); - assertEquals(expected.destinationTable(), value.destinationTable()); + assertEquals(expected.getCreateDisposition(), value.getCreateDisposition()); + assertEquals(expected.getDefaultDataset(), value.getDefaultDataset()); + assertEquals(expected.getDestinationTable(), value.getDestinationTable()); assertEquals(expected.flattenResults(), value.flattenResults()); - assertEquals(expected.priority(), value.priority()); - assertEquals(expected.query(), value.query()); - assertEquals(expected.tableDefinitions(), value.tableDefinitions()); + assertEquals(expected.getPriority(), value.getPriority()); + assertEquals(expected.getQuery(), value.getQuery()); + assertEquals(expected.getTableDefinitions(), value.getTableDefinitions()); assertEquals(expected.useQueryCache(), value.useQueryCache()); - assertEquals(expected.userDefinedFunctions(), value.userDefinedFunctions()); - assertEquals(expected.writeDisposition(), value.writeDisposition()); + assertEquals(expected.getUserDefinedFunctions(), value.getUserDefinedFunctions()); + assertEquals(expected.getWriteDisposition(), value.getWriteDisposition()); assertEquals(expected.useLegacySql(), value.useLegacySql()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryRequestTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryRequestTest.java index 083167d1ff31..92a331bc0180 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryRequestTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryRequestTest.java @@ -33,7 +33,15 @@ public class QueryRequestTest { private static final Long PAGE_SIZE = 42L; private static final Long MAX_WAIT_TIME = 42000L; private static final Boolean USE_LEGACY_SQL = true; - private static final QueryRequest QUERY_REQUEST = QueryRequest.builder(QUERY) + private static final QueryRequest QUERY_REQUEST = QueryRequest.newBuilder(QUERY) + .setUseQueryCache(USE_QUERY_CACHE) + .setDefaultDataset(DATASET_ID) + .setDryRun(DRY_RUN) + .setPageSize(PAGE_SIZE) + .setMaxWaitTime(MAX_WAIT_TIME) + .setUseLegacySql(USE_LEGACY_SQL) + .build(); + private static final QueryRequest DEPRECATED_QUERY_REQUEST = QueryRequest.builder(QUERY) .useQueryCache(USE_QUERY_CACHE) .defaultDataset(DATASET_ID) .dryRun(DRY_RUN) @@ -49,10 +57,10 @@ public class QueryRequestTest { public void testToBuilder() { compareQueryRequest(QUERY_REQUEST, QUERY_REQUEST.toBuilder().build()); QueryRequest queryRequest = QUERY_REQUEST.toBuilder() - .query("New BigQuery SQL") + .setQuery("New BigQuery SQL") .build(); - assertEquals("New BigQuery SQL", queryRequest.query()); - queryRequest = queryRequest.toBuilder().query(QUERY).build(); + assertEquals("New BigQuery SQL", queryRequest.getQuery()); + queryRequest = queryRequest.toBuilder().setQuery(QUERY).build(); compareQueryRequest(QUERY_REQUEST, queryRequest); } @@ -64,26 +72,39 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(QUERY, QUERY_REQUEST.query()); + assertEquals(QUERY, QUERY_REQUEST.getQuery()); assertEquals(USE_QUERY_CACHE, QUERY_REQUEST.useQueryCache()); - assertEquals(DATASET_ID, QUERY_REQUEST.defaultDataset()); + assertEquals(DATASET_ID, QUERY_REQUEST.getDefaultDataset()); assertEquals(DRY_RUN, QUERY_REQUEST.dryRun()); - assertEquals(PAGE_SIZE, QUERY_REQUEST.pageSize()); - assertEquals(MAX_WAIT_TIME, QUERY_REQUEST.maxWaitTime()); + assertEquals(PAGE_SIZE, QUERY_REQUEST.getPageSize()); + assertEquals(MAX_WAIT_TIME, QUERY_REQUEST.getMaxWaitTime()); assertTrue(QUERY_REQUEST.useLegacySql()); thrown.expect(NullPointerException.class); + QueryRequest.newBuilder(null); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(QUERY, DEPRECATED_QUERY_REQUEST.query()); + assertEquals(USE_QUERY_CACHE, DEPRECATED_QUERY_REQUEST.useQueryCache()); + assertEquals(DATASET_ID, DEPRECATED_QUERY_REQUEST.defaultDataset()); + assertEquals(DRY_RUN, DEPRECATED_QUERY_REQUEST.dryRun()); + assertEquals(PAGE_SIZE, DEPRECATED_QUERY_REQUEST.pageSize()); + assertEquals(MAX_WAIT_TIME, DEPRECATED_QUERY_REQUEST.maxWaitTime()); + assertTrue(DEPRECATED_QUERY_REQUEST.useLegacySql()); + thrown.expect(NullPointerException.class); QueryRequest.builder(null); } @Test public void testOf() { QueryRequest request = QueryRequest.of(QUERY); - assertEquals(QUERY, request.query()); + assertEquals(QUERY, request.getQuery()); assertNull(request.useQueryCache()); - assertNull(request.defaultDataset()); + assertNull(request.getDefaultDataset()); assertNull(request.dryRun()); - assertNull(request.pageSize()); - assertNull(request.maxWaitTime()); + assertNull(request.getPageSize()); + assertNull(request.getMaxWaitTime()); assertNull(request.useLegacySql()); thrown.expect(NullPointerException.class); QueryRequest.of(null); @@ -98,17 +119,17 @@ public void testToPbAndFromPb() { @Test public void testSetProjectId() { - assertEquals("p", QUERY_REQUEST.setProjectId("p").defaultDataset().project()); + assertEquals("p", QUERY_REQUEST.setProjectId("p").getDefaultDataset().getProject()); } private void compareQueryRequest(QueryRequest expected, QueryRequest value) { assertEquals(expected, value); - assertEquals(expected.query(), value.query()); + assertEquals(expected.getQuery(), value.getQuery()); assertEquals(expected.useQueryCache(), value.useQueryCache()); - assertEquals(expected.defaultDataset(), value.defaultDataset()); + assertEquals(expected.getDefaultDataset(), value.getDefaultDataset()); assertEquals(expected.dryRun(), value.dryRun()); - assertEquals(expected.pageSize(), value.pageSize()); - assertEquals(expected.maxWaitTime(), value.maxWaitTime()); + assertEquals(expected.getPageSize(), value.getPageSize()); + assertEquals(expected.getMaxWaitTime(), value.getMaxWaitTime()); assertEquals(expected.useLegacySql(), value.useLegacySql()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResponseTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResponseTest.java index 8eae6a9e03e3..b6c3bc61ff7e 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResponseTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResponseTest.java @@ -31,9 +31,9 @@ public class QueryResponseTest { private static final String ETAG = "etag"; private static final Field FIELD_SCHEMA1 = - Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) - .description("FieldDescription1") + Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) + .setDescription("FieldDescription1") .build(); private static final Schema SCHEMA = Schema.of(FIELD_SCHEMA1); private static final JobId JOB_ID = JobId.of("project", "job"); @@ -52,25 +52,35 @@ public QueryResult nextPage() { new BigQueryError("reason2", "location2", "message2", "debugInfo2") ); private static final Boolean CACHE_HIT = false; - private static final QueryResult QUERY_RESULT = QueryResult.builder() - .schema(SCHEMA) - .totalRows(TOTAL_ROWS) - .totalBytesProcessed(TOTAL_BYTES_PROCESSED) - .cursor("cursor") - .pageFetcher(FETCHER) - .results(ImmutableList.>of()) - .cacheHit(CACHE_HIT) + private static final QueryResult QUERY_RESULT = QueryResult.newBuilder() + .setSchema(SCHEMA) + .setTotalRows(TOTAL_ROWS) + .setTotalBytesProcessed(TOTAL_BYTES_PROCESSED) + .setCursor("cursor") + .setPageFetcher(FETCHER) + .setResults(ImmutableList.>of()) + .setCacheHit(CACHE_HIT) .build(); - private static final QueryResponse QUERY_RESPONSE = QueryResponse.builder() - .etag(ETAG) - .jobId(JOB_ID) - .jobCompleted(JOB_COMPLETE) - .executionErrors(ERRORS) - .result(QUERY_RESULT) + private static final QueryResponse QUERY_RESPONSE = QueryResponse.newBuilder() + .setEtag(ETAG) + .setJobId(JOB_ID) + .setJobCompleted(JOB_COMPLETE) + .setExecutionErrors(ERRORS) + .setResult(QUERY_RESULT) .build(); @Test public void testBuilder() { + assertEquals(ETAG, QUERY_RESPONSE.getEtag()); + assertEquals(QUERY_RESULT, QUERY_RESPONSE.getResult()); + assertEquals(JOB_ID, QUERY_RESPONSE.getJobId()); + assertEquals(JOB_COMPLETE, QUERY_RESPONSE.jobCompleted()); + assertEquals(ERRORS, QUERY_RESPONSE.getExecutionErrors()); + assertTrue(QUERY_RESPONSE.hasErrors()); + } + + @Test + public void testBuilderDeprecated() { assertEquals(ETAG, QUERY_RESPONSE.etag()); assertEquals(QUERY_RESULT, QUERY_RESPONSE.result()); assertEquals(JOB_ID, QUERY_RESPONSE.jobId()); @@ -81,12 +91,12 @@ public void testBuilder() { @Test public void testBuilderIncomplete() { - QueryResponse queryResponse = QueryResponse.builder().jobCompleted(false).build(); - assertNull(queryResponse.etag()); - assertNull(queryResponse.result()); - assertNull(queryResponse.jobId()); + QueryResponse queryResponse = QueryResponse.newBuilder().setJobCompleted(false).build(); + assertNull(queryResponse.getEtag()); + assertNull(queryResponse.getResult()); + assertNull(queryResponse.getJobId()); assertFalse(queryResponse.jobCompleted()); - assertEquals(ImmutableList.of(), queryResponse.executionErrors()); + assertEquals(ImmutableList.of(), queryResponse.getExecutionErrors()); assertFalse(queryResponse.hasErrors()); } @@ -97,11 +107,11 @@ public void testEquals() { private void compareQueryResponse(QueryResponse expected, QueryResponse value) { assertEquals(expected, value); - assertEquals(expected.etag(), value.etag()); - assertEquals(expected.result(), value.result()); - assertEquals(expected.jobId(), value.jobId()); + assertEquals(expected.getEtag(), value.getEtag()); + assertEquals(expected.getResult(), value.getResult()); + assertEquals(expected.getJobId(), value.getJobId()); assertEquals(expected.jobCompleted(), value.jobCompleted()); - assertEquals(expected.executionErrors(), value.executionErrors()); + assertEquals(expected.getExecutionErrors(), value.getExecutionErrors()); assertEquals(expected.hasErrors(), value.hasErrors()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResultTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResultTest.java index db4df54bfc0c..875560ee3032 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResultTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResultTest.java @@ -28,9 +28,9 @@ public class QueryResultTest { private static final String CURSOR = "cursor"; private static final Field FIELD_SCHEMA1 = - Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) - .description("FieldDescription1") + Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) + .setDescription("FieldDescription1") .build(); private static final Schema SCHEMA = Schema.of(FIELD_SCHEMA1); private static final long TOTAL_ROWS = 42L; @@ -43,21 +43,37 @@ public QueryResult nextPage() { }; private static final long TOTAL_BYTES_PROCESSED = 4200L; private static final boolean CACHE_HIT = false; - private static final QueryResult QUERY_RESULT = QueryResult.builder() - .schema(SCHEMA) - .totalRows(TOTAL_ROWS) - .totalBytesProcessed(TOTAL_BYTES_PROCESSED) - .cursor(CURSOR) - .pageFetcher(FETCHER) - .results(ImmutableList.>of()) - .cacheHit(CACHE_HIT) + private static final QueryResult QUERY_RESULT = QueryResult.newBuilder() + .setSchema(SCHEMA) + .setTotalRows(TOTAL_ROWS) + .setTotalBytesProcessed(TOTAL_BYTES_PROCESSED) + .setCursor(CURSOR) + .setPageFetcher(FETCHER) + .setResults(ImmutableList.>of()) + .setCacheHit(CACHE_HIT) .build(); - private static final QueryResult QUERY_RESULT_INCOMPLETE = QueryResult.builder() - .totalBytesProcessed(TOTAL_BYTES_PROCESSED) + private static final QueryResult QUERY_RESULT_INCOMPLETE = QueryResult.newBuilder() + .setTotalBytesProcessed(TOTAL_BYTES_PROCESSED) .build(); @Test public void testBuilder() { + assertEquals(SCHEMA, QUERY_RESULT.getSchema()); + assertEquals(TOTAL_ROWS, QUERY_RESULT.getTotalRows()); + assertEquals(TOTAL_BYTES_PROCESSED, QUERY_RESULT.getTotalBytesProcessed()); + assertEquals(CACHE_HIT, QUERY_RESULT.cacheHit()); + assertEquals(CURSOR, QUERY_RESULT.nextPageCursor()); + assertEquals(null, QUERY_RESULT.nextPage()); + assertEquals(null, QUERY_RESULT_INCOMPLETE.getSchema()); + assertEquals(0L, QUERY_RESULT_INCOMPLETE.getTotalRows()); + assertEquals(TOTAL_BYTES_PROCESSED, QUERY_RESULT_INCOMPLETE.getTotalBytesProcessed()); + assertEquals(false, QUERY_RESULT_INCOMPLETE.cacheHit()); + assertEquals(null, QUERY_RESULT_INCOMPLETE.nextPageCursor()); + assertEquals(null, QUERY_RESULT_INCOMPLETE.nextPage()); + } + + @Test + public void testBuilderDeprecated() { assertEquals(SCHEMA, QUERY_RESULT.schema()); assertEquals(TOTAL_ROWS, QUERY_RESULT.totalRows()); assertEquals(TOTAL_BYTES_PROCESSED, QUERY_RESULT.totalBytesProcessed()); @@ -83,9 +99,9 @@ private void compareQueryResult(QueryResult expected, QueryResult value) { assertEquals(expected.nextPage(), value.nextPage()); assertEquals(expected.nextPageCursor(), value.nextPageCursor()); assertEquals(expected.values(), value.values()); - assertEquals(expected.schema(), value.schema()); - assertEquals(expected.totalRows(), value.totalRows()); - assertEquals(expected.totalBytesProcessed(), value.totalBytesProcessed()); + assertEquals(expected.getSchema(), value.getSchema()); + assertEquals(expected.getTotalRows(), value.getTotalRows()); + assertEquals(expected.getTotalBytesProcessed(), value.getTotalBytesProcessed()); assertEquals(expected.cacheHit(), value.cacheHit()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryStageTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryStageTest.java index 670143190cf5..1bc90d8f4032 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryStageTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryStageTest.java @@ -45,24 +45,32 @@ public class QueryStageTest { private static final double WAIT_RATIO_MAX = 8.8; private static final double WRITE_RATIO_AVG = 9.9; private static final double WRITE_RATIO_MAX = 10.10; - private static final QueryStage QUERY_STAGE = QueryStage.builder() - .computeRatioAvg(COMPUTE_RATIO_AVG) - .computeRatioMax(COMPUTE_RATIO_MAX) - .generatedId(ID) - .name(NAME) - .readRatioAvg(READ_RATIO_AVG) - .readRatioMax(READ_RATIO_MAX) - .recordsRead(RECORDS_READ) - .recordsWritten(RECORDS_WRITTEN) - .steps(STEPS) - .waitRatioAvg(WAIT_RATIO_AVG) - .waitRatioMax(WAIT_RATIO_MAX) - .writeRatioAvg(WRITE_RATIO_AVG) - .writeRatioMax(WRITE_RATIO_MAX) + private static final QueryStage QUERY_STAGE = QueryStage.newBuilder() + .setComputeRationAvg(COMPUTE_RATIO_AVG) + .setComputeRatioMax(COMPUTE_RATIO_MAX) + .setGeneratedId(ID) + .setName(NAME) + .setReadRatioAvg(READ_RATIO_AVG) + .setReadRatioMax(READ_RATIO_MAX) + .setRecordsRead(RECORDS_READ) + .setRecordsWritten(RECORDS_WRITTEN) + .setSteps(STEPS) + .setWaitRatioAvg(WAIT_RATIO_AVG) + .setWaitRatioMax(WAIT_RATIO_MAX) + .setWriteRatioAvg(WRITE_RATIO_AVG) + .setWriteRatioMax(WRITE_RATIO_MAX) .build(); @Test public void testQueryStepConstructor() { + assertEquals("KIND", QUERY_STEP1.getName()); + assertEquals("KIND", QUERY_STEP2.getName()); + assertEquals(SUBSTEPS1, QUERY_STEP1.getSubsteps()); + assertEquals(SUBSTEPS2, QUERY_STEP2.getSubsteps()); + } + + @Test + public void testQueryStepConstructorDeprecated() { assertEquals("KIND", QUERY_STEP1.name()); assertEquals("KIND", QUERY_STEP2.name()); assertEquals(SUBSTEPS1, QUERY_STEP1.substeps()); @@ -71,6 +79,23 @@ public void testQueryStepConstructor() { @Test public void testBuilder() { + assertEquals(COMPUTE_RATIO_AVG, QUERY_STAGE.getComputeRatioAvg(), 0); + assertEquals(COMPUTE_RATIO_MAX, QUERY_STAGE.getComputeRatioMax(), 0); + assertEquals(ID, QUERY_STAGE.getGeneratedId()); + assertEquals(NAME, QUERY_STAGE.getName()); + assertEquals(READ_RATIO_AVG, QUERY_STAGE.getReadRatioAvg(), 0); + assertEquals(READ_RATIO_MAX, QUERY_STAGE.getReadRatioMax(), 0); + assertEquals(RECORDS_READ, QUERY_STAGE.getRecordsRead()); + assertEquals(RECORDS_WRITTEN, QUERY_STAGE.getRecordsWritten()); + assertEquals(STEPS, QUERY_STAGE.getSteps()); + assertEquals(WAIT_RATIO_AVG, QUERY_STAGE.getWaitRatioAvg(), 0); + assertEquals(WAIT_RATIO_MAX, QUERY_STAGE.getWaitRatioMax(), 0); + assertEquals(WRITE_RATIO_AVG, QUERY_STAGE.getWriteRatioAvg(), 0); + assertEquals(WRITE_RATIO_MAX, QUERY_STAGE.getWriteRatioMax(), 0); + } + + @Test + public void testBuilderDeprecated() { assertEquals(COMPUTE_RATIO_AVG, QUERY_STAGE.computeRatioAvg(), 0); assertEquals(COMPUTE_RATIO_MAX, QUERY_STAGE.computeRatioMax(), 0); assertEquals(ID, QUERY_STAGE.generatedId()); @@ -106,26 +131,26 @@ public void testEquals() { private void compareQueryStage(QueryStage expected, QueryStage value) { assertEquals(expected, value); - assertEquals(expected.computeRatioAvg(), value.computeRatioAvg(), 0); - assertEquals(expected.computeRatioMax(), value.computeRatioMax(), 0); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.name(), value.name()); - assertEquals(expected.readRatioAvg(), value.readRatioAvg(), 0); - assertEquals(expected.readRatioMax(), value.readRatioMax(), 0); - assertEquals(expected.recordsRead(), value.recordsRead()); - assertEquals(expected.recordsWritten(), value.recordsWritten()); - assertEquals(expected.steps(), value.steps()); - assertEquals(expected.waitRatioAvg(), value.waitRatioAvg(), 0); - assertEquals(expected.waitRatioMax(), value.waitRatioMax(), 0); - assertEquals(expected.writeRatioAvg(), value.writeRatioAvg(), 0); - assertEquals(expected.writeRatioMax(), value.writeRatioMax(), 0); + assertEquals(expected.getComputeRatioAvg(), value.getComputeRatioAvg(), 0); + assertEquals(expected.getComputeRatioMax(), value.getComputeRatioMax(), 0); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getReadRatioAvg(), value.getReadRatioAvg(), 0); + assertEquals(expected.getReadRatioMax(), value.getReadRatioMax(), 0); + assertEquals(expected.getRecordsRead(), value.getRecordsRead()); + assertEquals(expected.getRecordsWritten(), value.getRecordsWritten()); + assertEquals(expected.getSteps(), value.getSteps()); + assertEquals(expected.getWaitRatioAvg(), value.getWaitRatioAvg(), 0); + assertEquals(expected.getWaitRatioMax(), value.getWaitRatioMax(), 0); + assertEquals(expected.getWriteRatioAvg(), value.getWriteRatioAvg(), 0); + assertEquals(expected.getWriteRatioMax(), value.getWriteRatioMax(), 0); assertEquals(expected.hashCode(), value.hashCode()); } private void compareQueryStep(QueryStep expected, QueryStep value) { assertEquals(expected, value); - assertEquals(expected.name(), value.name()); - assertEquals(expected.substeps(), value.substeps()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getSubsteps(), value.getSubsteps()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SchemaTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SchemaTest.java index 312b7e674991..9fe59e377e59 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SchemaTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SchemaTest.java @@ -27,23 +27,24 @@ public class SchemaTest { private static final Field FIELD_SCHEMA1 = - Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) - .description("FieldDescription1") + Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) + .setDescription("FieldDescription1") .build(); private static final Field FIELD_SCHEMA2 = - Field.builder("IntegerField", Field.Type.integer()) - .mode(Field.Mode.REPEATED) - .description("FieldDescription2") + Field.newBuilder("IntegerField", Field.Type.integer()) + .setMode(Field.Mode.REPEATED) + .setDescription("FieldDescription2") .build(); private static final Field FIELD_SCHEMA3 = - Field.builder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) - .mode(Field.Mode.REQUIRED) - .description("FieldDescription3") + Field.newBuilder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) + .setMode(Field.Mode.REQUIRED) + .setDescription("FieldDescription3") .build(); private static final List FIELDS = ImmutableList.of(FIELD_SCHEMA1, FIELD_SCHEMA2, FIELD_SCHEMA3); - private static final Schema TABLE_SCHEMA = Schema.builder().fields(FIELDS).build(); + private static final Schema TABLE_SCHEMA = Schema.newBuilder().setFields(FIELDS).build(); + private static final Schema DEPRECATED_TABLE_SCHEMA = Schema.builder().fields(FIELDS).build(); @Test public void testToBuilder() { @@ -52,14 +53,24 @@ public void testToBuilder() { @Test public void testBuilder() { - assertEquals(FIELDS, TABLE_SCHEMA.fields()); + assertEquals(FIELDS, TABLE_SCHEMA.getFields()); Schema schema = TABLE_SCHEMA.toBuilder() - .fields(FIELD_SCHEMA1, FIELD_SCHEMA2) + .setFields(FIELD_SCHEMA1, FIELD_SCHEMA2) .addField(FIELD_SCHEMA3) .build(); compareTableSchema(TABLE_SCHEMA, schema); } + @Test + public void testBuilderDepreacated() { + assertEquals(FIELDS, DEPRECATED_TABLE_SCHEMA.fields()); + Schema schema = DEPRECATED_TABLE_SCHEMA.toBuilder() + .fields(FIELD_SCHEMA1, FIELD_SCHEMA2) + .addField(FIELD_SCHEMA3) + .build(); + compareTableSchema(DEPRECATED_TABLE_SCHEMA, schema); + } + @Test public void testOf() { compareTableSchema(TABLE_SCHEMA, Schema.of(FIELDS)); @@ -72,6 +83,6 @@ public void testToAndFromPb() { private void compareTableSchema(Schema expected, Schema value) { assertEquals(expected, value); - assertEquals(expected.fields(), value.fields()); + assertEquals(expected.getFields(), value.getFields()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java index ad32a9496728..016686d6f8c3 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java @@ -49,111 +49,111 @@ public class SerializationTest extends BaseSerializationTest { private static final String LOCATION = ""; private static final String SELF_LINK = "http://bigquery/p/d"; private static final DatasetId DATASET_ID = DatasetId.of("project", "dataset"); - private static final DatasetInfo DATASET_INFO = DatasetInfo.builder(DATASET_ID) - .acl(ACCESS_RULES) - .creationTime(CREATION_TIME) - .defaultTableLifetime(DEFAULT_TABLE_EXPIRATION) - .description(DESCRIPTION) - .etag(ETAG) - .friendlyName(FRIENDLY_NAME) - .generatedId(GENERATED_ID) - .lastModified(LAST_MODIFIED) - .location(LOCATION) - .selfLink(SELF_LINK) + private static final DatasetInfo DATASET_INFO = DatasetInfo.newBuilder(DATASET_ID) + .setAcl(ACCESS_RULES) + .setCreationTime(CREATION_TIME) + .setDefaultTableLifetime(DEFAULT_TABLE_EXPIRATION) + .setDescription(DESCRIPTION) + .setEtag(ETAG) + .setFriendlyName(FRIENDLY_NAME) + .setGeneratedId(GENERATED_ID) + .setLastModified(LAST_MODIFIED) + .setLocation(LOCATION) + .setSelfLink(SELF_LINK) .build(); private static final TableId TABLE_ID = TableId.of("project", "dataset", "table"); - private static final CsvOptions CSV_OPTIONS = CsvOptions.builder() - .allowJaggedRows(true) - .allowQuotedNewLines(false) - .encoding(StandardCharsets.ISO_8859_1) - .fieldDelimiter(",") - .quote("\"") - .skipLeadingRows(42L) + private static final CsvOptions CSV_OPTIONS = CsvOptions.newBuilder() + .setAllowJaggedRows(true) + .setAllowQuotedNewLines(false) + .setEncoding(StandardCharsets.ISO_8859_1) + .setFieldDelimiter(",") + .setQuote("\"") + .setSkipLeadingRows(42L) .build(); private static final Field FIELD_SCHEMA1 = - Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) - .description("FieldDescription1") + Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) + .setDescription("FieldDescription1") .build(); private static final Field FIELD_SCHEMA2 = - Field.builder("IntegerField", Field.Type.integer()) - .mode(Field.Mode.REPEATED) - .description("FieldDescription2") + Field.newBuilder("IntegerField", Field.Type.integer()) + .setMode(Field.Mode.REPEATED) + .setDescription("FieldDescription2") .build(); private static final Field FIELD_SCHEMA3 = - Field.builder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) - .mode(Field.Mode.REQUIRED) - .description("FieldDescription3") + Field.newBuilder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) + .setMode(Field.Mode.REQUIRED) + .setDescription("FieldDescription3") .build(); private static final Schema TABLE_SCHEMA = Schema.of(FIELD_SCHEMA1, FIELD_SCHEMA2, FIELD_SCHEMA3); private static final StreamingBuffer STREAMING_BUFFER = new StreamingBuffer(1L, 2L, 3L); private static final List SOURCE_URIS = ImmutableList.of("uri1", "uri2"); private static final ExternalTableDefinition EXTERNAL_TABLE_DEFINITION = - ExternalTableDefinition.builder(SOURCE_URIS, TABLE_SCHEMA, CSV_OPTIONS) - .ignoreUnknownValues(true) - .maxBadRecords(42) + ExternalTableDefinition.newBuilder(SOURCE_URIS, TABLE_SCHEMA, CSV_OPTIONS) + .setIgnoreUnknownValues(true) + .setMaxBadRecords(42) .build(); private static final UserDefinedFunction INLINE_FUNCTION = new UserDefinedFunction.InlineFunction("inline"); private static final UserDefinedFunction URI_FUNCTION = new UserDefinedFunction.UriFunction("URI"); - private static final TableDefinition TABLE_DEFINITION = StandardTableDefinition.builder() - .schema(TABLE_SCHEMA) - .location(LOCATION) - .streamingBuffer(STREAMING_BUFFER) + private static final TableDefinition TABLE_DEFINITION = StandardTableDefinition.newBuilder() + .setSchema(TABLE_SCHEMA) + .setLocation(LOCATION) + .setStreamingBuffer(STREAMING_BUFFER) .build(); - private static final TableInfo TABLE_INFO = TableInfo.builder(TABLE_ID, TABLE_DEFINITION) - .creationTime(CREATION_TIME) - .description(DESCRIPTION) - .etag(ETAG) - .generatedId(GENERATED_ID) + private static final TableInfo TABLE_INFO = TableInfo.newBuilder(TABLE_ID, TABLE_DEFINITION) + .setCreationTime(CREATION_TIME) + .setDescription(DESCRIPTION) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) .build(); private static final TableDefinition VIEW_DEFINITION = ViewDefinition.of("QUERY"); - private static final TableInfo VIEW_INFO = TableInfo.builder(TABLE_ID, VIEW_DEFINITION) - .creationTime(CREATION_TIME) - .description(DESCRIPTION) - .etag(ETAG) - .generatedId(GENERATED_ID) + private static final TableInfo VIEW_INFO = TableInfo.newBuilder(TABLE_ID, VIEW_DEFINITION) + .setCreationTime(CREATION_TIME) + .setDescription(DESCRIPTION) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) .build(); private static final TableInfo EXTERNAL_TABLE_INFO = - TableInfo.builder(TABLE_ID, EXTERNAL_TABLE_DEFINITION) - .creationTime(CREATION_TIME) - .description(DESCRIPTION) - .etag(ETAG) - .generatedId(GENERATED_ID) + TableInfo.newBuilder(TABLE_ID, EXTERNAL_TABLE_DEFINITION) + .setCreationTime(CREATION_TIME) + .setDescription(DESCRIPTION) + .setEtag(ETAG) + .setGeneratedId(GENERATED_ID) .build(); private static final JobStatistics.CopyStatistics COPY_STATISTICS = - JobStatistics.CopyStatistics.builder() - .creationTime(1L) - .endTime(3L) - .startTime(2L) + JobStatistics.CopyStatistics.newBuilder() + .setCreationTimestamp(1L) + .setEndTime(3L) + .setStartTime(2L) .build(); private static final JobStatistics.ExtractStatistics EXTRACT_STATISTICS = - JobStatistics.ExtractStatistics.builder() - .creationTime(1L) - .endTime(3L) - .startTime(2L) - .destinationUriFileCounts(ImmutableList.of(42L)) + JobStatistics.ExtractStatistics.newBuilder() + .setCreationTimestamp(1L) + .setEndTime(3L) + .setStartTime(2L) + .setDestinationUriFileCounts(ImmutableList.of(42L)) .build(); private static final JobStatistics.LoadStatistics LOAD_STATISTICS = - JobStatistics.LoadStatistics.builder() - .creationTime(1L) - .endTime(3L) - .startTime(2L) - .inputFiles(42L) - .outputBytes(1024L) - .inputBytes(2048L) - .outputRows(24L) + JobStatistics.LoadStatistics.newBuilder() + .setCreationTimestamp(1L) + .setEndTime(3L) + .setStartTime(2L) + .setInputFiles(42L) + .setOutputBytes(1024L) + .setInputBytes(2048L) + .setOutputRows(24L) .build(); private static final JobStatistics.QueryStatistics QUERY_STATISTICS = - JobStatistics.QueryStatistics.builder() - .creationTime(1L) - .endTime(3L) - .startTime(2L) - .totalBytesProcessed(2048L) - .totalBytesBilled(1024L) - .cacheHit(false) - .billingTier(42) + JobStatistics.QueryStatistics.newBuilder() + .setCreationTimestamp(1L) + .setEndTime(3L) + .setStartTime(2L) + .setTotalBytesProcessed(2048L) + .setTotalBytesBilled(1024L) + .setCacheHit(false) + .setBillingTier(42) .build(); private static final BigQueryError BIGQUERY_ERROR = new BigQueryError("reason", "location", "message", "debugInfo"); @@ -165,13 +165,13 @@ public class SerializationTest extends BaseSerializationTest { private static final ExtractJobConfiguration EXTRACT_JOB_CONFIGURATION = ExtractJobConfiguration.of(TABLE_ID, SOURCE_URIS); private static final WriteChannelConfiguration LOAD_CONFIGURATION = - WriteChannelConfiguration.builder(TABLE_ID) - .createDisposition(JobInfo.CreateDisposition.CREATE_IF_NEEDED) - .writeDisposition(JobInfo.WriteDisposition.WRITE_APPEND) - .formatOptions(CSV_OPTIONS) - .ignoreUnknownValues(true) - .maxBadRecords(10) - .schema(TABLE_SCHEMA) + WriteChannelConfiguration.newBuilder(TABLE_ID) + .setCreateDisposition(JobInfo.CreateDisposition.CREATE_IF_NEEDED) + .setWriteDisposition(JobInfo.WriteDisposition.WRITE_APPEND) + .setFormatOptions(CSV_OPTIONS) + .setIgnoreUnknownValues(true) + .setMaxBadRecords(10) + .setSchema(TABLE_SCHEMA) .build(); private static final LoadJobConfiguration LOAD_JOB_CONFIGURATION = LoadJobConfiguration.of(TABLE_ID, SOURCE_URIS); @@ -182,37 +182,37 @@ public class SerializationTest extends BaseSerializationTest { ImmutableMap.of("key", "val1"); private static final Map CONTENT2 = ImmutableMap.of("key", "val2"); - private static final InsertAllRequest INSERT_ALL_REQUEST = InsertAllRequest.builder(TABLE_ID) + private static final InsertAllRequest INSERT_ALL_REQUEST = InsertAllRequest.newBuilder(TABLE_ID) .addRow(CONTENT1) .addRow(CONTENT2) - .ignoreUnknownValues(true) - .skipInvalidRows(false) + .setIgnoreUnknownValues(true) + .setSkipInvalidRows(false) .build(); private static final Map> ERRORS_MAP = ImmutableMap.>of(0L, ImmutableList.of(BIGQUERY_ERROR)); private static final InsertAllResponse INSERT_ALL_RESPONSE = new InsertAllResponse(ERRORS_MAP); private static final FieldValue FIELD_VALUE = new FieldValue(FieldValue.Attribute.PRIMITIVE, "value"); - private static final QueryRequest QUERY_REQUEST = QueryRequest.builder("query") - .useQueryCache(true) - .defaultDataset(DATASET_ID) - .dryRun(false) - .pageSize(42L) - .maxWaitTime(10L) + private static final QueryRequest QUERY_REQUEST = QueryRequest.newBuilder("query") + .setUseQueryCache(true) + .setDefaultDataset(DATASET_ID) + .setDryRun(false) + .setPageSize(42L) + .setMaxWaitTime(10L) .build(); - private static final QueryResult QUERY_RESULT = QueryResult.builder() - .schema(TABLE_SCHEMA) - .totalRows(1L) - .totalBytesProcessed(42L) - .cursor("cursor") - .pageFetcher(null) - .results(ImmutableList.>of()) + private static final QueryResult QUERY_RESULT = QueryResult.newBuilder() + .setSchema(TABLE_SCHEMA) + .setTotalRows(1L) + .setTotalBytesProcessed(42L) + .setCursor("cursor") + .setPageFetcher(null) + .setResults(ImmutableList.>of()) .build(); - private static final QueryResponse QUERY_RESPONSE = QueryResponse.builder() - .etag(ETAG) - .jobId(JOB_ID) - .jobCompleted(true) - .result(QUERY_RESULT) + private static final QueryResponse QUERY_RESPONSE = QueryResponse.newBuilder() + .setEtag(ETAG) + .setJobId(JOB_ID) + .setJobCompleted(true) + .setResult(QUERY_RESULT) .build(); private static final BigQuery BIGQUERY = BigQueryOptions.builder().projectId("p1").build().service(); diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/StandardTableDefinitionTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/StandardTableDefinitionTest.java index 63f917c7834f..48e4d2e2ed0e 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/StandardTableDefinitionTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/StandardTableDefinitionTest.java @@ -27,19 +27,19 @@ public class StandardTableDefinitionTest { private static final Field FIELD_SCHEMA1 = - Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) - .description("FieldDescription1") + Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) + .setDescription("FieldDescription1") .build(); private static final Field FIELD_SCHEMA2 = - Field.builder("IntegerField", Field.Type.integer()) - .mode(Field.Mode.REPEATED) - .description("FieldDescription2") + Field.newBuilder("IntegerField", Field.Type.integer()) + .setMode(Field.Mode.REPEATED) + .setDescription("FieldDescription2") .build(); private static final Field FIELD_SCHEMA3 = - Field.builder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) - .mode(Field.Mode.REQUIRED) - .description("FieldDescription3") + Field.newBuilder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) + .setMode(Field.Mode.REQUIRED) + .setDescription("FieldDescription3") .build(); private static final Schema TABLE_SCHEMA = Schema.of(FIELD_SCHEMA1, FIELD_SCHEMA2, FIELD_SCHEMA3); private static final Long NUM_BYTES = 42L; @@ -49,11 +49,20 @@ public class StandardTableDefinitionTest { private static final TimePartitioning TIME_PARTITIONING = TimePartitioning.of(TimePartitioning.Type.DAY, 42); private static final StandardTableDefinition TABLE_DEFINITION = + StandardTableDefinition.newBuilder() + .setLocation(LOCATION) + .setNumBytes(NUM_BYTES) + .setNumRows(NUM_ROWS) + .setStreamingBuffer(STREAMING_BUFFER) + .setSchema(TABLE_SCHEMA) + .setTimePartitioning(TIME_PARTITIONING) + .build(); + private static final StandardTableDefinition DEPRECATED_TABLE_DEFINITION = StandardTableDefinition.builder() - .location(LOCATION) - .numBytes(NUM_BYTES) - .numRows(NUM_ROWS) - .streamingBuffer(STREAMING_BUFFER) + .setLocation(LOCATION) + .setNumBytes(NUM_BYTES) + .setNumRows(NUM_ROWS) + .setStreamingBuffer(STREAMING_BUFFER) .schema(TABLE_SCHEMA) .timePartitioning(TIME_PARTITIONING) .build(); @@ -61,10 +70,10 @@ public class StandardTableDefinitionTest { @Test public void testToBuilder() { compareStandardTableDefinition(TABLE_DEFINITION, TABLE_DEFINITION.toBuilder().build()); - StandardTableDefinition tableDefinition = TABLE_DEFINITION.toBuilder().location("EU").build(); - assertEquals("EU", tableDefinition.location()); + StandardTableDefinition tableDefinition = TABLE_DEFINITION.toBuilder().setLocation("EU").build(); + assertEquals("EU", tableDefinition.getLocation()); tableDefinition = tableDefinition.toBuilder() - .location(LOCATION) + .setLocation(LOCATION) .build(); compareStandardTableDefinition(TABLE_DEFINITION, tableDefinition); } @@ -77,25 +86,36 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(TableDefinition.Type.TABLE, TABLE_DEFINITION.type()); - assertEquals(TABLE_SCHEMA, TABLE_DEFINITION.schema()); - assertEquals(LOCATION, TABLE_DEFINITION.location()); - assertEquals(NUM_BYTES, TABLE_DEFINITION.numBytes()); - assertEquals(NUM_ROWS, TABLE_DEFINITION.numRows()); - assertEquals(STREAMING_BUFFER, TABLE_DEFINITION.streamingBuffer()); - assertEquals(TIME_PARTITIONING, TABLE_DEFINITION.timePartitioning()); + assertEquals(TableDefinition.Type.TABLE, TABLE_DEFINITION.getType()); + assertEquals(TABLE_SCHEMA, TABLE_DEFINITION.getSchema()); + assertEquals(LOCATION, TABLE_DEFINITION.getLocation()); + assertEquals(NUM_BYTES, TABLE_DEFINITION.getNumBytes()); + assertEquals(NUM_ROWS, TABLE_DEFINITION.getNumRows()); + assertEquals(STREAMING_BUFFER, TABLE_DEFINITION.getStreamingBuffer()); + assertEquals(TIME_PARTITIONING, TABLE_DEFINITION.getTimePartitioning()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(TableDefinition.Type.TABLE, DEPRECATED_TABLE_DEFINITION.type()); + assertEquals(TABLE_SCHEMA, DEPRECATED_TABLE_DEFINITION.schema()); + assertEquals(LOCATION, DEPRECATED_TABLE_DEFINITION.location()); + assertEquals(NUM_BYTES, DEPRECATED_TABLE_DEFINITION.numBytes()); + assertEquals(NUM_ROWS, DEPRECATED_TABLE_DEFINITION.numRows()); + assertEquals(STREAMING_BUFFER, DEPRECATED_TABLE_DEFINITION.streamingBuffer()); + assertEquals(TIME_PARTITIONING, DEPRECATED_TABLE_DEFINITION.timePartitioning()); } @Test public void testOf() { StandardTableDefinition definition = StandardTableDefinition.of(TABLE_SCHEMA); - assertEquals(TableDefinition.Type.TABLE, TABLE_DEFINITION.type()); - assertEquals(TABLE_SCHEMA, TABLE_DEFINITION.schema()); - assertNull(definition.location()); - assertNull(definition.numBytes()); - assertNull(definition.numRows()); - assertNull(definition.streamingBuffer()); - assertNull(definition.timePartitioning()); + assertEquals(TableDefinition.Type.TABLE, TABLE_DEFINITION.getType()); + assertEquals(TABLE_SCHEMA, TABLE_DEFINITION.getSchema()); + assertNull(definition.getLocation()); + assertNull(definition.getNumBytes()); + assertNull(definition.getNumRows()); + assertNull(definition.getStreamingBuffer()); + assertNull(definition.getTimePartitioning()); } @Test @@ -112,14 +132,14 @@ public void testToAndFromPb() { private void compareStandardTableDefinition(StandardTableDefinition expected, StandardTableDefinition value) { assertEquals(expected, value); - assertEquals(expected.schema(), value.schema()); - assertEquals(expected.type(), value.type()); - assertEquals(expected.numBytes(), value.numBytes()); - assertEquals(expected.numRows(), value.numRows()); - assertEquals(expected.location(), value.location()); - assertEquals(expected.streamingBuffer(), value.streamingBuffer()); - assertEquals(expected.type(), value.type()); - assertEquals(expected.timePartitioning(), value.timePartitioning()); + assertEquals(expected.getSchema(), value.getSchema()); + assertEquals(expected.getType(), value.getType()); + assertEquals(expected.getNumBytes(), value.getNumBytes()); + assertEquals(expected.getNumRows(), value.getNumRows()); + assertEquals(expected.getLocation(), value.getLocation()); + assertEquals(expected.getStreamingBuffer(), value.getStreamingBuffer()); + assertEquals(expected.getType(), value.getType()); + assertEquals(expected.getTimePartitioning(), value.getTimePartitioning()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableIdTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableIdTest.java index 7db923bdd7ca..a519d4d9966a 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableIdTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableIdTest.java @@ -27,6 +27,16 @@ public class TableIdTest { @Test public void testOf() { + assertEquals(null, TABLE.getProject()); + assertEquals("dataset", TABLE.getDataset()); + assertEquals("table", TABLE.getTable()); + assertEquals("project", TABLE_COMPLETE.getProject()); + assertEquals("dataset", TABLE_COMPLETE.getDataset()); + assertEquals("table", TABLE_COMPLETE.getTable()); + } + + @Test + public void testOfDeprecated() { assertEquals(null, TABLE.project()); assertEquals("dataset", TABLE.dataset()); assertEquals("table", TABLE.table()); @@ -54,8 +64,8 @@ public void testSetProjectId() { private void compareTableIds(TableId expected, TableId value) { assertEquals(expected, value); - assertEquals(expected.project(), value.project()); - assertEquals(expected.dataset(), value.dataset()); + assertEquals(expected.getProject(), value.getProject()); + assertEquals(expected.getDataset(), value.getDataset()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableInfoTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableInfoTest.java index 973d4f252007..fcc78f3e2c2d 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableInfoTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableInfoTest.java @@ -38,19 +38,19 @@ public class TableInfoTest { private static final Long LAST_MODIFIED_TIME = 20L; private static final Field FIELD_SCHEMA1 = - Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) - .description("FieldDescription1") + Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) + .setDescription("FieldDescription1") .build(); private static final Field FIELD_SCHEMA2 = - Field.builder("IntegerField", Field.Type.integer()) - .mode(Field.Mode.REPEATED) - .description("FieldDescription2") + Field.newBuilder("IntegerField", Field.Type.integer()) + .setMode(Field.Mode.REPEATED) + .setDescription("FieldDescription2") .build(); private static final Field FIELD_SCHEMA3 = - Field.builder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) - .mode(Field.Mode.REQUIRED) - .description("FieldDescription3") + Field.newBuilder("RecordField", Field.Type.record(FIELD_SCHEMA1, FIELD_SCHEMA2)) + .setMode(Field.Mode.REQUIRED) + .setDescription("FieldDescription3") .build(); private static final Schema TABLE_SCHEMA = Schema.of(FIELD_SCHEMA1, FIELD_SCHEMA2, FIELD_SCHEMA3); private static final Long NUM_BYTES = 42L; @@ -58,24 +58,25 @@ public class TableInfoTest { private static final String LOCATION = "US"; private static final StandardTableDefinition.StreamingBuffer STREAMING_BUFFER = new StandardTableDefinition.StreamingBuffer(1L, 2L, 3L); - private static final StandardTableDefinition TABLE_DEFINITION = StandardTableDefinition.builder() - .location(LOCATION) - .numBytes(NUM_BYTES) - .numRows(NUM_ROWS) - .streamingBuffer(STREAMING_BUFFER) - .schema(TABLE_SCHEMA) - .build(); + private static final StandardTableDefinition TABLE_DEFINITION = + StandardTableDefinition.newBuilder() + .setLocation(LOCATION) + .setNumBytes(NUM_BYTES) + .setNumRows(NUM_ROWS) + .setStreamingBuffer(STREAMING_BUFFER) + .setSchema(TABLE_SCHEMA) + .build(); private static final List SOURCE_URIS = ImmutableList.of("uri1", "uri2"); private static final Integer MAX_BAD_RECORDS = 42; private static final Boolean IGNORE_UNKNOWN_VALUES = true; private static final String COMPRESSION = "GZIP"; - private static final CsvOptions CSV_OPTIONS = CsvOptions.builder().build(); + private static final CsvOptions CSV_OPTIONS = CsvOptions.newBuilder().build(); private static final ExternalTableDefinition EXTERNAL_TABLE_DEFINITION = - ExternalTableDefinition.builder(SOURCE_URIS, TABLE_SCHEMA, CSV_OPTIONS) - .compression(COMPRESSION) - .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) - .maxBadRecords(MAX_BAD_RECORDS) + ExternalTableDefinition.newBuilder(SOURCE_URIS, TABLE_SCHEMA, CSV_OPTIONS) + .setCompression(COMPRESSION) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setMaxBadRecords(MAX_BAD_RECORDS) .build(); private static final String VIEW_QUERY = "VIEW QUERY"; @@ -84,36 +85,47 @@ public class TableInfoTest { private static final ViewDefinition VIEW_DEFINITION = ViewDefinition.builder(VIEW_QUERY, USER_DEFINED_FUNCTIONS).build(); - private static final TableInfo TABLE_INFO = TableInfo.builder(TABLE_ID, TABLE_DEFINITION) - .creationTime(CREATION_TIME) - .description(DESCRIPTION) - .etag(ETAG) - .expirationTime(EXPIRATION_TIME) - .friendlyName(FRIENDLY_NAME) - .generatedId(GENERATED_ID) - .lastModifiedTime(LAST_MODIFIED_TIME) - .selfLink(SELF_LINK) + private static final TableInfo TABLE_INFO = TableInfo.newBuilder(TABLE_ID, TABLE_DEFINITION) + .setCreationTime(CREATION_TIME) + .setDescription(DESCRIPTION) + .setEtag(ETAG) + .setExpirationTime(EXPIRATION_TIME) + .setFriendlyName(FRIENDLY_NAME) + .setGeneratedId(GENERATED_ID) + .setLastModifiedTime(LAST_MODIFIED_TIME) + .setSelfLink(SELF_LINK) .build(); - private static final TableInfo VIEW_INFO = TableInfo.builder(TABLE_ID, VIEW_DEFINITION) - .creationTime(CREATION_TIME) - .description(DESCRIPTION) - .etag(ETAG) - .expirationTime(EXPIRATION_TIME) - .friendlyName(FRIENDLY_NAME) - .generatedId(GENERATED_ID) - .lastModifiedTime(LAST_MODIFIED_TIME) - .selfLink(SELF_LINK) + private static final TableInfo VIEW_INFO = TableInfo.newBuilder(TABLE_ID, VIEW_DEFINITION) + .setCreationTime(CREATION_TIME) + .setDescription(DESCRIPTION) + .setEtag(ETAG) + .setExpirationTime(EXPIRATION_TIME) + .setFriendlyName(FRIENDLY_NAME) + .setGeneratedId(GENERATED_ID) + .setLastModifiedTime(LAST_MODIFIED_TIME) + .setSelfLink(SELF_LINK) .build(); private static final TableInfo EXTERNAL_TABLE_INFO = - TableInfo.builder(TABLE_ID, EXTERNAL_TABLE_DEFINITION) - .creationTime(CREATION_TIME) + TableInfo.newBuilder(TABLE_ID, EXTERNAL_TABLE_DEFINITION) + .setCreationTime(CREATION_TIME) + .setDescription(DESCRIPTION) + .setEtag(ETAG) + .setExpirationTime(EXPIRATION_TIME) + .setFriendlyName(FRIENDLY_NAME) + .setGeneratedId(GENERATED_ID) + .setLastModifiedTime(LAST_MODIFIED_TIME) + .setSelfLink(SELF_LINK) + .build(); + private static final TableInfo DEPRECATED_TABLE_INFO = + TableInfo.builder(TABLE_ID, TABLE_DEFINITION) + .setCreationTime(CREATION_TIME) .description(DESCRIPTION) - .etag(ETAG) + .setEtag(ETAG) .expirationTime(EXPIRATION_TIME) .friendlyName(FRIENDLY_NAME) - .generatedId(GENERATED_ID) - .lastModifiedTime(LAST_MODIFIED_TIME) - .selfLink(SELF_LINK) + .setGeneratedId(GENERATED_ID) + .setLastModifiedTime(LAST_MODIFIED_TIME) + .setSelfLink(SELF_LINK) .build(); @Test @@ -122,11 +134,11 @@ public void testToBuilder() { compareTableInfo(VIEW_INFO, VIEW_INFO.toBuilder().build()); compareTableInfo(EXTERNAL_TABLE_INFO, EXTERNAL_TABLE_INFO.toBuilder().build()); TableInfo tableInfo = TABLE_INFO.toBuilder() - .description("newDescription") + .setDescription("newDescription") .build(); - assertEquals("newDescription", tableInfo.description()); + assertEquals("newDescription", tableInfo.getDescription()); tableInfo = tableInfo.toBuilder() - .description("description") + .setDescription("description") .build(); compareTableInfo(TABLE_INFO, tableInfo); } @@ -143,74 +155,88 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(TABLE_ID, TABLE_INFO.tableId()); - assertEquals(CREATION_TIME, TABLE_INFO.creationTime()); - assertEquals(DESCRIPTION, TABLE_INFO.description()); - assertEquals(ETAG, TABLE_INFO.etag()); - assertEquals(EXPIRATION_TIME, TABLE_INFO.expirationTime()); - assertEquals(FRIENDLY_NAME, TABLE_INFO.friendlyName()); - assertEquals(GENERATED_ID, TABLE_INFO.generatedId()); - assertEquals(LAST_MODIFIED_TIME, TABLE_INFO.lastModifiedTime()); - assertEquals(TABLE_DEFINITION, TABLE_INFO.definition()); - assertEquals(SELF_LINK, TABLE_INFO.selfLink()); - assertEquals(TABLE_ID, VIEW_INFO.tableId()); - assertEquals(VIEW_DEFINITION, VIEW_INFO.definition()); - assertEquals(CREATION_TIME, VIEW_INFO.creationTime()); - assertEquals(DESCRIPTION, VIEW_INFO.description()); - assertEquals(ETAG, VIEW_INFO.etag()); - assertEquals(EXPIRATION_TIME, VIEW_INFO.expirationTime()); - assertEquals(FRIENDLY_NAME, VIEW_INFO.friendlyName()); - assertEquals(GENERATED_ID, VIEW_INFO.generatedId()); - assertEquals(LAST_MODIFIED_TIME, VIEW_INFO.lastModifiedTime()); - assertEquals(VIEW_DEFINITION, VIEW_INFO.definition()); - assertEquals(SELF_LINK, VIEW_INFO.selfLink()); - assertEquals(TABLE_ID, EXTERNAL_TABLE_INFO.tableId()); - assertEquals(CREATION_TIME, EXTERNAL_TABLE_INFO.creationTime()); - assertEquals(DESCRIPTION, EXTERNAL_TABLE_INFO.description()); - assertEquals(ETAG, EXTERNAL_TABLE_INFO.etag()); - assertEquals(EXPIRATION_TIME, EXTERNAL_TABLE_INFO.expirationTime()); - assertEquals(FRIENDLY_NAME, EXTERNAL_TABLE_INFO.friendlyName()); - assertEquals(GENERATED_ID, EXTERNAL_TABLE_INFO.generatedId()); - assertEquals(LAST_MODIFIED_TIME, EXTERNAL_TABLE_INFO.lastModifiedTime()); - assertEquals(EXTERNAL_TABLE_DEFINITION, EXTERNAL_TABLE_INFO.definition()); - assertEquals(SELF_LINK, EXTERNAL_TABLE_INFO.selfLink()); + assertEquals(TABLE_ID, TABLE_INFO.getTableId()); + assertEquals(CREATION_TIME, TABLE_INFO.getCreationTime()); + assertEquals(DESCRIPTION, TABLE_INFO.getDescription()); + assertEquals(ETAG, TABLE_INFO.getEtag()); + assertEquals(EXPIRATION_TIME, TABLE_INFO.getExpirationTime()); + assertEquals(FRIENDLY_NAME, TABLE_INFO.getFriendlyName()); + assertEquals(GENERATED_ID, TABLE_INFO.getGeneratedId()); + assertEquals(LAST_MODIFIED_TIME, TABLE_INFO.getLastModifiedTime()); + assertEquals(TABLE_DEFINITION, TABLE_INFO.getDefinition()); + assertEquals(SELF_LINK, TABLE_INFO.getSelfLink()); + assertEquals(TABLE_ID, VIEW_INFO.getTableId()); + assertEquals(VIEW_DEFINITION, VIEW_INFO.getDefinition()); + assertEquals(CREATION_TIME, VIEW_INFO.getCreationTime()); + assertEquals(DESCRIPTION, VIEW_INFO.getDescription()); + assertEquals(ETAG, VIEW_INFO.getEtag()); + assertEquals(EXPIRATION_TIME, VIEW_INFO.getExpirationTime()); + assertEquals(FRIENDLY_NAME, VIEW_INFO.getFriendlyName()); + assertEquals(GENERATED_ID, VIEW_INFO.getGeneratedId()); + assertEquals(LAST_MODIFIED_TIME, VIEW_INFO.getLastModifiedTime()); + assertEquals(VIEW_DEFINITION, VIEW_INFO.getDefinition()); + assertEquals(SELF_LINK, VIEW_INFO.getSelfLink()); + assertEquals(TABLE_ID, EXTERNAL_TABLE_INFO.getTableId()); + assertEquals(CREATION_TIME, EXTERNAL_TABLE_INFO.getCreationTime()); + assertEquals(DESCRIPTION, EXTERNAL_TABLE_INFO.getDescription()); + assertEquals(ETAG, EXTERNAL_TABLE_INFO.getEtag()); + assertEquals(EXPIRATION_TIME, EXTERNAL_TABLE_INFO.getExpirationTime()); + assertEquals(FRIENDLY_NAME, EXTERNAL_TABLE_INFO.getFriendlyName()); + assertEquals(GENERATED_ID, EXTERNAL_TABLE_INFO.getGeneratedId()); + assertEquals(LAST_MODIFIED_TIME, EXTERNAL_TABLE_INFO.getLastModifiedTime()); + assertEquals(EXTERNAL_TABLE_DEFINITION, EXTERNAL_TABLE_INFO.getDefinition()); + assertEquals(SELF_LINK, EXTERNAL_TABLE_INFO.getSelfLink()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(TABLE_ID, DEPRECATED_TABLE_INFO.tableId()); + assertEquals(CREATION_TIME, DEPRECATED_TABLE_INFO.creationTime()); + assertEquals(DESCRIPTION, DEPRECATED_TABLE_INFO.description()); + assertEquals(ETAG, DEPRECATED_TABLE_INFO.etag()); + assertEquals(EXPIRATION_TIME, DEPRECATED_TABLE_INFO.expirationTime()); + assertEquals(FRIENDLY_NAME, DEPRECATED_TABLE_INFO.friendlyName()); + assertEquals(GENERATED_ID, DEPRECATED_TABLE_INFO.generatedId()); + assertEquals(LAST_MODIFIED_TIME, DEPRECATED_TABLE_INFO.lastModifiedTime()); + assertEquals(TABLE_DEFINITION, DEPRECATED_TABLE_INFO.definition()); + assertEquals(SELF_LINK, DEPRECATED_TABLE_INFO.selfLink()); } @Test public void testOf() { TableInfo tableInfo = TableInfo.of(TABLE_ID, TABLE_DEFINITION); - assertEquals(TABLE_ID, tableInfo.tableId()); - assertNull(tableInfo.creationTime()); - assertNull(tableInfo.description()); - assertNull(tableInfo.etag()); - assertNull(tableInfo.expirationTime()); - assertNull(tableInfo.friendlyName()); - assertNull(tableInfo.generatedId()); - assertNull(tableInfo.lastModifiedTime()); - assertEquals(TABLE_DEFINITION, tableInfo.definition()); - assertNull(tableInfo.selfLink()); + assertEquals(TABLE_ID, tableInfo.getTableId()); + assertNull(tableInfo.getCreationTime()); + assertNull(tableInfo.getDescription()); + assertNull(tableInfo.getEtag()); + assertNull(tableInfo.getExpirationTime()); + assertNull(tableInfo.getFriendlyName()); + assertNull(tableInfo.getGeneratedId()); + assertNull(tableInfo.getLastModifiedTime()); + assertEquals(TABLE_DEFINITION, tableInfo.getDefinition()); + assertNull(tableInfo.getSelfLink()); tableInfo = TableInfo.of(TABLE_ID, VIEW_DEFINITION); - assertEquals(TABLE_ID, tableInfo.tableId()); - assertNull(tableInfo.creationTime()); - assertNull(tableInfo.description()); - assertNull(tableInfo.etag()); - assertNull(tableInfo.expirationTime()); - assertNull(tableInfo.friendlyName()); - assertNull(tableInfo.generatedId()); - assertNull(tableInfo.lastModifiedTime()); - assertEquals(VIEW_DEFINITION, tableInfo.definition()); - assertNull(tableInfo.selfLink()); + assertEquals(TABLE_ID, tableInfo.getTableId()); + assertNull(tableInfo.getCreationTime()); + assertNull(tableInfo.getDescription()); + assertNull(tableInfo.getEtag()); + assertNull(tableInfo.getExpirationTime()); + assertNull(tableInfo.getFriendlyName()); + assertNull(tableInfo.getGeneratedId()); + assertNull(tableInfo.getLastModifiedTime()); + assertEquals(VIEW_DEFINITION, tableInfo.getDefinition()); + assertNull(tableInfo.getSelfLink()); tableInfo = TableInfo.of(TABLE_ID, EXTERNAL_TABLE_DEFINITION); - assertEquals(TABLE_ID, tableInfo.tableId()); - assertNull(tableInfo.creationTime()); - assertNull(tableInfo.description()); - assertNull(tableInfo.etag()); - assertNull(tableInfo.expirationTime()); - assertNull(tableInfo.friendlyName()); - assertNull(tableInfo.generatedId()); - assertNull(tableInfo.lastModifiedTime()); - assertEquals(EXTERNAL_TABLE_DEFINITION, tableInfo.definition()); - assertNull(tableInfo.selfLink()); + assertEquals(TABLE_ID, tableInfo.getTableId()); + assertNull(tableInfo.getCreationTime()); + assertNull(tableInfo.getDescription()); + assertNull(tableInfo.getEtag()); + assertNull(tableInfo.getExpirationTime()); + assertNull(tableInfo.getFriendlyName()); + assertNull(tableInfo.getGeneratedId()); + assertNull(tableInfo.getLastModifiedTime()); + assertEquals(EXTERNAL_TABLE_DEFINITION, tableInfo.getDefinition()); + assertNull(tableInfo.getSelfLink()); } @Test @@ -222,24 +248,24 @@ public void testToAndFromPb() { @Test public void testSetProjectId() { - assertEquals("project", TABLE_INFO.setProjectId("project").tableId().project()); - assertEquals("project", EXTERNAL_TABLE_INFO.setProjectId("project").tableId().project()); - assertEquals("project", VIEW_INFO.setProjectId("project").tableId().project()); + assertEquals("project", TABLE_INFO.setProjectId("project").getTableId().getProject()); + assertEquals("project", EXTERNAL_TABLE_INFO.setProjectId("project").getTableId().getProject()); + assertEquals("project", VIEW_INFO.setProjectId("project").getTableId().getProject()); } private void compareTableInfo(TableInfo expected, TableInfo value) { assertEquals(expected, value); - assertEquals(expected.tableId(), value.tableId()); - assertEquals(expected.definition(), value.definition()); - assertEquals(expected.creationTime(), value.creationTime()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.etag(), value.etag()); - assertEquals(expected.expirationTime(), value.expirationTime()); - assertEquals(expected.friendlyName(), value.friendlyName()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.lastModifiedTime(), value.lastModifiedTime()); - assertEquals(expected.selfLink(), value.selfLink()); - assertEquals(expected.definition(), value.definition()); + assertEquals(expected.getTableId(), value.getTableId()); + assertEquals(expected.getDefinition(), value.getDefinition()); + assertEquals(expected.getCreationTime(), value.getCreationTime()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getEtag(), value.getEtag()); + assertEquals(expected.getExpirationTime(), value.getExpirationTime()); + assertEquals(expected.getFriendlyName(), value.getFriendlyName()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getLastModifiedTime(), value.getLastModifiedTime()); + assertEquals(expected.getSelfLink(), value.getSelfLink()); + assertEquals(expected.getDefinition(), value.getDefinition()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableTest.java index c74fc8e244bc..1a48d161a5c4 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableTest.java @@ -70,9 +70,9 @@ public class TableTest { private static final InsertAllRequest INSERT_ALL_REQUEST = InsertAllRequest.of(TABLE_ID1, ROWS_TO_INSERT); private static final InsertAllRequest INSERT_ALL_REQUEST_COMPLETE = - InsertAllRequest.builder(TABLE_ID1, ROWS_TO_INSERT) - .skipInvalidRows(true) - .ignoreUnknownValues(true) + InsertAllRequest.newBuilder(TABLE_ID1, ROWS_TO_INSERT) + .setSkipInvalidRows(true) + .setIgnoreUnknownValues(true) .build(); private static final InsertAllResponse EMPTY_INSERT_ALL_RESPONSE = new InsertAllResponse(ImmutableMap.>of()); @@ -110,14 +110,41 @@ public void testBuilder() { initializeExpectedTable(2); replay(bigquery); Table builtTable = new Table.Builder(serviceMockReturnsOptions, TABLE_ID1, TABLE_DEFINITION) - .creationTime(CREATION_TIME) + .setCreationTime(CREATION_TIME) + .setDescription(DESCRIPTION) + .setEtag(ETAG) + .setExpirationTime(EXPIRATION_TIME) + .setFriendlyName(FRIENDLY_NAME) + .setGeneratedId(GENERATED_ID) + .setLastModifiedTime(LAST_MODIFIED_TIME) + .setSelfLink(SELF_LINK) + .build(); + assertEquals(TABLE_ID1, builtTable.getTableId()); + assertEquals(CREATION_TIME, builtTable.getCreationTime()); + assertEquals(DESCRIPTION, builtTable.getDescription()); + assertEquals(ETAG, builtTable.getEtag()); + assertEquals(EXPIRATION_TIME, builtTable.getExpirationTime()); + assertEquals(FRIENDLY_NAME, builtTable.getFriendlyName()); + assertEquals(GENERATED_ID, builtTable.getGeneratedId()); + assertEquals(LAST_MODIFIED_TIME, builtTable.getLastModifiedTime()); + assertEquals(TABLE_DEFINITION, builtTable.getDefinition()); + assertEquals(SELF_LINK, builtTable.getSelfLink()); + assertSame(serviceMockReturnsOptions, builtTable.getBigquery()); + } + + @Test + public void testBuilderDeprecated() { + initializeExpectedTable(2); + replay(bigquery); + Table builtTable = new Table.Builder(serviceMockReturnsOptions, TABLE_ID1, TABLE_DEFINITION) + .setCreationTime(CREATION_TIME) .description(DESCRIPTION) - .etag(ETAG) + .setEtag(ETAG) .expirationTime(EXPIRATION_TIME) .friendlyName(FRIENDLY_NAME) - .generatedId(GENERATED_ID) - .lastModifiedTime(LAST_MODIFIED_TIME) - .selfLink(SELF_LINK) + .setGeneratedId(GENERATED_ID) + .setLastModifiedTime(LAST_MODIFIED_TIME) + .setSelfLink(SELF_LINK) .build(); assertEquals(TABLE_ID1, builtTable.tableId()); assertEquals(CREATION_TIME, builtTable.creationTime()); @@ -144,7 +171,7 @@ public void testExists_True() throws Exception { initializeExpectedTable(1); BigQuery.TableOption[] expectedOptions = {BigQuery.TableOption.fields()}; expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getTable(TABLE_INFO.tableId(), expectedOptions)).andReturn(expectedTable); + expect(bigquery.getTable(TABLE_INFO.getTableId(), expectedOptions)).andReturn(expectedTable); replay(bigquery); initializeTable(); assertTrue(table.exists()); @@ -155,7 +182,7 @@ public void testExists_False() throws Exception { initializeExpectedTable(1); BigQuery.TableOption[] expectedOptions = {BigQuery.TableOption.fields()}; expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getTable(TABLE_INFO.tableId(), expectedOptions)).andReturn(null); + expect(bigquery.getTable(TABLE_INFO.getTableId(), expectedOptions)).andReturn(null); replay(bigquery); initializeTable(); assertFalse(table.exists()); @@ -164,11 +191,11 @@ public void testExists_False() throws Exception { @Test public void testReload() throws Exception { initializeExpectedTable(4); - TableInfo updatedInfo = TABLE_INFO.toBuilder().description("Description").build(); + TableInfo updatedInfo = TABLE_INFO.toBuilder().setDescription("Description").build(); Table expectedTable = new Table(serviceMockReturnsOptions, new TableInfo.BuilderImpl(updatedInfo)); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getTable(TABLE_INFO.tableId())).andReturn(expectedTable); + expect(bigquery.getTable(TABLE_INFO.getTableId())).andReturn(expectedTable); replay(bigquery); initializeTable(); Table updatedTable = table.reload(); @@ -179,7 +206,7 @@ public void testReload() throws Exception { public void testReloadNull() throws Exception { initializeExpectedTable(1); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getTable(TABLE_INFO.tableId())).andReturn(null); + expect(bigquery.getTable(TABLE_INFO.getTableId())).andReturn(null); replay(bigquery); initializeTable(); assertNull(table.reload()); @@ -188,11 +215,11 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedTable(4); - TableInfo updatedInfo = TABLE_INFO.toBuilder().description("Description").build(); + TableInfo updatedInfo = TABLE_INFO.toBuilder().setDescription("Description").build(); Table expectedTable = new Table(serviceMockReturnsOptions, new TableInfo.BuilderImpl(updatedInfo)); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.getTable(TABLE_INFO.tableId(), BigQuery.TableOption.fields())) + expect(bigquery.getTable(TABLE_INFO.getTableId(), BigQuery.TableOption.fields())) .andReturn(expectedTable); replay(bigquery); initializeTable(); @@ -203,7 +230,7 @@ public void testReloadWithOptions() throws Exception { @Test public void testUpdate() { initializeExpectedTable(4); - Table expectedUpdatedTable = expectedTable.toBuilder().description("Description").build(); + Table expectedUpdatedTable = expectedTable.toBuilder().setDescription("Description").build(); expect(bigquery.options()).andReturn(mockOptions); expect(bigquery.update(eq(expectedTable))).andReturn(expectedUpdatedTable); replay(bigquery); @@ -215,7 +242,7 @@ public void testUpdate() { @Test public void testUpdateWithOptions() { initializeExpectedTable(4); - Table expectedUpdatedTable = expectedTable.toBuilder().description("Description").build(); + Table expectedUpdatedTable = expectedTable.toBuilder().setDescription("Description").build(); expect(bigquery.options()).andReturn(mockOptions); expect(bigquery.update(eq(expectedTable), eq(BigQuery.TableOption.fields()))) .andReturn(expectedUpdatedTable); @@ -229,7 +256,7 @@ public void testUpdateWithOptions() { public void testDeleteTrue() { initializeExpectedTable(1); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.delete(TABLE_INFO.tableId())).andReturn(true); + expect(bigquery.delete(TABLE_INFO.getTableId())).andReturn(true); replay(bigquery); initializeTable(); assertTrue(table.delete()); @@ -239,7 +266,7 @@ public void testDeleteTrue() { public void testDeleteFalse() { initializeExpectedTable(1); expect(bigquery.options()).andReturn(mockOptions); - expect(bigquery.delete(TABLE_INFO.tableId())).andReturn(false); + expect(bigquery.delete(TABLE_INFO.getTableId())).andReturn(false); replay(bigquery); initializeTable(); assertFalse(table.delete()); @@ -305,7 +332,7 @@ public void testCopyFromString() throws Exception { .andReturn(expectedJob); replay(bigquery); initializeTable(); - Job job = table.copy(TABLE_ID2.dataset(), TABLE_ID2.table()); + Job job = table.copy(TABLE_ID2.getDataset(), TABLE_ID2.getTable()); assertSame(expectedJob, job); } @@ -317,7 +344,7 @@ public void testCopyFromId() throws Exception { expect(bigquery.create(COPY_JOB_INFO)).andReturn(expectedJob); replay(bigquery); initializeTable(); - Job job = table.copy(TABLE_ID2.dataset(), TABLE_ID2.table()); + Job job = table.copy(TABLE_ID2.getDataset(), TABLE_ID2.getTable()); assertSame(expectedJob, job); } @@ -373,7 +400,7 @@ public void testExtractDataUris() throws Exception { public void testBigquery() { initializeExpectedTable(1); replay(bigquery); - assertSame(serviceMockReturnsOptions, expectedTable.bigquery()); + assertSame(serviceMockReturnsOptions, expectedTable.getBigquery()); } @Test @@ -386,22 +413,22 @@ public void testToAndFromPb() { private void compareTable(Table expected, Table value) { assertEquals(expected, value); compareTableInfo(expected, value); - assertEquals(expected.bigquery().options(), value.bigquery().options()); + assertEquals(expected.getBigquery().options(), value.getBigquery().options()); } private void compareTableInfo(TableInfo expected, TableInfo value) { assertEquals(expected, value); - assertEquals(expected.tableId(), value.tableId()); - assertEquals(expected.definition(), value.definition()); - assertEquals(expected.creationTime(), value.creationTime()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.etag(), value.etag()); - assertEquals(expected.expirationTime(), value.expirationTime()); - assertEquals(expected.friendlyName(), value.friendlyName()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.lastModifiedTime(), value.lastModifiedTime()); - assertEquals(expected.selfLink(), value.selfLink()); - assertEquals(expected.definition(), value.definition()); + assertEquals(expected.getTableId(), value.getTableId()); + assertEquals(expected.getDefinition(), value.getDefinition()); + assertEquals(expected.getCreationTime(), value.getCreationTime()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getEtag(), value.getEtag()); + assertEquals(expected.getExpirationTime(), value.getExpirationTime()); + assertEquals(expected.getFriendlyName(), value.getFriendlyName()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getLastModifiedTime(), value.getLastModifiedTime()); + assertEquals(expected.getSelfLink(), value.getSelfLink()); + assertEquals(expected.getDefinition(), value.getDefinition()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TimePartitioningTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TimePartitioningTest.java index 37b5c15926b3..d5e6c3cef989 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TimePartitioningTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TimePartitioningTest.java @@ -37,6 +37,15 @@ public class TimePartitioningTest { @Test public void testOf() { + assertEquals(TYPE, TIME_PARTITIONING.getType()); + assertEquals(EXPIRATION_MS, TIME_PARTITIONING.getExpirationMs().longValue()); + TimePartitioning partitioning = TimePartitioning.of(TYPE); + assertEquals(TYPE, partitioning.getType()); + assertNull(partitioning.getExpirationMs()); + } + + @Test + public void testOfDeprecated() { assertEquals(TYPE, TIME_PARTITIONING.type()); assertEquals(EXPIRATION_MS, TIME_PARTITIONING.expirationMs().longValue()); TimePartitioning partitioning = TimePartitioning.of(TYPE); @@ -65,8 +74,8 @@ public void testToAndFromPb() { private void compareTimePartitioning(TimePartitioning expected, TimePartitioning value) { assertEquals(expected, value); - assertEquals(expected.type(), value.type()); - assertEquals(expected.expirationMs(), value.expirationMs()); + assertEquals(expected.getType(), value.getType()); + assertEquals(expected.getExpirationMs(), value.getExpirationMs()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/UserDefinedFunctionTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/UserDefinedFunctionTest.java index db6cada4e0e5..2621a5e13798 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/UserDefinedFunctionTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/UserDefinedFunctionTest.java @@ -30,6 +30,14 @@ public class UserDefinedFunctionTest { @Test public void testConstructor() { + assertEquals(INLINE, INLINE_FUNCTION.getContent()); + assertEquals(UserDefinedFunction.Type.INLINE, INLINE_FUNCTION.getType()); + assertEquals(URI, URI_FUNCTION.getContent()); + assertEquals(UserDefinedFunction.Type.FROM_URI, URI_FUNCTION.getType()); + } + + @Test + public void testConstructorDeprecated() { assertEquals(INLINE, INLINE_FUNCTION.content()); assertEquals(UserDefinedFunction.Type.INLINE, INLINE_FUNCTION.type()); assertEquals(URI, URI_FUNCTION.content()); diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ViewDefinitionTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ViewDefinitionTest.java index 25c880bc8b78..864b8a97e659 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ViewDefinitionTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/ViewDefinitionTest.java @@ -17,6 +17,7 @@ package com.google.cloud.bigquery; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import com.google.common.collect.ImmutableList; @@ -31,17 +32,19 @@ public class ViewDefinitionTest { private static final List USER_DEFINED_FUNCTIONS = ImmutableList.of(UserDefinedFunction.inline("Function"), UserDefinedFunction.fromUri("URI")); private static final ViewDefinition VIEW_DEFINITION = + ViewDefinition.newBuilder(VIEW_QUERY, USER_DEFINED_FUNCTIONS).build(); + private static final ViewDefinition DEPRECATED_VIEW_DEFINITION = ViewDefinition.builder(VIEW_QUERY, USER_DEFINED_FUNCTIONS).build(); @Test public void testToBuilder() { compareViewDefinition(VIEW_DEFINITION, VIEW_DEFINITION.toBuilder().build()); ViewDefinition viewDefinition = VIEW_DEFINITION.toBuilder() - .query("NEW QUERY") + .setQuery("NEW QUERY") .build(); - assertEquals("NEW QUERY", viewDefinition.query()); + assertEquals("NEW QUERY", viewDefinition.getQuery()); viewDefinition = viewDefinition.toBuilder() - .query(VIEW_QUERY) + .setQuery(VIEW_QUERY) .build(); compareViewDefinition(VIEW_DEFINITION, viewDefinition); } @@ -54,9 +57,48 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(VIEW_QUERY, VIEW_DEFINITION.query()); - assertEquals(TableDefinition.Type.VIEW, VIEW_DEFINITION.type()); - assertEquals(USER_DEFINED_FUNCTIONS, VIEW_DEFINITION.userDefinedFunctions()); + assertEquals(VIEW_QUERY, VIEW_DEFINITION.getQuery()); + assertEquals(TableDefinition.Type.VIEW, VIEW_DEFINITION.getType()); + assertEquals(USER_DEFINED_FUNCTIONS, VIEW_DEFINITION.getUserDefinedFunctions()); + ViewDefinition viewDefinition = ViewDefinition.newBuilder(VIEW_QUERY) + .setUserDefinedFunctions(UserDefinedFunction.inline("Function"), + UserDefinedFunction.fromUri("URI")) + .build(); + assertEquals(VIEW_QUERY, viewDefinition.getQuery()); + assertEquals(TableDefinition.Type.VIEW, viewDefinition.getType()); + assertEquals(USER_DEFINED_FUNCTIONS, viewDefinition.getUserDefinedFunctions()); + viewDefinition = ViewDefinition.newBuilder(VIEW_QUERY, + UserDefinedFunction.inline("Function"), UserDefinedFunction.fromUri("URI")).build(); + assertEquals(VIEW_QUERY, viewDefinition.getQuery()); + assertEquals(TableDefinition.Type.VIEW, viewDefinition.getType()); + assertEquals(USER_DEFINED_FUNCTIONS, viewDefinition.getUserDefinedFunctions()); + viewDefinition = ViewDefinition.newBuilder(VIEW_QUERY).build(); + assertEquals(VIEW_QUERY, viewDefinition.getQuery()); + assertEquals(TableDefinition.Type.VIEW, viewDefinition.getType()); + assertNull(viewDefinition.getUserDefinedFunctions()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(VIEW_QUERY, DEPRECATED_VIEW_DEFINITION.query()); + assertEquals(TableDefinition.Type.VIEW, DEPRECATED_VIEW_DEFINITION.type()); + assertEquals(USER_DEFINED_FUNCTIONS, DEPRECATED_VIEW_DEFINITION.userDefinedFunctions()); + ViewDefinition viewDefinition = ViewDefinition.builder(VIEW_QUERY) + .userDefinedFunctions(UserDefinedFunction.inline("Function"), + UserDefinedFunction.fromUri("URI")) + .build(); + assertEquals(VIEW_QUERY, viewDefinition.query()); + assertEquals(TableDefinition.Type.VIEW, viewDefinition.type()); + assertEquals(USER_DEFINED_FUNCTIONS, viewDefinition.userDefinedFunctions()); + viewDefinition = ViewDefinition.builder(VIEW_QUERY, + UserDefinedFunction.inline("Function"), UserDefinedFunction.fromUri("URI")).build(); + assertEquals(VIEW_QUERY, viewDefinition.query()); + assertEquals(TableDefinition.Type.VIEW, viewDefinition.type()); + assertEquals(USER_DEFINED_FUNCTIONS, viewDefinition.userDefinedFunctions()); + viewDefinition = ViewDefinition.builder(VIEW_QUERY).build(); + assertEquals(VIEW_QUERY, viewDefinition.query()); + assertEquals(TableDefinition.Type.VIEW, viewDefinition.type()); + assertNull(viewDefinition.userDefinedFunctions()); } @Test @@ -68,8 +110,8 @@ public void testToAndFromPb() { private void compareViewDefinition(ViewDefinition expected, ViewDefinition value) { assertEquals(expected, value); - assertEquals(expected.query(), value.query()); - assertEquals(expected.userDefinedFunctions(), value.userDefinedFunctions()); + assertEquals(expected.getQuery(), value.getQuery()); + assertEquals(expected.getUserDefinedFunctions(), value.getUserDefinedFunctions()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/WriteChannelConfigurationTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/WriteChannelConfigurationTest.java index ffe1e58dc19e..0e3524d2fb25 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/WriteChannelConfigurationTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/WriteChannelConfigurationTest.java @@ -30,10 +30,10 @@ public class WriteChannelConfigurationTest { - private static final CsvOptions CSV_OPTIONS = CsvOptions.builder() - .allowJaggedRows(true) - .allowQuotedNewLines(false) - .encoding(StandardCharsets.UTF_8) + private static final CsvOptions CSV_OPTIONS = CsvOptions.newBuilder() + .setAllowJaggedRows(true) + .setAllowQuotedNewLines(false) + .setEncoding(StandardCharsets.UTF_8) .build(); private static final TableId TABLE_ID = TableId.of("dataset", "table"); private static final CreateDisposition CREATE_DISPOSITION = CreateDisposition.CREATE_IF_NEEDED; @@ -42,12 +42,22 @@ public class WriteChannelConfigurationTest { private static final String FORMAT = "CSV"; private static final Boolean IGNORE_UNKNOWN_VALUES = true; private static final List PROJECTION_FIELDS = ImmutableList.of("field1", "field2"); - private static final Field FIELD_SCHEMA = Field.builder("IntegerField", Field.Type.integer()) - .mode(Field.Mode.REQUIRED) - .description("FieldDescription") + private static final Field FIELD_SCHEMA = Field.newBuilder("IntegerField", Field.Type.integer()) + .setMode(Field.Mode.REQUIRED) + .setDescription("FieldDescription") .build(); private static final Schema TABLE_SCHEMA = Schema.of(FIELD_SCHEMA); private static final WriteChannelConfiguration LOAD_CONFIGURATION = + WriteChannelConfiguration.newBuilder(TABLE_ID) + .setCreateDisposition(CREATE_DISPOSITION) + .setWriteDisposition(WRITE_DISPOSITION) + .setFormatOptions(CSV_OPTIONS) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setMaxBadRecords(MAX_BAD_RECORDS) + .setProjectionFields(PROJECTION_FIELDS) + .setSchema(TABLE_SCHEMA) + .build(); + private static final WriteChannelConfiguration DEPRECATED_LOAD_CONFIGURATION = WriteChannelConfiguration.builder(TABLE_ID) .createDisposition(CREATE_DISPOSITION) .writeDisposition(WRITE_DISPOSITION) @@ -62,21 +72,21 @@ public class WriteChannelConfigurationTest { public void testToBuilder() { compareLoadConfiguration(LOAD_CONFIGURATION, LOAD_CONFIGURATION.toBuilder().build()); WriteChannelConfiguration configuration = LOAD_CONFIGURATION.toBuilder() - .destinationTable(TableId.of("dataset", "newTable")) + .setDestinationTable(TableId.of("dataset", "newTable")) .build(); - assertEquals("newTable", configuration.destinationTable().table()); - configuration = configuration.toBuilder().destinationTable(TABLE_ID).build(); + assertEquals("newTable", configuration.getDestinationTable().getTable()); + configuration = configuration.toBuilder().setDestinationTable(TABLE_ID).build(); compareLoadConfiguration(LOAD_CONFIGURATION, configuration); } @Test public void testOf() { WriteChannelConfiguration configuration = WriteChannelConfiguration.of(TABLE_ID); - assertEquals(TABLE_ID, configuration.destinationTable()); + assertEquals(TABLE_ID, configuration.getDestinationTable()); configuration = WriteChannelConfiguration.of(TABLE_ID, CSV_OPTIONS); - assertEquals(TABLE_ID, configuration.destinationTable()); - assertEquals(FORMAT, configuration.format()); - assertEquals(CSV_OPTIONS, configuration.csvOptions()); + assertEquals(TABLE_ID, configuration.getDestinationTable()); + assertEquals(FORMAT, configuration.getFormat()); + assertEquals(CSV_OPTIONS, configuration.getCsvOptions()); } @Test @@ -87,15 +97,64 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(TABLE_ID, LOAD_CONFIGURATION.destinationTable()); - assertEquals(CREATE_DISPOSITION, LOAD_CONFIGURATION.createDisposition()); - assertEquals(WRITE_DISPOSITION, LOAD_CONFIGURATION.writeDisposition()); - assertEquals(CSV_OPTIONS, LOAD_CONFIGURATION.csvOptions()); - assertEquals(FORMAT, LOAD_CONFIGURATION.format()); + assertEquals(TABLE_ID, LOAD_CONFIGURATION.getDestinationTable()); + assertEquals(CREATE_DISPOSITION, LOAD_CONFIGURATION.getCreateDisposition()); + assertEquals(WRITE_DISPOSITION, LOAD_CONFIGURATION.getWriteDisposition()); + assertEquals(CSV_OPTIONS, LOAD_CONFIGURATION.getCsvOptions()); + assertEquals(FORMAT, LOAD_CONFIGURATION.getFormat()); assertEquals(IGNORE_UNKNOWN_VALUES, LOAD_CONFIGURATION.ignoreUnknownValues()); - assertEquals(MAX_BAD_RECORDS, LOAD_CONFIGURATION.maxBadRecords()); - assertEquals(PROJECTION_FIELDS, LOAD_CONFIGURATION.projectionFields()); - assertEquals(TABLE_SCHEMA, LOAD_CONFIGURATION.schema()); + assertEquals(MAX_BAD_RECORDS, LOAD_CONFIGURATION.getMaxBadRecords()); + assertEquals(PROJECTION_FIELDS, LOAD_CONFIGURATION.getProjectionFields()); + assertEquals(TABLE_SCHEMA, LOAD_CONFIGURATION.getSchema()); + WriteChannelConfiguration loadConfiguration = + WriteChannelConfiguration.newBuilder(TABLE_ID, CSV_OPTIONS) + .setCreateDisposition(CREATE_DISPOSITION) + .setWriteDisposition(WRITE_DISPOSITION) + .setIgnoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .setMaxBadRecords(MAX_BAD_RECORDS) + .setProjectionFields(PROJECTION_FIELDS) + .setSchema(TABLE_SCHEMA) + .build(); + assertEquals(TABLE_ID, loadConfiguration.getDestinationTable()); + assertEquals(CREATE_DISPOSITION, loadConfiguration.getCreateDisposition()); + assertEquals(WRITE_DISPOSITION, loadConfiguration.getWriteDisposition()); + assertEquals(CSV_OPTIONS, loadConfiguration.getCsvOptions()); + assertEquals(FORMAT, loadConfiguration.getFormat()); + assertEquals(IGNORE_UNKNOWN_VALUES, loadConfiguration.ignoreUnknownValues()); + assertEquals(MAX_BAD_RECORDS, loadConfiguration.getMaxBadRecords()); + assertEquals(PROJECTION_FIELDS, loadConfiguration.getProjectionFields()); + assertEquals(TABLE_SCHEMA, loadConfiguration.getSchema()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(TABLE_ID, DEPRECATED_LOAD_CONFIGURATION.destinationTable()); + assertEquals(CREATE_DISPOSITION, DEPRECATED_LOAD_CONFIGURATION.createDisposition()); + assertEquals(WRITE_DISPOSITION, DEPRECATED_LOAD_CONFIGURATION.writeDisposition()); + assertEquals(CSV_OPTIONS, DEPRECATED_LOAD_CONFIGURATION.csvOptions()); + assertEquals(FORMAT, DEPRECATED_LOAD_CONFIGURATION.format()); + assertEquals(IGNORE_UNKNOWN_VALUES, DEPRECATED_LOAD_CONFIGURATION.ignoreUnknownValues()); + assertEquals(MAX_BAD_RECORDS, DEPRECATED_LOAD_CONFIGURATION.maxBadRecords()); + assertEquals(PROJECTION_FIELDS, DEPRECATED_LOAD_CONFIGURATION.projectionFields()); + assertEquals(TABLE_SCHEMA, DEPRECATED_LOAD_CONFIGURATION.schema()); + WriteChannelConfiguration loadConfiguration = + WriteChannelConfiguration.builder(TABLE_ID, CSV_OPTIONS) + .createDisposition(CREATE_DISPOSITION) + .writeDisposition(WRITE_DISPOSITION) + .ignoreUnknownValues(IGNORE_UNKNOWN_VALUES) + .maxBadRecords(MAX_BAD_RECORDS) + .projectionFields(PROJECTION_FIELDS) + .schema(TABLE_SCHEMA) + .build(); + assertEquals(TABLE_ID, loadConfiguration.destinationTable()); + assertEquals(CREATE_DISPOSITION, loadConfiguration.createDisposition()); + assertEquals(WRITE_DISPOSITION, loadConfiguration.writeDisposition()); + assertEquals(CSV_OPTIONS, loadConfiguration.csvOptions()); + assertEquals(FORMAT, loadConfiguration.format()); + assertEquals(IGNORE_UNKNOWN_VALUES, loadConfiguration.ignoreUnknownValues()); + assertEquals(MAX_BAD_RECORDS, loadConfiguration.maxBadRecords()); + assertEquals(PROJECTION_FIELDS, loadConfiguration.projectionFields()); + assertEquals(TABLE_SCHEMA, loadConfiguration.schema()); } @Test @@ -112,14 +171,14 @@ private void compareLoadConfiguration(WriteChannelConfiguration expected, assertEquals(expected, value); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); - assertEquals(expected.destinationTable(), value.destinationTable()); - assertEquals(expected.createDisposition(), value.createDisposition()); - assertEquals(expected.writeDisposition(), value.writeDisposition()); - assertEquals(expected.csvOptions(), value.csvOptions()); - assertEquals(expected.format(), value.format()); + assertEquals(expected.getDestinationTable(), value.getDestinationTable()); + assertEquals(expected.getCreateDisposition(), value.getCreateDisposition()); + assertEquals(expected.getWriteDisposition(), value.getWriteDisposition()); + assertEquals(expected.getCsvOptions(), value.getCsvOptions()); + assertEquals(expected.getFormat(), value.getFormat()); assertEquals(expected.ignoreUnknownValues(), value.ignoreUnknownValues()); - assertEquals(expected.maxBadRecords(), value.maxBadRecords()); - assertEquals(expected.projectionFields(), value.projectionFields()); - assertEquals(expected.schema(), value.schema()); + assertEquals(expected.getMaxBadRecords(), value.getMaxBadRecords()); + assertEquals(expected.getProjectionFields(), value.getProjectionFields()); + assertEquals(expected.getSchema(), value.getSchema()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java index 367935d298bb..61b3ae83753a 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java @@ -102,48 +102,48 @@ public class ITBigQueryTest { private static final String DESCRIPTION = "Test dataset"; private static final String OTHER_DATASET = RemoteBigQueryHelper.generateDatasetName(); private static final Field TIMESTAMP_FIELD_SCHEMA = - Field.builder("TimestampField", Field.Type.timestamp()) - .mode(Field.Mode.NULLABLE) - .description("TimestampDescription") + Field.newBuilder("TimestampField", Field.Type.timestamp()) + .setMode(Field.Mode.NULLABLE) + .setDescription("TimestampDescription") .build(); private static final Field STRING_FIELD_SCHEMA = - Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) - .description("StringDescription") + Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) + .setDescription("StringDescription") .build(); private static final Field INTEGER_FIELD_SCHEMA = - Field.builder("IntegerField", Field.Type.integer()) - .mode(Field.Mode.REPEATED) - .description("IntegerDescription") + Field.newBuilder("IntegerField", Field.Type.integer()) + .setMode(Field.Mode.REPEATED) + .setDescription("IntegerDescription") .build(); private static final Field BOOLEAN_FIELD_SCHEMA = - Field.builder("BooleanField", Field.Type.bool()) - .mode(Field.Mode.NULLABLE) - .description("BooleanDescription") + Field.newBuilder("BooleanField", Field.Type.bool()) + .setMode(Field.Mode.NULLABLE) + .setDescription("BooleanDescription") .build(); private static final Field BYTES_FIELD_SCHEMA = - Field.builder("BytesField", Field.Type.bytes()) - .mode(Field.Mode.NULLABLE) - .description("BytesDescription") + Field.newBuilder("BytesField", Field.Type.bytes()) + .setMode(Field.Mode.NULLABLE) + .setDescription("BytesDescription") .build(); private static final Field RECORD_FIELD_SCHEMA = - Field.builder("RecordField", Field.Type.record(TIMESTAMP_FIELD_SCHEMA, + Field.newBuilder("RecordField", Field.Type.record(TIMESTAMP_FIELD_SCHEMA, STRING_FIELD_SCHEMA, INTEGER_FIELD_SCHEMA, BOOLEAN_FIELD_SCHEMA, BYTES_FIELD_SCHEMA)) - .mode(Field.Mode.REQUIRED) - .description("RecordDescription") + .setMode(Field.Mode.REQUIRED) + .setDescription("RecordDescription") .build(); private static final Schema TABLE_SCHEMA = Schema.of(TIMESTAMP_FIELD_SCHEMA, STRING_FIELD_SCHEMA, INTEGER_FIELD_SCHEMA, BOOLEAN_FIELD_SCHEMA, BYTES_FIELD_SCHEMA, RECORD_FIELD_SCHEMA); private static final Schema SIMPLE_SCHEMA = Schema.of(STRING_FIELD_SCHEMA); - private static final Schema QUERY_RESULT_SCHEMA = Schema.builder() - .addField(Field.builder("TimestampField", Field.Type.timestamp()) - .mode(Field.Mode.NULLABLE) + private static final Schema QUERY_RESULT_SCHEMA = Schema.newBuilder() + .addField(Field.newBuilder("TimestampField", Field.Type.timestamp()) + .setMode(Field.Mode.NULLABLE) .build()) - .addField(Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) + .addField(Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) .build()) - .addField(Field.builder("BooleanField", Field.Type.bool()) - .mode(Field.Mode.NULLABLE) + .addField(Field.newBuilder("BooleanField", Field.Type.bool()) + .setMode(Field.Mode.NULLABLE) .build()) .build(); private static final String LOAD_FILE = "load.csv"; @@ -193,7 +193,7 @@ public class ITBigQueryTest { public static void beforeClass() throws InterruptedException, TimeoutException { RemoteBigQueryHelper bigqueryHelper = RemoteBigQueryHelper.create(); RemoteStorageHelper storageHelper = RemoteStorageHelper.create(); - bigquery = bigqueryHelper.options().service(); + bigquery = bigqueryHelper.getOptions().service(); storage = storageHelper.getOptions().service(); storage.create(BucketInfo.of(BUCKET)); storage.create(BlobInfo.newBuilder(BUCKET, LOAD_FILE).setContentType("text/plain").build(), @@ -202,16 +202,16 @@ public static void beforeClass() throws InterruptedException, TimeoutException { .setContentType("application/json") .build(), JSON_CONTENT.getBytes(StandardCharsets.UTF_8)); - DatasetInfo info = DatasetInfo.builder(DATASET).description(DESCRIPTION).build(); + DatasetInfo info = DatasetInfo.newBuilder(DATASET).setDescription(DESCRIPTION).build(); bigquery.create(info); - LoadJobConfiguration configuration = LoadJobConfiguration.builder( + LoadJobConfiguration configuration = LoadJobConfiguration.newBuilder( TABLE_ID, "gs://" + BUCKET + "/" + JSON_LOAD_FILE, FormatOptions.json()) - .createDisposition(JobInfo.CreateDisposition.CREATE_IF_NEEDED) - .schema(TABLE_SCHEMA) + .setCreateDisposition(JobInfo.CreateDisposition.CREATE_IF_NEEDED) + .setSchema(TABLE_SCHEMA) .build(); Job job = bigquery.create(JobInfo.of(configuration)); job = job.waitFor(); - assertNull(job.status().error()); + assertNull(job.getStatus().getError()); } @AfterClass @@ -233,7 +233,7 @@ public void testListDatasets() { Iterator iterator = datasets.iterateAll(); Set datasetNames = new HashSet<>(); while (iterator.hasNext()) { - datasetNames.add(iterator.next().datasetId().dataset()); + datasetNames.add(iterator.next().getDatasetId().getDataset()); } for (String type : PUBLIC_DATASETS) { assertTrue(datasetNames.contains(type)); @@ -243,71 +243,71 @@ public void testListDatasets() { @Test public void testGetDataset() { Dataset dataset = bigquery.getDataset(DATASET); - assertEquals(bigquery.options().projectId(), dataset.datasetId().project()); - assertEquals(DATASET, dataset.datasetId().dataset()); - assertEquals(DESCRIPTION, dataset.description()); - assertNotNull(dataset.acl()); - assertNotNull(dataset.etag()); - assertNotNull(dataset.generatedId()); - assertNotNull(dataset.lastModified()); - assertNotNull(dataset.selfLink()); + assertEquals(bigquery.options().projectId(), dataset.getDatasetId().getProject()); + assertEquals(DATASET, dataset.getDatasetId().getDataset()); + assertEquals(DESCRIPTION, dataset.getDescription()); + assertNotNull(dataset.getAcl()); + assertNotNull(dataset.getEtag()); + assertNotNull(dataset.getGeneratedId()); + assertNotNull(dataset.getLastModified()); + assertNotNull(dataset.getSelfLink()); } @Test public void testGetDatasetWithSelectedFields() { Dataset dataset = bigquery.getDataset(DATASET, DatasetOption.fields(DatasetField.CREATION_TIME)); - assertEquals(bigquery.options().projectId(), dataset.datasetId().project()); - assertEquals(DATASET, dataset.datasetId().dataset()); - assertNotNull(dataset.creationTime()); - assertNull(dataset.description()); - assertNull(dataset.defaultTableLifetime()); - assertNull(dataset.acl()); - assertNull(dataset.etag()); - assertNull(dataset.friendlyName()); - assertNull(dataset.generatedId()); - assertNull(dataset.lastModified()); - assertNull(dataset.location()); - assertNull(dataset.selfLink()); + assertEquals(bigquery.options().projectId(), dataset.getDatasetId().getProject()); + assertEquals(DATASET, dataset.getDatasetId().getDataset()); + assertNotNull(dataset.getCreationTime()); + assertNull(dataset.getDescription()); + assertNull(dataset.getDefaultTableLifetime()); + assertNull(dataset.getAcl()); + assertNull(dataset.getEtag()); + assertNull(dataset.getFriendlyName()); + assertNull(dataset.getGeneratedId()); + assertNull(dataset.getLastModified()); + assertNull(dataset.getLocation()); + assertNull(dataset.getSelfLink()); } @Test public void testUpdateDataset() { - Dataset dataset = bigquery.create(DatasetInfo.builder(OTHER_DATASET) - .description("Some Description") + Dataset dataset = bigquery.create(DatasetInfo.newBuilder(OTHER_DATASET) + .setDescription("Some Description") .build()); assertNotNull(dataset); - assertEquals(bigquery.options().projectId(), dataset.datasetId().project()); - assertEquals(OTHER_DATASET, dataset.datasetId().dataset()); - assertEquals("Some Description", dataset.description()); + assertEquals(bigquery.options().projectId(), dataset.getDatasetId().getProject()); + assertEquals(OTHER_DATASET, dataset.getDatasetId().getDataset()); + assertEquals("Some Description", dataset.getDescription()); Dataset updatedDataset = - bigquery.update(dataset.toBuilder().description("Updated Description").build()); - assertEquals("Updated Description", updatedDataset.description()); + bigquery.update(dataset.toBuilder().setDescription("Updated Description").build()); + assertEquals("Updated Description", updatedDataset.getDescription()); assertTrue(dataset.delete()); } @Test public void testUpdateDatasetWithSelectedFields() { - Dataset dataset = bigquery.create(DatasetInfo.builder(OTHER_DATASET) - .description("Some Description") + Dataset dataset = bigquery.create(DatasetInfo.newBuilder(OTHER_DATASET) + .setDescription("Some Description") .build()); assertNotNull(dataset); - assertEquals(bigquery.options().projectId(), dataset.datasetId().project()); - assertEquals(OTHER_DATASET, dataset.datasetId().dataset()); - assertEquals("Some Description", dataset.description()); + assertEquals(bigquery.options().projectId(), dataset.getDatasetId().getProject()); + assertEquals(OTHER_DATASET, dataset.getDatasetId().getDataset()); + assertEquals("Some Description", dataset.getDescription()); Dataset updatedDataset = - bigquery.update(dataset.toBuilder().description("Updated Description").build(), + bigquery.update(dataset.toBuilder().setDescription("Updated Description").build(), DatasetOption.fields(DatasetField.DESCRIPTION)); - assertEquals("Updated Description", updatedDataset.description()); - assertNull(updatedDataset.creationTime()); - assertNull(updatedDataset.defaultTableLifetime()); - assertNull(updatedDataset.acl()); - assertNull(updatedDataset.etag()); - assertNull(updatedDataset.friendlyName()); - assertNull(updatedDataset.generatedId()); - assertNull(updatedDataset.lastModified()); - assertNull(updatedDataset.location()); - assertNull(updatedDataset.selfLink()); + assertEquals("Updated Description", updatedDataset.getDescription()); + assertNull(updatedDataset.getCreationTime()); + assertNull(updatedDataset.getDefaultTableLifetime()); + assertNull(updatedDataset.getAcl()); + assertNull(updatedDataset.getEtag()); + assertNull(updatedDataset.getFriendlyName()); + assertNull(updatedDataset.getGeneratedId()); + assertNull(updatedDataset.getLastModified()); + assertNull(updatedDataset.getLocation()); + assertNull(updatedDataset.getSelfLink()); assertTrue(dataset.delete()); } @@ -321,26 +321,26 @@ public void testCreateAndGetTable() { String tableName = "test_create_and_get_table"; TableId tableId = TableId.of(DATASET, tableName); TimePartitioning partitioning = TimePartitioning.of(Type.DAY); - StandardTableDefinition tableDefinition = StandardTableDefinition.builder() - .schema(TABLE_SCHEMA) - .timePartitioning(partitioning) + StandardTableDefinition tableDefinition = StandardTableDefinition.newBuilder() + .setSchema(TABLE_SCHEMA) + .setTimePartitioning(partitioning) .build(); Table createdTable = bigquery.create(TableInfo.of(tableId, tableDefinition)); assertNotNull(createdTable); - assertEquals(DATASET, createdTable.tableId().dataset()); - assertEquals(tableName, createdTable.tableId().table()); + assertEquals(DATASET, createdTable.getTableId().getDataset()); + assertEquals(tableName, createdTable.getTableId().getTable()); Table remoteTable = bigquery.getTable(DATASET, tableName); assertNotNull(remoteTable); - assertTrue(remoteTable.definition() instanceof StandardTableDefinition); - assertEquals(createdTable.tableId(), remoteTable.tableId()); - assertEquals(TableDefinition.Type.TABLE, remoteTable.definition().type()); - assertEquals(TABLE_SCHEMA, remoteTable.definition().schema()); - assertNotNull(remoteTable.creationTime()); - assertNotNull(remoteTable.lastModifiedTime()); - assertNotNull(remoteTable.definition().numBytes()); - assertNotNull(remoteTable.definition().numRows()); + assertTrue(remoteTable.getDefinition() instanceof StandardTableDefinition); + assertEquals(createdTable.getTableId(), remoteTable.getTableId()); + assertEquals(TableDefinition.Type.TABLE, remoteTable.getDefinition().getType()); + assertEquals(TABLE_SCHEMA, remoteTable.getDefinition().getSchema()); + assertNotNull(remoteTable.getCreationTime()); + assertNotNull(remoteTable.getLastModifiedTime()); + assertNotNull(remoteTable.getDefinition().getNumBytes()); + assertNotNull(remoteTable.getDefinition().getNumRows()); assertEquals(partitioning, - remoteTable.definition().timePartitioning()); + remoteTable.getDefinition().getTimePartitioning()); assertTrue(remoteTable.delete()); } @@ -351,20 +351,20 @@ public void testCreateAndGetTableWithSelectedField() { StandardTableDefinition tableDefinition = StandardTableDefinition.of(TABLE_SCHEMA); Table createdTable = bigquery.create(TableInfo.of(tableId, tableDefinition)); assertNotNull(createdTable); - assertEquals(DATASET, createdTable.tableId().dataset()); - assertEquals(tableName, createdTable.tableId().table()); + assertEquals(DATASET, createdTable.getTableId().getDataset()); + assertEquals(tableName, createdTable.getTableId().getTable()); Table remoteTable = bigquery.getTable(DATASET, tableName, TableOption.fields(TableField.CREATION_TIME)); assertNotNull(remoteTable); - assertTrue(remoteTable.definition() instanceof StandardTableDefinition); - assertEquals(createdTable.tableId(), remoteTable.tableId()); - assertEquals(TableDefinition.Type.TABLE, remoteTable.definition().type()); - assertNotNull(remoteTable.creationTime()); - assertNull(remoteTable.definition().schema()); - assertNull(remoteTable.lastModifiedTime()); - assertNull(remoteTable.definition().numBytes()); - assertNull(remoteTable.definition().numRows()); - assertNull(remoteTable.definition().timePartitioning()); + assertTrue(remoteTable.getDefinition() instanceof StandardTableDefinition); + assertEquals(createdTable.getTableId(), remoteTable.getTableId()); + assertEquals(TableDefinition.Type.TABLE, remoteTable.getDefinition().getType()); + assertNotNull(remoteTable.getCreationTime()); + assertNull(remoteTable.getDefinition().getSchema()); + assertNull(remoteTable.getLastModifiedTime()); + assertNull(remoteTable.getDefinition().getNumBytes()); + assertNull(remoteTable.getDefinition().getNumRows()); + assertNull(remoteTable.getDefinition().getTimePartitioning()); assertTrue(remoteTable.delete()); } @@ -377,40 +377,40 @@ public void testCreateExternalTable() throws InterruptedException { TableInfo tableInfo = TableInfo.of(tableId, externalTableDefinition); Table createdTable = bigquery.create(tableInfo); assertNotNull(createdTable); - assertEquals(DATASET, createdTable.tableId().dataset()); - assertEquals(tableName, createdTable.tableId().table()); + assertEquals(DATASET, createdTable.getTableId().getDataset()); + assertEquals(tableName, createdTable.getTableId().getTable()); Table remoteTable = bigquery.getTable(DATASET, tableName); assertNotNull(remoteTable); - assertTrue(remoteTable.definition() instanceof ExternalTableDefinition); - assertEquals(createdTable.tableId(), remoteTable.tableId()); - assertEquals(TABLE_SCHEMA, remoteTable.definition().schema()); - QueryRequest request = QueryRequest.builder( + assertTrue(remoteTable.getDefinition() instanceof ExternalTableDefinition); + assertEquals(createdTable.getTableId(), remoteTable.getTableId()); + assertEquals(TABLE_SCHEMA, remoteTable.getDefinition().getSchema()); + QueryRequest request = QueryRequest.newBuilder( "SELECT TimestampField, StringField, IntegerField, BooleanField FROM " + DATASET + "." + tableName) - .defaultDataset(DatasetId.of(DATASET)) - .maxWaitTime(60000L) - .pageSize(1000L) + .setDefaultDataset(DatasetId.of(DATASET)) + .setMaxWaitTime(60000L) + .setPageSize(1000L) .build(); QueryResponse response = bigquery.query(request); while (!response.jobCompleted()) { - response = bigquery.getQueryResults(response.jobId()); + response = bigquery.getQueryResults(response.getJobId()); Thread.sleep(1000); } long integerValue = 0; int rowCount = 0; - for (List row : response.result().values()) { + for (List row : response.getResult().values()) { FieldValue timestampCell = row.get(0); FieldValue stringCell = row.get(1); FieldValue integerCell = row.get(2); FieldValue booleanCell = row.get(3); - assertEquals(FieldValue.Attribute.PRIMITIVE, timestampCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, stringCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, integerCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, booleanCell.attribute()); - assertEquals(1408452095220000L, timestampCell.timestampValue()); - assertEquals("stringValue", stringCell.stringValue()); - assertEquals(integerValue, integerCell.longValue()); - assertEquals(false, booleanCell.booleanValue()); + assertEquals(FieldValue.Attribute.PRIMITIVE, timestampCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, stringCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, integerCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, booleanCell.getAttribute()); + assertEquals(1408452095220000L, timestampCell.getTimestampValue()); + assertEquals("stringValue", stringCell.getStringValue()); + assertEquals(integerValue, integerCell.getLongValue()); + assertEquals(false, booleanCell.getBooleanValue()); integerValue = ~integerValue & 0x1; rowCount++; } @@ -424,52 +424,52 @@ public void testCreateViewTable() throws InterruptedException { TableId tableId = TableId.of(DATASET, tableName); ViewDefinition viewDefinition = ViewDefinition.of("SELECT TimestampField, StringField, BooleanField FROM " + DATASET + "." - + TABLE_ID.table()); + + TABLE_ID.getTable()); TableInfo tableInfo = TableInfo.of(tableId, viewDefinition); Table createdTable = bigquery.create(tableInfo); assertNotNull(createdTable); - assertEquals(DATASET, createdTable.tableId().dataset()); - assertEquals(tableName, createdTable.tableId().table()); + assertEquals(DATASET, createdTable.getTableId().getDataset()); + assertEquals(tableName, createdTable.getTableId().getTable()); Table remoteTable = bigquery.getTable(DATASET, tableName); assertNotNull(remoteTable); - assertEquals(createdTable.tableId(), remoteTable.tableId()); - assertTrue(remoteTable.definition() instanceof ViewDefinition); - Schema expectedSchema = Schema.builder() + assertEquals(createdTable.getTableId(), remoteTable.getTableId()); + assertTrue(remoteTable.getDefinition() instanceof ViewDefinition); + Schema expectedSchema = Schema.newBuilder() .addField( - Field.builder("TimestampField", Field.Type.timestamp()) - .mode(Field.Mode.NULLABLE) + Field.newBuilder("TimestampField", Field.Type.timestamp()) + .setMode(Field.Mode.NULLABLE) .build()) .addField( - Field.builder("StringField", Field.Type.string()) - .mode(Field.Mode.NULLABLE) + Field.newBuilder("StringField", Field.Type.string()) + .setMode(Field.Mode.NULLABLE) .build()) .addField( - Field.builder("BooleanField", Field.Type.bool()) - .mode(Field.Mode.NULLABLE) + Field.newBuilder("BooleanField", Field.Type.bool()) + .setMode(Field.Mode.NULLABLE) .build()) .build(); - assertEquals(expectedSchema, remoteTable.definition().schema()); - QueryRequest request = QueryRequest.builder("SELECT * FROM " + tableName) - .defaultDataset(DatasetId.of(DATASET)) - .maxWaitTime(60000L) - .pageSize(1000L) + assertEquals(expectedSchema, remoteTable.getDefinition().getSchema()); + QueryRequest request = QueryRequest.newBuilder("SELECT * FROM " + tableName) + .setDefaultDataset(DatasetId.of(DATASET)) + .setMaxWaitTime(60000L) + .setPageSize(1000L) .build(); QueryResponse response = bigquery.query(request); while (!response.jobCompleted()) { - response = bigquery.getQueryResults(response.jobId()); + response = bigquery.getQueryResults(response.getJobId()); Thread.sleep(1000); } int rowCount = 0; - for (List row : response.result().values()) { + for (List row : response.getResult().values()) { FieldValue timestampCell = row.get(0); FieldValue stringCell = row.get(1); FieldValue booleanCell = row.get(2); - assertEquals(FieldValue.Attribute.PRIMITIVE, timestampCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, stringCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, booleanCell.attribute()); - assertEquals(1408452095220000L, timestampCell.timestampValue()); - assertEquals("stringValue", stringCell.stringValue()); - assertEquals(false, booleanCell.booleanValue()); + assertEquals(FieldValue.Attribute.PRIMITIVE, timestampCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, stringCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, booleanCell.getAttribute()); + assertEquals(1408452095220000L, timestampCell.getTimestampValue()); + assertEquals("stringValue", stringCell.getStringValue()); + assertEquals(false, booleanCell.getBooleanValue()); rowCount++; } assertEquals(2, rowCount); @@ -487,7 +487,7 @@ public void testListTables() { boolean found = false; Iterator
tableIterator = tables.values().iterator(); while (tableIterator.hasNext() && !found) { - if (tableIterator.next().tableId().equals(createdTable.tableId())) { + if (tableIterator.next().getTableId().equals(createdTable.getTableId())) { found = true; } } @@ -503,11 +503,11 @@ public void testUpdateTable() { Table createdTable = bigquery.create(tableInfo); assertNotNull(createdTable); Table updatedTable = - bigquery.update(tableInfo.toBuilder().description("newDescription").build()); - assertEquals(DATASET, updatedTable.tableId().dataset()); - assertEquals(tableName, updatedTable.tableId().table()); - assertEquals(TABLE_SCHEMA, updatedTable.definition().schema()); - assertEquals("newDescription", updatedTable.description()); + bigquery.update(tableInfo.toBuilder().setDescription("newDescription").build()); + assertEquals(DATASET, updatedTable.getTableId().getDataset()); + assertEquals(tableName, updatedTable.getTableId().getTable()); + assertEquals(TABLE_SCHEMA, updatedTable.getDefinition().getSchema()); + assertEquals("newDescription", updatedTable.getDescription()); assertTrue(updatedTable.delete()); } @@ -518,16 +518,16 @@ public void testUpdateTableWithSelectedFields() { TableInfo tableInfo = TableInfo.of(TableId.of(DATASET, tableName), tableDefinition); Table createdTable = bigquery.create(tableInfo); assertNotNull(createdTable); - Table updatedTable = bigquery.update(tableInfo.toBuilder().description("newDescr").build(), + Table updatedTable = bigquery.update(tableInfo.toBuilder().setDescription("newDescr").build(), TableOption.fields(TableField.DESCRIPTION)); - assertTrue(updatedTable.definition() instanceof StandardTableDefinition); - assertEquals(DATASET, updatedTable.tableId().dataset()); - assertEquals(tableName, updatedTable.tableId().table()); - assertEquals("newDescr", updatedTable.description()); - assertNull(updatedTable.definition().schema()); - assertNull(updatedTable.lastModifiedTime()); - assertNull(updatedTable.definition().numBytes()); - assertNull(updatedTable.definition().numRows()); + assertTrue(updatedTable.getDefinition() instanceof StandardTableDefinition); + assertEquals(DATASET, updatedTable.getTableId().getDataset()); + assertEquals(tableName, updatedTable.getTableId().getTable()); + assertEquals("newDescr", updatedTable.getDescription()); + assertNull(updatedTable.getDefinition().getSchema()); + assertNull(updatedTable.getLastModifiedTime()); + assertNull(updatedTable.getDefinition().getNumBytes()); + assertNull(updatedTable.getDefinition().getNumRows()); assertTrue(createdTable.delete()); } @@ -539,10 +539,10 @@ public void testUpdateNonExistingTable() { bigquery.update(tableInfo); fail("BigQueryException was expected"); } catch (BigQueryException e) { - BigQueryError error = e.error(); + BigQueryError error = e.getError(); assertNotNull(error); - assertEquals("notFound", error.reason()); - assertNotNull(error.message()); + assertEquals("notFound", error.getReason()); + assertNotNull(error.getMessage()); } } @@ -579,13 +579,13 @@ public void testInsertAll() throws IOException { "IntegerField", ImmutableList.of(1, 0), "BooleanField", true, "BytesField", BYTES_BASE64)); - InsertAllRequest request = InsertAllRequest.builder(tableInfo.tableId()) + InsertAllRequest request = InsertAllRequest.newBuilder(tableInfo.getTableId()) .addRow(builder1.build()) .addRow(builder2.build()) .build(); InsertAllResponse response = bigquery.insertAll(request); assertFalse(response.hasErrors()); - assertEquals(0, response.insertErrors().size()); + assertEquals(0, response.getInsertErrors().size()); assertTrue(bigquery.delete(TableId.of(DATASET, tableName))); } @@ -617,14 +617,14 @@ public void testInsertAllWithSuffix() throws InterruptedException { "IntegerField", ImmutableList.of(1, 0), "BooleanField", true, "BytesField", BYTES_BASE64)); - InsertAllRequest request = InsertAllRequest.builder(tableInfo.tableId()) + InsertAllRequest request = InsertAllRequest.newBuilder(tableInfo.getTableId()) .addRow(builder1.build()) .addRow(builder2.build()) - .templateSuffix("_suffix") + .setTemplateSuffix("_suffix") .build(); InsertAllResponse response = bigquery.insertAll(request); assertFalse(response.hasErrors()); - assertEquals(0, response.insertErrors().size()); + assertEquals(0, response.getInsertErrors().size()); String newTableName = tableName + "_suffix"; Table suffixTable = bigquery.getTable(DATASET, newTableName, TableOption.fields()); // wait until the new table is created. If the table is never created the test will time-out @@ -670,17 +670,17 @@ public void testInsertAllWithErrors() { builder3.put("IntegerField", ImmutableList.of(0, 1)); builder3.put("BooleanField", false); builder3.put("BytesField", BYTES_BASE64); - InsertAllRequest request = InsertAllRequest.builder(tableInfo.tableId()) + InsertAllRequest request = InsertAllRequest.newBuilder(tableInfo.getTableId()) .addRow(builder1.build()) .addRow(builder2.build()) .addRow(builder3.build()) - .skipInvalidRows(true) + .setSkipInvalidRows(true) .build(); InsertAllResponse response = bigquery.insertAll(request); assertTrue(response.hasErrors()); - assertEquals(2, response.insertErrors().size()); - assertNotNull(response.errorsFor(1L)); - assertNotNull(response.errorsFor(2L)); + assertEquals(2, response.getInsertErrors().size()); + assertNotNull(response.getErrorsFor(1L)); + assertNotNull(response.getErrorsFor(2L)); assertTrue(bigquery.delete(TableId.of(DATASET, tableName))); } @@ -695,23 +695,23 @@ public void testListAllTableData() { FieldValue booleanCell = row.get(3); FieldValue bytesCell = row.get(4); FieldValue recordCell = row.get(5); - assertEquals(FieldValue.Attribute.PRIMITIVE, timestampCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, stringCell.attribute()); - assertEquals(FieldValue.Attribute.REPEATED, integerCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, booleanCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, bytesCell.attribute()); - assertEquals(FieldValue.Attribute.RECORD, recordCell.attribute()); - assertEquals(1408452095220000L, timestampCell.timestampValue()); - assertEquals("stringValue", stringCell.stringValue()); - assertEquals(0, integerCell.repeatedValue().get(0).longValue()); - assertEquals(1, integerCell.repeatedValue().get(1).longValue()); - assertEquals(false, booleanCell.booleanValue()); - assertArrayEquals(BYTES, bytesCell.bytesValue()); - assertEquals(-14182916000000L, recordCell.recordValue().get(0).timestampValue()); - assertTrue(recordCell.recordValue().get(1).isNull()); - assertEquals(1, recordCell.recordValue().get(2).repeatedValue().get(0).longValue()); - assertEquals(0, recordCell.recordValue().get(2).repeatedValue().get(1).longValue()); - assertEquals(true, recordCell.recordValue().get(3).booleanValue()); + assertEquals(FieldValue.Attribute.PRIMITIVE, timestampCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, stringCell.getAttribute()); + assertEquals(FieldValue.Attribute.REPEATED, integerCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, booleanCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, bytesCell.getAttribute()); + assertEquals(FieldValue.Attribute.RECORD, recordCell.getAttribute()); + assertEquals(1408452095220000L, timestampCell.getTimestampValue()); + assertEquals("stringValue", stringCell.getStringValue()); + assertEquals(0, integerCell.getRepeatedValue().get(0).getLongValue()); + assertEquals(1, integerCell.getRepeatedValue().get(1).getLongValue()); + assertEquals(false, booleanCell.getBooleanValue()); + assertArrayEquals(BYTES, bytesCell.getBytesValue()); + assertEquals(-14182916000000L, recordCell.getRecordValue().get(0).getTimestampValue()); + assertTrue(recordCell.getRecordValue().get(1).isNull()); + assertEquals(1, recordCell.getRecordValue().get(2).getRepeatedValue().get(0).getLongValue()); + assertEquals(0, recordCell.getRecordValue().get(2).getRepeatedValue().get(1).getLongValue()); + assertEquals(true, recordCell.getRecordValue().get(3).getBooleanValue()); rowCount++; } assertEquals(2, rowCount); @@ -721,47 +721,47 @@ public void testListAllTableData() { public void testQuery() throws InterruptedException { String query = new StringBuilder() .append("SELECT TimestampField, StringField, BooleanField FROM ") - .append(TABLE_ID.table()) + .append(TABLE_ID.getTable()) .toString(); - QueryRequest request = QueryRequest.builder(query) - .defaultDataset(DatasetId.of(DATASET)) - .maxWaitTime(60000L) - .pageSize(1000L) + QueryRequest request = QueryRequest.newBuilder(query) + .setDefaultDataset(DatasetId.of(DATASET)) + .setMaxWaitTime(60000L) + .setPageSize(1000L) .build(); QueryResponse response = bigquery.query(request); while (!response.jobCompleted()) { Thread.sleep(1000); - response = bigquery.getQueryResults(response.jobId()); + response = bigquery.getQueryResults(response.getJobId()); } - assertEquals(QUERY_RESULT_SCHEMA, response.result().schema()); + assertEquals(QUERY_RESULT_SCHEMA, response.getResult().getSchema()); int rowCount = 0; - for (List row : response.result().values()) { + for (List row : response.getResult().values()) { FieldValue timestampCell = row.get(0); FieldValue stringCell = row.get(1); FieldValue booleanCell = row.get(2); - assertEquals(FieldValue.Attribute.PRIMITIVE, timestampCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, stringCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, booleanCell.attribute()); - assertEquals(1408452095220000L, timestampCell.timestampValue()); - assertEquals("stringValue", stringCell.stringValue()); - assertEquals(false, booleanCell.booleanValue()); + assertEquals(FieldValue.Attribute.PRIMITIVE, timestampCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, stringCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, booleanCell.getAttribute()); + assertEquals(1408452095220000L, timestampCell.getTimestampValue()); + assertEquals("stringValue", stringCell.getStringValue()); + assertEquals(false, booleanCell.getBooleanValue()); rowCount++; } assertEquals(2, rowCount); - Job queryJob = bigquery.getJob(response.jobId()); - JobStatistics.QueryStatistics statistics = queryJob.statistics(); - assertNotNull(statistics.queryPlan()); + Job queryJob = bigquery.getJob(response.getJobId()); + JobStatistics.QueryStatistics statistics = queryJob.getStatistics(); + assertNotNull(statistics.getQueryPlan()); } @Test public void testListJobs() { Page jobs = bigquery.listJobs(); for (Job job : jobs.values()) { - assertNotNull(job.jobId()); - assertNotNull(job.statistics()); - assertNotNull(job.status()); - assertNotNull(job.userEmail()); - assertNotNull(job.generatedId()); + assertNotNull(job.getJobId()); + assertNotNull(job.getStatistics()); + assertNotNull(job.getStatus()); + assertNotNull(job.getUserEmail()); + assertNotNull(job.getGeneratedId()); } } @@ -769,11 +769,11 @@ public void testListJobs() { public void testListJobsWithSelectedFields() { Page jobs = bigquery.listJobs(JobListOption.fields(JobField.USER_EMAIL)); for (Job job : jobs.values()) { - assertNotNull(job.jobId()); - assertNotNull(job.status()); - assertNotNull(job.userEmail()); - assertNull(job.statistics()); - assertNull(job.generatedId()); + assertNotNull(job.getJobId()); + assertNotNull(job.getStatus()); + assertNotNull(job.getUserEmail()); + assertNull(job.getStatistics()); + assertNull(job.getGeneratedId()); } } @@ -786,25 +786,28 @@ public void testCreateAndGetJob() { TableInfo tableInfo = TableInfo.of(sourceTable, tableDefinition); Table createdTable = bigquery.create(tableInfo); assertNotNull(createdTable); - assertEquals(DATASET, createdTable.tableId().dataset()); - assertEquals(sourceTableName, createdTable.tableId().table()); + assertEquals(DATASET, createdTable.getTableId().getDataset()); + assertEquals(sourceTableName, createdTable.getTableId().getTable()); TableId destinationTable = TableId.of(DATASET, destinationTableName); CopyJobConfiguration copyJobConfiguration = CopyJobConfiguration.of(destinationTable, sourceTable); Job createdJob = bigquery.create(JobInfo.of(copyJobConfiguration)); - Job remoteJob = bigquery.getJob(createdJob.jobId()); - assertEquals(createdJob.jobId(), remoteJob.jobId()); - CopyJobConfiguration createdConfiguration = createdJob.configuration(); - CopyJobConfiguration remoteConfiguration = remoteJob.configuration(); - assertEquals(createdConfiguration.sourceTables(), remoteConfiguration.sourceTables()); - assertEquals(createdConfiguration.destinationTable(), remoteConfiguration.destinationTable()); - assertEquals(createdConfiguration.createDisposition(), remoteConfiguration.createDisposition()); - assertEquals(createdConfiguration.writeDisposition(), remoteConfiguration.writeDisposition()); - assertNotNull(remoteJob.etag()); - assertNotNull(remoteJob.statistics()); - assertNotNull(remoteJob.status()); - assertEquals(createdJob.selfLink(), remoteJob.selfLink()); - assertEquals(createdJob.userEmail(), remoteJob.userEmail()); + Job remoteJob = bigquery.getJob(createdJob.getJobId()); + assertEquals(createdJob.getJobId(), remoteJob.getJobId()); + CopyJobConfiguration createdConfiguration = createdJob.getConfiguration(); + CopyJobConfiguration remoteConfiguration = remoteJob.getConfiguration(); + assertEquals(createdConfiguration.getSourceTables(), remoteConfiguration.getSourceTables()); + assertEquals(createdConfiguration.getDestinationTable(), + remoteConfiguration.getDestinationTable()); + assertEquals(createdConfiguration.getCreateDisposition(), + remoteConfiguration.getCreateDisposition()); + assertEquals(createdConfiguration.getWriteDisposition(), + remoteConfiguration.getWriteDisposition()); + assertNotNull(remoteJob.getEtag()); + assertNotNull(remoteJob.getStatistics()); + assertNotNull(remoteJob.getStatus()); + assertEquals(createdJob.getSelfLink(), remoteJob.getSelfLink()); + assertEquals(createdJob.getUserEmail(), remoteJob.getUserEmail()); assertTrue(createdTable.delete()); assertTrue(bigquery.delete(DATASET, destinationTableName)); } @@ -818,32 +821,35 @@ public void testCreateAndGetJobWithSelectedFields() { TableInfo tableInfo = TableInfo.of(sourceTable, tableDefinition); Table createdTable = bigquery.create(tableInfo); assertNotNull(createdTable); - assertEquals(DATASET, createdTable.tableId().dataset()); - assertEquals(sourceTableName, createdTable.tableId().table()); + assertEquals(DATASET, createdTable.getTableId().getDataset()); + assertEquals(sourceTableName, createdTable.getTableId().getTable()); TableId destinationTable = TableId.of(DATASET, destinationTableName); CopyJobConfiguration configuration = CopyJobConfiguration.of(destinationTable, sourceTable); Job createdJob = bigquery.create(JobInfo.of(configuration), JobOption.fields(JobField.ETAG)); - CopyJobConfiguration createdConfiguration = createdJob.configuration(); - assertNotNull(createdJob.jobId()); - assertNotNull(createdConfiguration.sourceTables()); - assertNotNull(createdConfiguration.destinationTable()); - assertNotNull(createdJob.etag()); - assertNull(createdJob.statistics()); - assertNull(createdJob.status()); - assertNull(createdJob.selfLink()); - assertNull(createdJob.userEmail()); - Job remoteJob = bigquery.getJob(createdJob.jobId(), JobOption.fields(JobField.ETAG)); - CopyJobConfiguration remoteConfiguration = remoteJob.configuration(); - assertEquals(createdJob.jobId(), remoteJob.jobId()); - assertEquals(createdConfiguration.sourceTables(), remoteConfiguration.sourceTables()); - assertEquals(createdConfiguration.destinationTable(), remoteConfiguration.destinationTable()); - assertEquals(createdConfiguration.createDisposition(), remoteConfiguration.createDisposition()); - assertEquals(createdConfiguration.writeDisposition(), remoteConfiguration.writeDisposition()); - assertNotNull(remoteJob.etag()); - assertNull(remoteJob.statistics()); - assertNull(remoteJob.status()); - assertNull(remoteJob.selfLink()); - assertNull(remoteJob.userEmail()); + CopyJobConfiguration createdConfiguration = createdJob.getConfiguration(); + assertNotNull(createdJob.getJobId()); + assertNotNull(createdConfiguration.getSourceTables()); + assertNotNull(createdConfiguration.getDestinationTable()); + assertNotNull(createdJob.getEtag()); + assertNull(createdJob.getStatistics()); + assertNull(createdJob.getStatus()); + assertNull(createdJob.getSelfLink()); + assertNull(createdJob.getUserEmail()); + Job remoteJob = bigquery.getJob(createdJob.getJobId(), JobOption.fields(JobField.ETAG)); + CopyJobConfiguration remoteConfiguration = remoteJob.getConfiguration(); + assertEquals(createdJob.getJobId(), remoteJob.getJobId()); + assertEquals(createdConfiguration.getSourceTables(), remoteConfiguration.getSourceTables()); + assertEquals(createdConfiguration.getDestinationTable(), + remoteConfiguration.getDestinationTable()); + assertEquals(createdConfiguration.getCreateDisposition(), + remoteConfiguration.getCreateDisposition()); + assertEquals(createdConfiguration.getWriteDisposition(), + remoteConfiguration.getWriteDisposition()); + assertNotNull(remoteJob.getEtag()); + assertNull(remoteJob.getStatistics()); + assertNull(remoteJob.getStatus()); + assertNull(remoteJob.getSelfLink()); + assertNull(remoteJob.getUserEmail()); assertTrue(createdTable.delete()); assertTrue(bigquery.delete(DATASET, destinationTableName)); } @@ -857,18 +863,18 @@ public void testCopyJob() throws InterruptedException, TimeoutException { TableInfo tableInfo = TableInfo.of(sourceTable, tableDefinition); Table createdTable = bigquery.create(tableInfo); assertNotNull(createdTable); - assertEquals(DATASET, createdTable.tableId().dataset()); - assertEquals(sourceTableName, createdTable.tableId().table()); + assertEquals(DATASET, createdTable.getTableId().getDataset()); + assertEquals(sourceTableName, createdTable.getTableId().getTable()); TableId destinationTable = TableId.of(DATASET, destinationTableName); CopyJobConfiguration configuration = CopyJobConfiguration.of(destinationTable, sourceTable); Job remoteJob = bigquery.create(JobInfo.of(configuration)); remoteJob = remoteJob.waitFor(); - assertNull(remoteJob.status().error()); + assertNull(remoteJob.getStatus().getError()); Table remoteTable = bigquery.getTable(DATASET, destinationTableName); assertNotNull(remoteTable); - assertEquals(destinationTable.dataset(), remoteTable.tableId().dataset()); - assertEquals(destinationTableName, remoteTable.tableId().table()); - assertEquals(TABLE_SCHEMA, remoteTable.definition().schema()); + assertEquals(destinationTable.getDataset(), remoteTable.getTableId().getDataset()); + assertEquals(destinationTableName, remoteTable.getTableId().getTable()); + assertEquals(TABLE_SCHEMA, remoteTable.getDefinition().getSchema()); assertTrue(createdTable.delete()); assertTrue(remoteTable.delete()); } @@ -878,42 +884,42 @@ public void testQueryJob() throws InterruptedException, TimeoutException { String tableName = "test_query_job_table"; String query = new StringBuilder() .append("SELECT TimestampField, StringField, BooleanField FROM ") - .append(TABLE_ID.table()) + .append(TABLE_ID.getTable()) .toString(); TableId destinationTable = TableId.of(DATASET, tableName); - QueryJobConfiguration configuration = QueryJobConfiguration.builder(query) - .defaultDataset(DatasetId.of(DATASET)) - .destinationTable(destinationTable) + QueryJobConfiguration configuration = QueryJobConfiguration.newBuilder(query) + .setDefaultDataset(DatasetId.of(DATASET)) + .setDestinationTable(destinationTable) .build(); Job remoteJob = bigquery.create(JobInfo.of(configuration)); remoteJob = remoteJob.waitFor(); - assertNull(remoteJob.status().error()); + assertNull(remoteJob.getStatus().getError()); - QueryResponse response = bigquery.getQueryResults(remoteJob.jobId()); + QueryResponse response = bigquery.getQueryResults(remoteJob.getJobId()); while (!response.jobCompleted()) { Thread.sleep(1000); - response = bigquery.getQueryResults(response.jobId()); + response = bigquery.getQueryResults(response.getJobId()); } assertFalse(response.hasErrors()); - assertEquals(QUERY_RESULT_SCHEMA, response.result().schema()); + assertEquals(QUERY_RESULT_SCHEMA, response.getResult().getSchema()); int rowCount = 0; - for (List row : response.result().values()) { + for (List row : response.getResult().values()) { FieldValue timestampCell = row.get(0); FieldValue stringCell = row.get(1); FieldValue booleanCell = row.get(2); - assertEquals(FieldValue.Attribute.PRIMITIVE, timestampCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, stringCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, booleanCell.attribute()); - assertEquals(1408452095220000L, timestampCell.timestampValue()); - assertEquals("stringValue", stringCell.stringValue()); - assertEquals(false, booleanCell.booleanValue()); + assertEquals(FieldValue.Attribute.PRIMITIVE, timestampCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, stringCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, booleanCell.getAttribute()); + assertEquals(1408452095220000L, timestampCell.getTimestampValue()); + assertEquals("stringValue", stringCell.getStringValue()); + assertEquals(false, booleanCell.getBooleanValue()); rowCount++; } assertEquals(2, rowCount); assertTrue(bigquery.delete(DATASET, tableName)); - Job queryJob = bigquery.getJob(remoteJob.jobId()); - JobStatistics.QueryStatistics statistics = queryJob.statistics(); - assertNotNull(statistics.queryPlan()); + Job queryJob = bigquery.getJob(remoteJob.getJobId()); + JobStatistics.QueryStatistics statistics = queryJob.getStatistics(); + assertNotNull(statistics.getQueryPlan()); } @Test @@ -921,20 +927,20 @@ public void testExtractJob() throws InterruptedException, TimeoutException { String tableName = "test_export_job_table"; TableId destinationTable = TableId.of(DATASET, tableName); LoadJobConfiguration configuration = - LoadJobConfiguration.builder(destinationTable, "gs://" + BUCKET + "/" + LOAD_FILE) - .schema(SIMPLE_SCHEMA) + LoadJobConfiguration.newBuilder(destinationTable, "gs://" + BUCKET + "/" + LOAD_FILE) + .setSchema(SIMPLE_SCHEMA) .build(); Job remoteLoadJob = bigquery.create(JobInfo.of(configuration)); remoteLoadJob = remoteLoadJob.waitFor(); - assertNull(remoteLoadJob.status().error()); + assertNull(remoteLoadJob.getStatus().getError()); ExtractJobConfiguration extractConfiguration = - ExtractJobConfiguration.builder(destinationTable, "gs://" + BUCKET + "/" + EXTRACT_FILE) - .printHeader(false) + ExtractJobConfiguration.newBuilder(destinationTable, "gs://" + BUCKET + "/" + EXTRACT_FILE) + .setPrintHeader(false) .build(); Job remoteExtractJob = bigquery.create(JobInfo.of(extractConfiguration)); remoteExtractJob = remoteExtractJob.waitFor(); - assertNull(remoteExtractJob.status().error()); + assertNull(remoteExtractJob.getStatus().getError()); assertEquals(CSV_CONTENT, new String(storage.readAllBytes(BUCKET, EXTRACT_FILE), StandardCharsets.UTF_8)); assertTrue(bigquery.delete(DATASET, tableName)); @@ -943,16 +949,16 @@ public void testExtractJob() throws InterruptedException, TimeoutException { @Test public void testCancelJob() throws InterruptedException, TimeoutException { String destinationTableName = "test_cancel_query_job_table"; - String query = "SELECT TimestampField, StringField, BooleanField FROM " + TABLE_ID.table(); + String query = "SELECT TimestampField, StringField, BooleanField FROM " + TABLE_ID.getTable(); TableId destinationTable = TableId.of(DATASET, destinationTableName); - QueryJobConfiguration configuration = QueryJobConfiguration.builder(query) - .defaultDataset(DatasetId.of(DATASET)) - .destinationTable(destinationTable) + QueryJobConfiguration configuration = QueryJobConfiguration.newBuilder(query) + .setDefaultDataset(DatasetId.of(DATASET)) + .setDestinationTable(destinationTable) .build(); Job remoteJob = bigquery.create(JobInfo.of(configuration)); assertTrue(remoteJob.cancel()); remoteJob = remoteJob.waitFor(); - assertNull(remoteJob.status().error()); + assertNull(remoteJob.getStatus().getError()); } @Test @@ -964,10 +970,10 @@ public void testCancelNonExistingJob() { public void testInsertFromFile() throws InterruptedException { String destinationTableName = "test_insert_from_file_table"; TableId tableId = TableId.of(DATASET, destinationTableName); - WriteChannelConfiguration configuration = WriteChannelConfiguration.builder(tableId) - .formatOptions(FormatOptions.json()) - .createDisposition(JobInfo.CreateDisposition.CREATE_IF_NEEDED) - .schema(TABLE_SCHEMA) + WriteChannelConfiguration configuration = WriteChannelConfiguration.newBuilder(tableId) + .setFormatOptions(FormatOptions.json()) + .setCreateDisposition(JobInfo.CreateDisposition.CREATE_IF_NEEDED) + .setSchema(TABLE_SCHEMA) .build(); try (WriteChannel channel = bigquery.writer(configuration)) { channel.write(ByteBuffer.wrap(JSON_CONTENT.getBytes(StandardCharsets.UTF_8))); @@ -987,23 +993,23 @@ public void testInsertFromFile() throws InterruptedException { FieldValue booleanCell = row.get(3); FieldValue bytesCell = row.get(4); FieldValue recordCell = row.get(5); - assertEquals(FieldValue.Attribute.PRIMITIVE, timestampCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, stringCell.attribute()); - assertEquals(FieldValue.Attribute.REPEATED, integerCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, booleanCell.attribute()); - assertEquals(FieldValue.Attribute.PRIMITIVE, bytesCell.attribute()); - assertEquals(FieldValue.Attribute.RECORD, recordCell.attribute()); - assertEquals(1408452095220000L, timestampCell.timestampValue()); - assertEquals("stringValue", stringCell.stringValue()); - assertEquals(0, integerCell.repeatedValue().get(0).longValue()); - assertEquals(1, integerCell.repeatedValue().get(1).longValue()); - assertEquals(false, booleanCell.booleanValue()); - assertArrayEquals(BYTES, bytesCell.bytesValue()); - assertEquals(-14182916000000L, recordCell.recordValue().get(0).timestampValue()); - assertTrue(recordCell.recordValue().get(1).isNull()); - assertEquals(1, recordCell.recordValue().get(2).repeatedValue().get(0).longValue()); - assertEquals(0, recordCell.recordValue().get(2).repeatedValue().get(1).longValue()); - assertEquals(true, recordCell.recordValue().get(3).booleanValue()); + assertEquals(FieldValue.Attribute.PRIMITIVE, timestampCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, stringCell.getAttribute()); + assertEquals(FieldValue.Attribute.REPEATED, integerCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, booleanCell.getAttribute()); + assertEquals(FieldValue.Attribute.PRIMITIVE, bytesCell.getAttribute()); + assertEquals(FieldValue.Attribute.RECORD, recordCell.getAttribute()); + assertEquals(1408452095220000L, timestampCell.getTimestampValue()); + assertEquals("stringValue", stringCell.getStringValue()); + assertEquals(0, integerCell.getRepeatedValue().get(0).getLongValue()); + assertEquals(1, integerCell.getRepeatedValue().get(1).getLongValue()); + assertEquals(false, booleanCell.getBooleanValue()); + assertArrayEquals(BYTES, bytesCell.getBytesValue()); + assertEquals(-14182916000000L, recordCell.getRecordValue().get(0).getTimestampValue()); + assertTrue(recordCell.getRecordValue().get(1).isNull()); + assertEquals(1, recordCell.getRecordValue().get(2).getRepeatedValue().get(0).getLongValue()); + assertEquals(0, recordCell.getRecordValue().get(2).getRepeatedValue().get(1).getLongValue()); + assertEquals(true, recordCell.getRecordValue().get(3).getBooleanValue()); rowCount++; } assertEquals(2, rowCount); diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelperTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelperTest.java index 46badf7bb7be..1912c3d9283e 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelperTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelperTest.java @@ -80,7 +80,8 @@ public void testForceDelete() throws InterruptedException, ExecutionException { @Test public void testCreateFromStream() { RemoteBigQueryHelper helper = RemoteBigQueryHelper.create(PROJECT_ID, JSON_KEY_STREAM); - BigQueryOptions options = helper.options(); + BigQueryOptions options = helper.getOptions(); + assertEquals(options, helper.getOptions()); assertEquals(PROJECT_ID, options.projectId()); assertEquals(60000, options.connectTimeout()); assertEquals(60000, options.readTimeout()); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/BigQueryExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/BigQueryExample.java index 12b67446f702..7478fa7e20c9 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/BigQueryExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/BigQueryExample.java @@ -237,7 +237,7 @@ public void run(BigQuery bigquery, DatasetId datasetId) { private static class CreateDatasetAction extends DatasetAction { @Override public void run(BigQuery bigquery, DatasetId datasetId) { - bigquery.create(DatasetInfo.builder(datasetId).build()); + bigquery.create(DatasetInfo.newBuilder(datasetId).build()); System.out.println("Created dataset " + datasetId); } } @@ -396,7 +396,7 @@ void run(BigQuery bigquery, TableInfo table) throws Exception { } static Schema parseSchema(String[] args, int start, int end) { - Schema.Builder builder = Schema.builder(); + Schema.Builder builder = Schema.newBuilder(); for (int i = start; i < end; i++) { String[] fieldsArray = args[i].split(":"); if (fieldsArray.length != 2) { @@ -523,15 +523,15 @@ void run(BigQuery bigquery, JobInfo job) throws Exception { System.out.println("Creating job"); Job startedJob = bigquery.create(job); while (!startedJob.isDone()) { - System.out.println("Waiting for job " + startedJob.jobId().job() + " to complete"); + System.out.println("Waiting for job " + startedJob.getJobId().getJob() + " to complete"); Thread.sleep(1000L); } startedJob = startedJob.reload(); - if (startedJob.status().error() == null) { - System.out.println("Job " + startedJob.jobId().job() + " succeeded"); + if (startedJob.getStatus().getError() == null) { + System.out.println("Job " + startedJob.getJobId().getJob() + " succeeded"); } else { - System.out.println("Job " + startedJob.jobId().job() + " failed"); - System.out.println("Error: " + startedJob.status().error()); + System.out.println("Job " + startedJob.getJobId().getJob() + " failed"); + System.out.println("Error: " + startedJob.getStatus().getError()); } } } @@ -627,19 +627,19 @@ void run(BigQuery bigquery, QueryRequest queryRequest) throws Exception { System.out.println("Running query"); QueryResponse queryResponse = bigquery.query(queryRequest); while (!queryResponse.jobCompleted()) { - System.out.println("Waiting for query job " + queryResponse.jobId() + " to complete"); + System.out.println("Waiting for query job " + queryResponse.getJobId() + " to complete"); Thread.sleep(1000L); - queryResponse = bigquery.getQueryResults(queryResponse.jobId()); + queryResponse = bigquery.getQueryResults(queryResponse.getJobId()); } if (!queryResponse.hasErrors()) { System.out.println("Query succeeded. Results:"); - Iterator> iterator = queryResponse.result().iterateAll(); + Iterator> iterator = queryResponse.getResult().iterateAll(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } else { System.out.println("Query completed with errors. Errors:"); - for (BigQueryError err : queryResponse.executionErrors()) { + for (BigQueryError err : queryResponse.getExecutionErrors()) { System.out.println(err); } } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/BigQuerySnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/BigQuerySnippets.java index d15036aa9471..dce4ac19a8bc 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/BigQuerySnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/BigQuerySnippets.java @@ -85,7 +85,7 @@ public BigQuerySnippets(BigQuery bigquery) { public Dataset createDataset(String datasetName) { // [START createDataset] Dataset dataset = null; - DatasetInfo datasetInfo = DatasetInfo.builder(datasetName).build(); + DatasetInfo datasetInfo = DatasetInfo.newBuilder(datasetName).build(); try { // the dataset was created dataset = bigquery.create(datasetInfo); @@ -105,7 +105,7 @@ public Dataset createDataset(String datasetName) { public Dataset updateDataset(String datasetName, String newFriendlyName) { // [START updateDataset] Dataset oldDataset = bigquery.getDataset(datasetName); - DatasetInfo datasetInfo = oldDataset.toBuilder().friendlyName(newFriendlyName).build(); + DatasetInfo datasetInfo = oldDataset.toBuilder().setFriendlyName(newFriendlyName).build(); Dataset newDataset = bigquery.update(datasetInfo); // [END updateDataset] return newDataset; @@ -121,7 +121,7 @@ public Dataset updateDataset(String datasetName, String newFriendlyName) { public Table updateTable(String datasetName, String tableName, String newFriendlyName) { // [START updateTable] Table oldTable = bigquery.getTable(datasetName, tableName); - TableInfo tableInfo = oldTable.toBuilder().friendlyName(newFriendlyName).build(); + TableInfo tableInfo = oldTable.toBuilder().setFriendlyName(newFriendlyName).build(); Table newTable = bigquery.update(tableInfo); // [END updateTable] return newTable; @@ -337,7 +337,9 @@ public BaseWriteChannel writeToTable // [START writeToTable] TableId tableId = TableId.of(datasetName, tableName); WriteChannelConfiguration writeChannelConfiguration = - WriteChannelConfiguration.builder(tableId).formatOptions(FormatOptions.csv()).build(); + WriteChannelConfiguration.newBuilder(tableId) + .setFormatOptions(FormatOptions.csv()) + .build(); BaseWriteChannel writer = bigquery.writer(writeChannelConfiguration); // Write data to writer @@ -365,13 +367,13 @@ public InsertAllResponse insertAll(String datasetName, String tableName) { rowContent.put("booleanField", true); // Bytes are passed in base64 rowContent.put("bytesField", "DQ4KDQ=="); - InsertAllResponse response = bigquery.insertAll(InsertAllRequest.builder(tableId) + InsertAllResponse response = bigquery.insertAll(InsertAllRequest.newBuilder(tableId) .addRow("rowId", rowContent) // More rows can be added in the same RPC by invoking .addRow() on the builder .build()); if (response.hasErrors()) { // If any of the insertions failed, this lets you inspect the errors - for (Entry> entry : response.insertErrors().entrySet()) { + for (Entry> entry : response.getInsertErrors().entrySet()) { // inspect row error } } @@ -394,7 +396,7 @@ public Table createTable(String datasetName, String tableName, String fieldName) // Table schema definition Schema schema = Schema.of(field); TableDefinition tableDefinition = StandardTableDefinition.of(schema); - TableInfo tableInfo = TableInfo.builder(tableId, tableDefinition).build(); + TableInfo tableInfo = TableInfo.newBuilder(tableId, tableDefinition).build(); Table table = bigquery.create(tableInfo); // [END createTable] return table; @@ -553,12 +555,12 @@ public QueryResponse runQuery(String query) throws InterruptedException { // Wait for things to finish while (!response.jobCompleted()) { Thread.sleep(1000); - response = bigquery.getQueryResults(response.jobId()); + response = bigquery.getQueryResults(response.getJobId()); } if (response.hasErrors()) { // handle errors } - QueryResult result = response.result(); + QueryResult result = response.getResult(); Iterator> rowIterator = result.iterateAll(); while (rowIterator.hasNext()) { List row = rowIterator.next(); @@ -580,12 +582,12 @@ public QueryResponse queryResults(final String query) throws InterruptedExceptio // Wait for things to finish while (!response.jobCompleted()) { Thread.sleep(1000); - response = bigquery.getQueryResults(response.jobId()); + response = bigquery.getQueryResults(response.getJobId()); } if (response.hasErrors()) { // handle errors } - QueryResult result = response.result(); + QueryResult result = response.getResult(); Iterator> rowIterator = result.iterateAll(); while (rowIterator.hasNext()) { List row = rowIterator.next(); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/CreateTableAndLoadData.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/CreateTableAndLoadData.java index 6772d79a73ca..02f3f70fd51a 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/CreateTableAndLoadData.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/CreateTableAndLoadData.java @@ -55,7 +55,7 @@ public static void main(String... args) throws InterruptedException, TimeoutExce System.out.println("Loading data into table " + tableId); Job loadJob = table.load(FormatOptions.csv(), "gs://bucket/path"); loadJob = loadJob.waitFor(); - if (loadJob.status().error() != null) { + if (loadJob.getStatus().getError() != null) { System.out.println("Job completed with errors"); } else { System.out.println("Job succeeded"); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/DatasetSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/DatasetSnippets.java index a44c7f6f166c..a345a037ac7e 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/DatasetSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/DatasetSnippets.java @@ -83,7 +83,7 @@ public Dataset reloadDataset() { public Dataset updateDataset(String friendlyName) { // [START update] Builder builder = dataset.toBuilder(); - builder.friendlyName(friendlyName); + builder.setFriendlyName(friendlyName); Dataset updatedDataset = builder.build().update(); // [END update] return updatedDataset; @@ -142,9 +142,9 @@ public Table getTable(String tableName) { public Table createTable(String tableName, String fieldName) { // [START createTable] Schema schema = Schema.of(Field.of(fieldName, Type.string())); - StandardTableDefinition definition = StandardTableDefinition.builder() - .schema(schema) - .timePartitioning(TimePartitioning.of(TimePartitioning.Type.DAY)) + StandardTableDefinition definition = StandardTableDefinition.newBuilder() + .setSchema(schema) + .setTimePartitioning(TimePartitioning.of(TimePartitioning.Type.DAY)) .build(); Table table = dataset.create(tableName, definition); // [END createTable] diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/InsertDataAndQueryTable.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/InsertDataAndQueryTable.java index 6022545eb3bf..a57e42fb7417 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/InsertDataAndQueryTable.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/InsertDataAndQueryTable.java @@ -53,7 +53,7 @@ public static void main(String... args) throws InterruptedException { // Create a dataset String datasetId = "my_dataset_id"; - bigquery.create(DatasetInfo.builder(datasetId).build()); + bigquery.create(DatasetInfo.newBuilder(datasetId).build()); TableId tableId = TableId.of(datasetId, "my_table_id"); // Table field definition @@ -71,7 +71,7 @@ public static void main(String... args) throws InterruptedException { secondRow.put("StringField", "value2"); // Create an insert request InsertAllRequest insertRequest = - InsertAllRequest.builder(tableId).addRow(firstRow).addRow(secondRow).build(); + InsertAllRequest.newBuilder(tableId).addRow(firstRow).addRow(secondRow).build(); // Insert rows InsertAllResponse insertResponse = bigquery.insertAll(insertRequest); // Check if errors occurred @@ -81,18 +81,18 @@ public static void main(String... args) throws InterruptedException { // Create a query request QueryRequest queryRequest = - QueryRequest.builder("SELECT * FROM my_dataset_id.my_table_id") - .maxWaitTime(60000L) - .pageSize(1000L) + QueryRequest.newBuilder("SELECT * FROM my_dataset_id.my_table_id") + .setMaxWaitTime(60000L) + .setPageSize(1000L) .build(); // Request query to be executed and wait for results QueryResponse queryResponse = bigquery.query(queryRequest); while (!queryResponse.jobCompleted()) { Thread.sleep(1000L); - queryResponse = bigquery.getQueryResults(queryResponse.jobId()); + queryResponse = bigquery.getQueryResults(queryResponse.getJobId()); } // Read rows - Iterator> rowIterator = queryResponse.result().iterateAll(); + Iterator> rowIterator = queryResponse.getResult().iterateAll(); System.out.println("Table rows:"); while (rowIterator.hasNext()) { System.out.println(rowIterator.next()); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/JobSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/JobSnippets.java index e33275e9d139..5efc7684b657 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/JobSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/JobSnippets.java @@ -73,7 +73,7 @@ public boolean waitFor() throws InterruptedException { Job completedJob = job.waitFor(); if (completedJob == null) { // job no longer exists - } else if (completedJob.status().error() != null) { + } else if (completedJob.getStatus().getError() != null) { // job failed, handle error } else { // job completed successfully @@ -99,7 +99,7 @@ public boolean waitForWithOptions() throws InterruptedException { WaitForOption.timeout(60, TimeUnit.SECONDS)); if (completedJob == null) { // job no longer exists - } else if (completedJob.status().error() != null) { + } else if (completedJob.getStatus().getError() != null) { // job failed, handle error } else { // job completed successfully @@ -117,12 +117,12 @@ public boolean waitForWithOptions() throws InterruptedException { // [TARGET reload(JobOption...)] public JobStatus.State reload() throws InterruptedException { // [START reload] - while (job.status().state() != JobStatus.State.DONE) { + while (job.getStatus().getState() != JobStatus.State.DONE) { Thread.sleep(1000L); job = job.reload(); } // [END reload] - return job.status().state(); + return job.getStatus().getState(); } /** @@ -131,12 +131,12 @@ public JobStatus.State reload() throws InterruptedException { // [TARGET reload(JobOption...)] public JobStatus.State reloadStatus() throws InterruptedException { // [START reloadStatus] - while (job.status().state() != JobStatus.State.DONE) { + while (job.getStatus().getState() != JobStatus.State.DONE) { Thread.sleep(1000L); job = job.reload(BigQuery.JobOption.fields(BigQuery.JobField.STATUS)); } // [END reloadStatus] - return job.status().state(); + return job.getStatus().getState(); } /** diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/TableSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/TableSnippets.java index c169f6badf58..cae06209c636 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/TableSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/TableSnippets.java @@ -97,7 +97,7 @@ public Table reloadTableWithFields(TableField field1, TableField field2) { // [TARGET update(TableOption...)] public Table update() { // [START update] - Table updatedTable = table.toBuilder().description("new description").build().update(); + Table updatedTable = table.toBuilder().setDescription("new description").build().update(); // [END update] return updatedTable; } @@ -193,7 +193,7 @@ public Job copy(String datasetName, String tableName) { try { Job completedJob = job.waitFor(WaitForOption.checkEvery(1, TimeUnit.SECONDS), WaitForOption.timeout(3, TimeUnit.MINUTES)); - if (completedJob != null && completedJob.status().error() == null) { + if (completedJob != null && completedJob.getStatus().getError() == null) { // Job completed successfully } else { // Handle error case @@ -220,7 +220,7 @@ public Job copyTableId(String dataset, String tableName) throws BigQueryExceptio try { Job completedJob = job.waitFor(WaitForOption.checkEvery(1, TimeUnit.SECONDS), WaitForOption.timeout(3, TimeUnit.MINUTES)); - if (completedJob != null && completedJob.status().error() == null) { + if (completedJob != null && completedJob.getStatus().getError() == null) { // Job completed successfully. } else { // Handle error case. @@ -249,7 +249,7 @@ public Job extractList(String format, String gcsUrl1, String gcsUrl2) { try { Job completedJob = job.waitFor(WaitForOption.checkEvery(1, TimeUnit.SECONDS), WaitForOption.timeout(3, TimeUnit.MINUTES)); - if (completedJob != null && completedJob.status().error() == null) { + if (completedJob != null && completedJob.getStatus().getError() == null) { // Job completed successfully } else { // Handle error case @@ -274,7 +274,7 @@ public Job extractSingle(String format, String gcsUrl) { try { Job completedJob = job.waitFor(WaitForOption.checkEvery(1, TimeUnit.SECONDS), WaitForOption.timeout(3, TimeUnit.MINUTES)); - if (completedJob != null && completedJob.status().error() == null) { + if (completedJob != null && completedJob.getStatus().getError() == null) { // Job completed successfully } else { // Handle error case @@ -302,7 +302,7 @@ public Job loadList(String gcsUrl1, String gcsUrl2) { try { Job completedJob = job.waitFor(WaitForOption.checkEvery(1, TimeUnit.SECONDS), WaitForOption.timeout(3, TimeUnit.MINUTES)); - if (completedJob != null && completedJob.status().error() == null) { + if (completedJob != null && completedJob.getStatus().getError() == null) { // Job completed successfully } else { // Handle error case @@ -326,7 +326,7 @@ public Job loadSingle(String sourceUri) { try { Job completedJob = job.waitFor(WaitForOption.checkEvery(1, TimeUnit.SECONDS), WaitForOption.timeout(3, TimeUnit.MINUTES)); - if (completedJob != null && completedJob.status().error() == null) { + if (completedJob != null && completedJob.getStatus().getError() == null) { // Job completed successfully } else { // Handle error case diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITBigQuerySnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITBigQuerySnippets.java index a60ab6a31beb..124135eabb48 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITBigQuerySnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITBigQuerySnippets.java @@ -67,21 +67,21 @@ public class ITBigQuerySnippets { private static final Function TO_JOB_ID_FUNCTION = new Function() { @Override public JobId apply(Job job) { - return job.jobId(); + return job.getJobId(); } }; private static final Function TO_TABLE_ID_FUNCTION = new Function() { @Override public TableId apply(Table table) { - return table.tableId(); + return table.getTableId(); } }; private static final Function TO_DATASET_ID_FUNCTION = new Function() { @Override public DatasetId apply(Dataset dataset) { - return dataset.datasetId(); + return dataset.getDatasetId(); } }; @@ -93,9 +93,9 @@ public DatasetId apply(Dataset dataset) { @BeforeClass public static void beforeClass() { - bigquery = RemoteBigQueryHelper.create().options().service(); + bigquery = RemoteBigQueryHelper.create().getOptions().service(); bigquerySnippets = new BigQuerySnippets(bigquery); - bigquery.create(DatasetInfo.builder(DATASET).build()); + bigquery.create(DatasetInfo.newBuilder(DATASET).build()); } @AfterClass @@ -111,11 +111,11 @@ public void testCreateGetAndDeleteTable() throws InterruptedException { Table table = bigquerySnippets.createTable(DATASET, tableName, fieldName); assertNotNull(table); TableId tableId = TableId.of(bigquery.options().projectId(), DATASET, tableName); - assertEquals(tableId, bigquerySnippets.getTable(tableId.dataset(), tableId.table()).tableId()); + assertEquals(tableId, + bigquerySnippets.getTable(tableId.getDataset(), tableId.getTable()).getTableId()); assertNotNull(bigquerySnippets.updateTable(DATASET, tableName, "new friendly name")); - assertEquals("new friendly name", - bigquerySnippets.getTableFromId(tableId.project(), tableId.dataset(), tableId.table()) - .friendlyName()); + assertEquals("new friendly name", bigquerySnippets.getTableFromId( + tableId.getProject(), tableId.getDataset(), tableId.getTable()).getFriendlyName()); Set tables = Sets.newHashSet( Iterators.transform(bigquerySnippets.listTables(DATASET).iterateAll(), TO_TABLE_ID_FUNCTION)); @@ -126,16 +126,16 @@ public void testCreateGetAndDeleteTable() throws InterruptedException { TO_TABLE_ID_FUNCTION)); } tables = Sets.newHashSet(Iterators.transform( - bigquerySnippets.listTablesFromId(tableId.project(), DATASET).iterateAll(), + bigquerySnippets.listTablesFromId(tableId.getProject(), DATASET).iterateAll(), TO_TABLE_ID_FUNCTION)); while (!tables.contains(tableId)) { Thread.sleep(500); tables = Sets.newHashSet(Iterators.transform( - bigquerySnippets.listTablesFromId(tableId.project(), DATASET).iterateAll(), + bigquerySnippets.listTablesFromId(tableId.getProject(), DATASET).iterateAll(), TO_TABLE_ID_FUNCTION)); } assertTrue(bigquerySnippets.deleteTable(DATASET, tableName)); - assertFalse(bigquerySnippets.deleteTableFromId(tableId.project(), DATASET, tableName)); + assertFalse(bigquerySnippets.deleteTableFromId(tableId.getProject(), DATASET, tableName)); } @Test @@ -143,10 +143,10 @@ public void testCreateGetAndDeleteDataset() throws InterruptedException { DatasetId datasetId = DatasetId.of(bigquery.options().projectId(), OTHER_DATASET); Dataset dataset = bigquerySnippets.createDataset(OTHER_DATASET); assertNotNull(dataset); - assertEquals(datasetId, bigquerySnippets.getDataset(OTHER_DATASET).datasetId()); + assertEquals(datasetId, bigquerySnippets.getDataset(OTHER_DATASET).getDatasetId()); assertNotNull(bigquerySnippets.updateDataset(OTHER_DATASET, "new friendly name")); assertEquals("new friendly name", - bigquerySnippets.getDatasetFromId(datasetId.project(), OTHER_DATASET).friendlyName()); + bigquerySnippets.getDatasetFromId(datasetId.getProject(), OTHER_DATASET).getFriendlyName()); Set datasets = Sets.newHashSet( Iterators.transform(bigquerySnippets.listDatasets().iterateAll(), TO_DATASET_ID_FUNCTION)); @@ -157,16 +157,16 @@ public void testCreateGetAndDeleteDataset() throws InterruptedException { TO_DATASET_ID_FUNCTION)); } datasets = Sets.newHashSet( - Iterators.transform(bigquerySnippets.listDatasets(datasetId.project()).iterateAll(), + Iterators.transform(bigquerySnippets.listDatasets(datasetId.getProject()).iterateAll(), TO_DATASET_ID_FUNCTION)); while (!datasets.contains(datasetId)) { Thread.sleep(500); datasets = Sets.newHashSet( - Iterators.transform(bigquerySnippets.listDatasets(datasetId.project()).iterateAll(), + Iterators.transform(bigquerySnippets.listDatasets(datasetId.getProject()).iterateAll(), TO_DATASET_ID_FUNCTION)); } assertTrue(bigquerySnippets.deleteDataset(OTHER_DATASET)); - assertFalse(bigquerySnippets.deleteDatasetFromId(datasetId.project(), OTHER_DATASET)); + assertFalse(bigquerySnippets.deleteDatasetFromId(datasetId.getProject(), OTHER_DATASET)); } @Test @@ -181,8 +181,8 @@ public void testWriteAndListTableData() throws IOException, InterruptedException listPage = bigquerySnippets.listTableData(DATASET, tableName); } Iterator> rowIterator = listPage.values().iterator(); - assertEquals("StringValue1", rowIterator.next().get(0).stringValue()); - assertEquals("StringValue2", rowIterator.next().get(0).stringValue()); + assertEquals("StringValue1", rowIterator.next().get(0).getStringValue()); + assertEquals("StringValue2", rowIterator.next().get(0).getStringValue()); assertTrue(bigquerySnippets.deleteTable(DATASET, tableName)); } @@ -198,15 +198,15 @@ public void testInsertAllAndListTableData() throws IOException, InterruptedExcep assertNotNull(bigquery.create(table)); InsertAllResponse response = bigquerySnippets.insertAll(DATASET, tableName); assertFalse(response.hasErrors()); - assertTrue(response.insertErrors().isEmpty()); + assertTrue(response.getInsertErrors().isEmpty()); Page> listPage = bigquerySnippets.listTableDataFromId(DATASET, tableName); while (Iterators.size(listPage.iterateAll()) < 1) { Thread.sleep(500); listPage = bigquerySnippets.listTableDataFromId(DATASET, tableName); } List row = listPage.values().iterator().next(); - assertEquals(true, row.get(0).booleanValue()); - assertArrayEquals(new byte[]{0xD, 0xE, 0xA, 0xD}, row.get(1).bytesValue()); + assertEquals(true, row.get(0).getBooleanValue()); + assertArrayEquals(new byte[]{0xD, 0xE, 0xA, 0xD}, row.get(1).getBytesValue()); assertTrue(bigquerySnippets.deleteTable(DATASET, tableName)); } @@ -216,17 +216,18 @@ public void testJob() throws ExecutionException, InterruptedException { Job job2 = bigquerySnippets.createJob(QUERY); assertNotNull(job1); assertNotNull(job2); - assertEquals(job1.jobId(), bigquerySnippets.getJob(job1.jobId().job()).jobId()); - assertEquals(job2.jobId(), bigquerySnippets.getJobFromId(job2.jobId().job()).jobId()); + assertEquals(job1.getJobId(), bigquerySnippets.getJob(job1.getJobId().getJob()).getJobId()); + assertEquals(job2.getJobId(), + bigquerySnippets.getJobFromId(job2.getJobId().getJob()).getJobId()); Set jobs = Sets.newHashSet(Iterators.transform(bigquerySnippets.listJobs().iterateAll(), TO_JOB_ID_FUNCTION)); - while (!jobs.contains(job1.jobId()) || !jobs.contains(job2.jobId())) { + while (!jobs.contains(job1.getJobId()) || !jobs.contains(job2.getJobId())) { Thread.sleep(500); jobs = Sets.newHashSet(Iterators.transform(bigquerySnippets.listJobs().iterateAll(), TO_JOB_ID_FUNCTION)); } - assertTrue(bigquerySnippets.cancelJob(job1.jobId().job())); - assertTrue(bigquerySnippets.cancelJobFromId(job2.jobId().job())); + assertTrue(bigquerySnippets.cancelJob(job1.getJobId().getJob())); + assertTrue(bigquerySnippets.cancelJobFromId(job2.getJobId().getJob())); } @Test @@ -235,15 +236,15 @@ public void testRunQuery() throws InterruptedException { assertNotNull(queryResponse); assertTrue(queryResponse.jobCompleted()); assertFalse(queryResponse.hasErrors()); - QueryResult result = queryResponse.result(); + QueryResult result = queryResponse.getResult(); assertNotNull(result); - assertTrue(bigquerySnippets.cancelJob(queryResponse.jobId().job())); + assertTrue(bigquerySnippets.cancelJob(queryResponse.getJobId().getJob())); queryResponse = bigquerySnippets.queryResults(QUERY); assertNotNull(queryResponse); assertTrue(queryResponse.jobCompleted()); assertFalse(queryResponse.hasErrors()); - result = queryResponse.result(); + result = queryResponse.getResult(); assertNotNull(result); - assertTrue(bigquerySnippets.cancelJobFromId(queryResponse.jobId().job())); + assertTrue(bigquerySnippets.cancelJobFromId(queryResponse.getJobId().getJob())); } } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITDatasetSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITDatasetSnippets.java index 7ac2773b0aee..5ac6ff6430db 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITDatasetSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITDatasetSnippets.java @@ -54,9 +54,9 @@ public class ITDatasetSnippets { @BeforeClass public static void beforeClass() { - bigquery = RemoteBigQueryHelper.create().options().service(); - dataset = bigquery.create(DatasetInfo.builder(DATASET).build()); - nonExistingDataset = bigquery.create(DatasetInfo.builder(NON_EXISTING_DATASET).build()); + bigquery = RemoteBigQueryHelper.create().getOptions().service(); + dataset = bigquery.create(DatasetInfo.newBuilder(DATASET).build()); + nonExistingDataset = bigquery.create(DatasetInfo.newBuilder(NON_EXISTING_DATASET).build()); nonExistingDataset.delete(DatasetDeleteOption.deleteContents()); } @@ -88,22 +88,22 @@ public void testReloadNonExistingDataset() { @Test public void testReload() { - assertNull(dataset.friendlyName()); + assertNull(dataset.getFriendlyName()); Builder builder = dataset.toBuilder(); - builder.friendlyName(FRIENDLY_NAME); + builder.setFriendlyName(FRIENDLY_NAME); builder.build().update(); Dataset reloadedDataset = datasetSnippets.reloadDataset(); - assertEquals(FRIENDLY_NAME, reloadedDataset.friendlyName()); + assertEquals(FRIENDLY_NAME, reloadedDataset.getFriendlyName()); } @Test public void testUpdate() { - assertNull(dataset.friendlyName()); + assertNull(dataset.getFriendlyName()); Dataset updatedDataset = datasetSnippets.updateDataset(FRIENDLY_NAME); - assertEquals(FRIENDLY_NAME, updatedDataset.friendlyName()); + assertEquals(FRIENDLY_NAME, updatedDataset.getFriendlyName()); } @Test @@ -114,7 +114,7 @@ public void testDeleteNonExistingDataset() { @Test public void testDelete() { String datasetName = RemoteBigQueryHelper.generateDatasetName(); - DatasetInfo dataset = DatasetInfo.builder(datasetName).build(); + DatasetInfo dataset = DatasetInfo.newBuilder(datasetName).build(); DatasetSnippets datasetSnippets = new DatasetSnippets(bigquery.create(dataset)); assertTrue(datasetSnippets.deleteDataset()); } @@ -129,13 +129,13 @@ public void testListTablesEmpty() { public void testListTablesNotEmpty() { String expectedTableName = "test_table"; - dataset.create(expectedTableName, StandardTableDefinition.builder().build()); + dataset.create(expectedTableName, StandardTableDefinition.newBuilder().build()); Page
tables = datasetSnippets.list(); Iterator
iterator = tables.iterateAll(); assertTrue(iterator.hasNext()); Table actualTable = iterator.next(); - assertEquals(expectedTableName, actualTable.tableId().table()); + assertEquals(expectedTableName, actualTable.getTableId().getTable()); assertFalse(iterator.hasNext()); bigquery.delete(DATASET, expectedTableName); @@ -145,11 +145,11 @@ public void testListTablesNotEmpty() { public void testGetTable() { String expectedTableName = "test_table"; - dataset.create(expectedTableName, StandardTableDefinition.builder().build()); + dataset.create(expectedTableName, StandardTableDefinition.newBuilder().build()); Table actualTable = datasetSnippets.getTable(expectedTableName); assertNotNull(actualTable); - assertEquals(expectedTableName, actualTable.tableId().table()); + assertEquals(expectedTableName, actualTable.getTableId().getTable()); bigquery.delete(DATASET, expectedTableName); } @@ -161,11 +161,11 @@ public void testCreateTable() { Table actualTable = datasetSnippets.createTable(expectedTableName, expectedFieldName); assertNotNull(actualTable); - assertEquals(expectedTableName, actualTable.tableId().table()); - assertEquals(1, actualTable.definition().schema().fields().size()); + assertEquals(expectedTableName, actualTable.getTableId().getTable()); + assertEquals(1, actualTable.getDefinition().getSchema().getFields().size()); - Field actualField = actualTable.definition().schema().fields().get(0); - assertEquals(expectedFieldName, actualField.name()); + Field actualField = actualTable.getDefinition().getSchema().getFields().get(0); + assertEquals(expectedFieldName, actualField.getName()); bigquery.delete(DATASET, expectedTableName); } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITJobSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITJobSnippets.java index af777ab7a489..44ec7c02aef6 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITJobSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITJobSnippets.java @@ -39,13 +39,14 @@ public class ITJobSnippets { @BeforeClass public static void beforeClass() { - bigquery = RemoteBigQueryHelper.create().options().service(); + bigquery = RemoteBigQueryHelper.create().getOptions().service(); } @Test public void testExists() throws Exception { - JobConfiguration jobConfig = QueryJobConfiguration.builder(QUERY).useLegacySql(false).build(); - JobInfo jobInfo = JobInfo.builder(jobConfig).build(); + JobConfiguration jobConfig = + QueryJobConfiguration.newBuilder(QUERY).setUseLegacySql(false).build(); + JobInfo jobInfo = JobInfo.newBuilder(jobConfig).build(); Job job = bigquery.create(jobInfo); JobSnippets jobSnippets = new JobSnippets(job); boolean result = jobSnippets.exists(); @@ -54,8 +55,9 @@ public void testExists() throws Exception { @Test public void testIsDone() throws Exception { - JobConfiguration jobConfig = QueryJobConfiguration.builder(QUERY).useLegacySql(false).build(); - JobInfo jobInfo = JobInfo.builder(jobConfig).build(); + JobConfiguration jobConfig = + QueryJobConfiguration.newBuilder(QUERY).setUseLegacySql(false).build(); + JobInfo jobInfo = JobInfo.newBuilder(jobConfig).build(); Job job = bigquery.create(jobInfo); JobSnippets jobSnippets = new JobSnippets(job); jobSnippets.isDone(); @@ -64,8 +66,9 @@ public void testIsDone() throws Exception { @Test public void testWaitFor() throws Exception { - JobConfiguration jobConfig = QueryJobConfiguration.builder(QUERY).useLegacySql(false).build(); - JobInfo jobInfo = JobInfo.builder(jobConfig).build(); + JobConfiguration jobConfig = + QueryJobConfiguration.newBuilder(QUERY).setUseLegacySql(false).build(); + JobInfo jobInfo = JobInfo.newBuilder(jobConfig).build(); Job job = bigquery.create(jobInfo); JobSnippets jobSnippets = new JobSnippets(job); boolean result = jobSnippets.waitFor(); @@ -74,8 +77,9 @@ public void testWaitFor() throws Exception { @Test public void testWaitForWithOptions() throws Exception { - JobConfiguration jobConfig = QueryJobConfiguration.builder(QUERY).useLegacySql(false).build(); - JobInfo jobInfo = JobInfo.builder(jobConfig).build(); + JobConfiguration jobConfig = + QueryJobConfiguration.newBuilder(QUERY).setUseLegacySql(false).build(); + JobInfo jobInfo = JobInfo.newBuilder(jobConfig).build(); Job job = bigquery.create(jobInfo); JobSnippets jobSnippets = new JobSnippets(job); boolean result = jobSnippets.waitForWithOptions(); @@ -84,8 +88,9 @@ public void testWaitForWithOptions() throws Exception { @Test public void testReload() throws Exception { - JobConfiguration jobConfig = QueryJobConfiguration.builder(QUERY).useLegacySql(false).build(); - JobInfo jobInfo = JobInfo.builder(jobConfig).build(); + JobConfiguration jobConfig = + QueryJobConfiguration.newBuilder(QUERY).setUseLegacySql(false).build(); + JobInfo jobInfo = JobInfo.newBuilder(jobConfig).build(); Job job = bigquery.create(jobInfo); JobSnippets jobSnippets = new JobSnippets(job); JobStatus.State result = jobSnippets.reload(); @@ -94,8 +99,9 @@ public void testReload() throws Exception { @Test public void testReloadStatus() throws Exception { - JobConfiguration jobConfig = QueryJobConfiguration.builder(QUERY).useLegacySql(false).build(); - JobInfo jobInfo = JobInfo.builder(jobConfig).build(); + JobConfiguration jobConfig = + QueryJobConfiguration.newBuilder(QUERY).setUseLegacySql(false).build(); + JobInfo jobInfo = JobInfo.newBuilder(jobConfig).build(); Job job = bigquery.create(jobInfo); JobSnippets jobSnippets = new JobSnippets(job); JobStatus.State result = jobSnippets.reloadStatus(); @@ -104,8 +110,9 @@ public void testReloadStatus() throws Exception { @Test public void testCancel() { - JobConfiguration jobConfig = QueryJobConfiguration.builder(QUERY).useLegacySql(false).build(); - JobInfo jobInfo = JobInfo.builder(jobConfig).build(); + JobConfiguration jobConfig = + QueryJobConfiguration.newBuilder(QUERY).setUseLegacySql(false).build(); + JobInfo jobInfo = JobInfo.newBuilder(jobConfig).build(); Job job = bigquery.create(jobInfo); JobSnippets jobSnippets = new JobSnippets(job); boolean result = jobSnippets.cancel(); diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITTableSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITTableSnippets.java index 6687c653d014..9294053c4588 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITTableSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITTableSnippets.java @@ -85,9 +85,9 @@ public class ITTableSnippets { @BeforeClass public static void beforeClass() { - bigquery = RemoteBigQueryHelper.create().options().service(); - bigquery.create(DatasetInfo.builder(DATASET_NAME).build()); - bigquery.create(DatasetInfo.builder(COPY_DATASET_NAME).build()); + bigquery = RemoteBigQueryHelper.create().getOptions().service(); + bigquery.create(DatasetInfo.newBuilder(DATASET_NAME).build()); + bigquery.create(DatasetInfo.newBuilder(COPY_DATASET_NAME).build()); storage = RemoteStorageHelper.create().options().service(); storage.create(BucketInfo.of(BUCKET_NAME)); } @@ -95,8 +95,8 @@ public static void beforeClass() { @Before public void before() { ++nextTableNumber; - StandardTableDefinition.Builder builder = StandardTableDefinition.builder(); - builder.schema(SCHEMA); + StandardTableDefinition.Builder builder = StandardTableDefinition.newBuilder(); + builder.setSchema(SCHEMA); table = bigquery.create(TableInfo.of(getTableId(), builder.build())); bigquery.create(TableInfo.of(getCopyTableId(), builder.build())); tableSnippets = new TableSnippets(table); @@ -141,13 +141,13 @@ public void testReloadTableWithFields() { Table latestTable = tableSnippets.reloadTableWithFields(TableField.LAST_MODIFIED_TIME, TableField.NUM_ROWS); assertNotNull(latestTable); - assertNotNull(latestTable.lastModifiedTime()); + assertNotNull(latestTable.getLastModifiedTime()); } @Test public void testUpdate() { Table updatedTable = tableSnippets.update(); - assertEquals("new description", updatedTable.description()); + assertEquals("new description", updatedTable.getDescription()); } @Test @@ -178,7 +178,7 @@ public void testInsertParams() throws InterruptedException { FluentIterable.from(rows).transform(new Function, List>() { @Override public List apply(List row) { - return ImmutableList.of(row.get(0).stringValue(), row.get(1).booleanValue()); + return ImmutableList.of(row.get(0).getStringValue(), row.get(1).getBooleanValue()); } }).toSet(); assertEquals(ImmutableSet.of(ROW2), values); @@ -243,7 +243,7 @@ private void verifyTestRows(Table checkTable) throws InterruptedException { FluentIterable.from(rows).transform(new Function, List>() { @Override public List apply(List row) { - return ImmutableList.of(row.get(0).stringValue(), row.get(1).booleanValue()); + return ImmutableList.of(row.get(0).getStringValue(), row.get(1).getBooleanValue()); } }).toSet(); assertEquals(ImmutableSet.of(ROW2, ROW1), values); @@ -272,6 +272,6 @@ private List> waitForTableRows(Table checkTable, int numRows) private void assertSuccessful(Job job) { assertTrue(job.isDone()); - assertNull(job.status().error()); + assertNull(job.getStatus().getError()); } } From 82b2951d7ea8c45f79323b8bb134c477482f8571 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Tue, 25 Oct 2016 21:18:18 +0200 Subject: [PATCH 21/32] Fix flakey list log entries test (#1335) --- .../java/com/google/cloud/logging/BaseSystemTest.java | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java index eb523b0dddcf..4e5d42ef9281 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java @@ -396,8 +396,13 @@ public void testWriteAndListLogEntries() throws InterruptedException { assertNull(entry.getHttpRequest()); assertNotNull(entry.getInsertId()); assertNotNull(entry.getTimestamp()); - page = logging().listLogEntries(EntryListOption.filter(filter), - EntryListOption.sortOrder(SortingField.TIMESTAMP, SortingOrder.DESCENDING)); + options = new EntryListOption[]{EntryListOption.filter(filter), + EntryListOption.sortOrder(SortingField.TIMESTAMP, SortingOrder.DESCENDING)}; + page = logging().listLogEntries(options); + while (Iterators.size(page.iterateAll()) < 2) { + Thread.sleep(500); + page = logging().listLogEntries(options); + } iterator = page.iterateAll(); Long lastTimestamp = iterator.next().getTimestamp(); while (iterator.hasNext()) { From 4142a84b686d4bb2f9970d20f4e54a7df192b730 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Wed, 26 Oct 2016 11:39:30 +0200 Subject: [PATCH 22/32] Rename setters/getters/builders for Compute classes to meet proto conventions (#1322) * Rename setters/getters/builders for Compute classes to meet proto conventions * Update Compute examples, snippets and READMEs to use renamed getters/setters/builders --- README.md | 4 +- google-cloud-compute/README.md | 12 +- .../com/google/cloud/compute/Address.java | 54 +- .../com/google/cloud/compute/AddressId.java | 20 + .../com/google/cloud/compute/AddressInfo.java | 188 ++- .../google/cloud/compute/AttachedDisk.java | 352 ++++- .../com/google/cloud/compute/ComputeImpl.java | 139 +- .../cloud/compute/DeprecationStatus.java | 174 ++- .../java/com/google/cloud/compute/Disk.java | 81 +- .../cloud/compute/DiskConfiguration.java | 48 +- .../java/com/google/cloud/compute/DiskId.java | 43 +- .../cloud/compute/DiskImageConfiguration.java | 46 +- .../com/google/cloud/compute/DiskInfo.java | 168 ++- .../com/google/cloud/compute/DiskType.java | 95 +- .../com/google/cloud/compute/DiskTypeId.java | 40 +- .../cloud/compute/ForwardingRuleId.java | 20 + .../google/cloud/compute/GlobalAddressId.java | 18 +- .../cloud/compute/GlobalForwardingRuleId.java | 20 +- .../cloud/compute/GlobalOperationId.java | 18 +- .../java/com/google/cloud/compute/Image.java | 66 +- .../cloud/compute/ImageConfiguration.java | 32 +- .../cloud/compute/ImageDiskConfiguration.java | 61 +- .../com/google/cloud/compute/ImageId.java | 25 +- .../com/google/cloud/compute/ImageInfo.java | 164 +- .../com/google/cloud/compute/Instance.java | 170 ++- .../com/google/cloud/compute/InstanceId.java | 46 +- .../google/cloud/compute/InstanceInfo.java | 332 +++- .../com/google/cloud/compute/License.java | 12 +- .../com/google/cloud/compute/LicenseId.java | 20 +- .../com/google/cloud/compute/MachineType.java | 133 +- .../google/cloud/compute/MachineTypeId.java | 38 +- .../com/google/cloud/compute/Metadata.java | 54 +- .../com/google/cloud/compute/Network.java | 50 +- .../cloud/compute/NetworkConfiguration.java | 10 + .../com/google/cloud/compute/NetworkId.java | 28 +- .../com/google/cloud/compute/NetworkInfo.java | 109 +- .../cloud/compute/NetworkInterface.java | 214 ++- .../com/google/cloud/compute/Operation.java | 263 +++- .../com/google/cloud/compute/OperationId.java | 14 + .../java/com/google/cloud/compute/Option.java | 4 +- .../java/com/google/cloud/compute/Region.java | 127 +- .../google/cloud/compute/RegionAddressId.java | 38 +- .../cloud/compute/RegionForwardingRuleId.java | 40 +- .../com/google/cloud/compute/RegionId.java | 24 +- .../cloud/compute/RegionOperationId.java | 38 +- .../com/google/cloud/compute/ResourceId.java | 16 + .../cloud/compute/SchedulingOptions.java | 8 + .../google/cloud/compute/ServiceAccount.java | 16 + .../com/google/cloud/compute/Snapshot.java | 72 +- .../compute/SnapshotDiskConfiguration.java | 64 +- .../com/google/cloud/compute/SnapshotId.java | 24 +- .../google/cloud/compute/SnapshotInfo.java | 187 ++- .../compute/StandardDiskConfiguration.java | 29 +- .../compute/StandardNetworkConfiguration.java | 20 + .../compute/StorageImageConfiguration.java | 65 +- .../compute/SubnetNetworkConfiguration.java | 8 + .../com/google/cloud/compute/Subnetwork.java | 58 +- .../google/cloud/compute/SubnetworkId.java | 48 +- .../google/cloud/compute/SubnetworkInfo.java | 151 +- .../java/com/google/cloud/compute/Tags.java | 83 +- .../java/com/google/cloud/compute/Zone.java | 92 +- .../java/com/google/cloud/compute/ZoneId.java | 20 +- .../google/cloud/compute/ZoneOperationId.java | 38 +- .../google/cloud/compute/package-info.java | 4 +- .../compute/testing/RemoteComputeHelper.java | 8 + .../cloud/compute/testing/package-info.java | 2 +- .../google/cloud/compute/AddressIdTest.java | 47 +- .../google/cloud/compute/AddressInfoTest.java | 205 ++- .../com/google/cloud/compute/AddressTest.java | 130 +- .../cloud/compute/AttachedDiskTest.java | 279 ++-- .../google/cloud/compute/ComputeImplTest.java | 1093 ++++++++------ .../cloud/compute/DeprecationStatusTest.java | 132 +- .../com/google/cloud/compute/DiskIdTest.java | 29 +- .../compute/DiskImageConfigurationTest.java | 69 +- .../google/cloud/compute/DiskInfoTest.java | 321 ++-- .../com/google/cloud/compute/DiskTest.java | 235 +-- .../google/cloud/compute/DiskTypeIdTest.java | 25 +- .../google/cloud/compute/DiskTypeTest.java | 43 +- .../cloud/compute/ForwardingRuleIdTest.java | 55 +- .../compute/ImageDiskConfigurationTest.java | 69 +- .../com/google/cloud/compute/ImageIdTest.java | 21 +- .../google/cloud/compute/ImageInfoTest.java | 200 ++- .../com/google/cloud/compute/ImageTest.java | 139 +- .../google/cloud/compute/InstanceIdTest.java | 30 +- .../cloud/compute/InstanceInfoTest.java | 184 ++- .../google/cloud/compute/InstanceTest.java | 290 ++-- .../google/cloud/compute/LicenseIdTest.java | 21 +- .../com/google/cloud/compute/LicenseTest.java | 12 +- .../cloud/compute/MachineTypeIdTest.java | 25 +- .../google/cloud/compute/MachineTypeTest.java | 59 +- .../google/cloud/compute/MetadataTest.java | 43 +- .../google/cloud/compute/NetworkIdTest.java | 21 +- .../google/cloud/compute/NetworkInfoTest.java | 90 +- .../cloud/compute/NetworkInterfaceTest.java | 163 +- .../com/google/cloud/compute/NetworkTest.java | 73 +- .../google/cloud/compute/OperationIdTest.java | 81 +- .../google/cloud/compute/OperationTest.java | 274 ++-- .../google/cloud/compute/RegionIdTest.java | 21 +- .../com/google/cloud/compute/RegionTest.java | 50 +- .../cloud/compute/SchedulingOptionsTest.java | 14 +- .../cloud/compute/SerializationTest.java | 70 +- .../cloud/compute/ServiceAccountTest.java | 10 +- .../SnapshotDiskConfigurationTest.java | 69 +- .../google/cloud/compute/SnapshotIdTest.java | 21 +- .../cloud/compute/SnapshotInfoTest.java | 128 +- .../google/cloud/compute/SnapshotTest.java | 113 +- .../StandardDiskConfigurationTest.java | 50 +- .../StandardNetworkConfigurationTest.java | 24 +- .../StorageImageConfigurationTest.java | 64 +- .../SubnetNetworkConfigurationTest.java | 28 +- .../cloud/compute/SubnetworkIdTest.java | 29 +- .../cloud/compute/SubnetworkInfoTest.java | 76 +- .../google/cloud/compute/SubnetworkTest.java | 45 +- .../com/google/cloud/compute/TagsTest.java | 25 +- .../com/google/cloud/compute/ZoneIdTest.java | 21 +- .../com/google/cloud/compute/ZoneTest.java | 47 +- .../cloud/compute/it/ITComputeTest.java | 1342 +++++++++-------- .../testing/RemoteComputeHelperTest.java | 3 +- .../examples/compute/ComputeExample.java | 219 +-- .../CreateAddressDiskAndInstance.java | 12 +- .../compute/snippets/CreateInstance.java | 2 +- .../compute/snippets/CreateSnapshot.java | 2 +- 122 files changed, 8166 insertions(+), 3442 deletions(-) diff --git a/README.md b/README.md index 0a0d208b028c..3bc2219ab2bd 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,7 @@ if (disk != null) { String snapshotName = "disk-name-snapshot"; Operation operation = disk.createSnapshot(snapshotName); operation = operation.waitFor(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { // use snapshot Snapshot snapshot = compute.getSnapshot(snapshotName); } @@ -252,7 +252,7 @@ MachineTypeId machineTypeId = MachineTypeId.of("us-central1-a", "n1-standard-1") Operation operation = compute.create(InstanceInfo.of(instanceId, machineTypeId, attachedDisk, networkInterface)); operation = operation.waitFor(); -if (operation.errors() == null) { +if (operation.getErrors() == null) { // use instance Instance instance = compute.getInstance(instanceId); } diff --git a/google-cloud-compute/README.md b/google-cloud-compute/README.md index 85385f819c8d..395f22936b0c 100644 --- a/google-cloud-compute/README.md +++ b/google-cloud-compute/README.md @@ -119,7 +119,7 @@ operation = operation.waitFor(); if (operation.errors() == null) { System.out.println("Address " + addressId + " was successfully created"); } else { - // inspect operation.errors() + // inspect operation.getErrors() throw new RuntimeException("Address creation failed"); } ``` @@ -150,7 +150,7 @@ DiskInfo disk = DiskInfo.of(diskId, diskConfiguration); Operation operation = compute.create(disk); // Wait for operation to complete operation = operation.waitFor(); -if (operation.errors() == null) { +if (operation.getErrors() == null) { System.out.println("Disk " + diskId + " was successfully created"); } else { // inspect operation.errors() @@ -185,10 +185,10 @@ Address externalIp = compute.getAddress(addressId); InstanceId instanceId = InstanceId.of("us-central1-a", "test-instance"); NetworkId networkId = NetworkId.of("default"); PersistentDiskConfiguration attachConfiguration = - PersistentDiskConfiguration.builder(diskId).boot(true).build(); + PersistentDiskConfiguration.newBuilder(diskId).setBoot(true).build(); AttachedDisk attachedDisk = AttachedDisk.of("dev0", attachConfiguration); -NetworkInterface networkInterface = NetworkInterface.builder(networkId) - .accessConfigurations(AccessConfig.of(externalIp.address())) +NetworkInterface networkInterface = NetworkInterface.newBuilder(networkId) + .setAccessConfigurations(AccessConfig.of(externalIp.getAddress())) .build(); MachineTypeId machineTypeId = MachineTypeId.of("us-central1-a", "n1-standard-1"); InstanceInfo instance = @@ -196,7 +196,7 @@ InstanceInfo instance = Operation operation = compute.create(instance); // Wait for operation to complete operation = operation.waitFor(); -if (operation.errors() == null) { +if (operation.getErrors() == null) { System.out.println("Instance " + instanceId + " was successfully created"); } else { // inspect operation.errors() diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Address.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Address.java index 10e99cadb60f..1c40e44dcd26 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Address.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Address.java @@ -56,7 +56,7 @@ public static class Builder extends AddressInfo.Builder { Builder(Compute compute, AddressId addressId) { this.compute = compute; this.infoBuilder = new AddressInfo.BuilderImpl(); - this.infoBuilder.addressId(addressId); + this.infoBuilder.setAddressId(addressId); } Builder(Address address) { @@ -65,44 +65,62 @@ public static class Builder extends AddressInfo.Builder { } @Override + @Deprecated public Builder address(String address) { - infoBuilder.address(address); + return setAddress(address); + } + + @Override + public Builder setAddress(String address) { + infoBuilder.setAddress(address); return this; } @Override - Builder creationTimestamp(Long creationTimestamp) { - infoBuilder.creationTimestamp(creationTimestamp); + Builder setCreationTimestamp(Long creationTimestamp) { + infoBuilder.setCreationTimestamp(creationTimestamp); return this; } @Override + @Deprecated public Builder description(String description) { - infoBuilder.description(description); + return setDescription(description); + } + + @Override + public Builder setDescription(String description) { + infoBuilder.setDescription(description); return this; } @Override - Builder generatedId(String generatedId) { - infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + infoBuilder.setGeneratedId(generatedId); return this; } @Override + @Deprecated public Builder addressId(AddressId addressId) { - infoBuilder.addressId(addressId); + return setAddressId(addressId); + } + + @Override + public Builder setAddressId(AddressId addressId) { + infoBuilder.setAddressId(addressId); return this; } @Override - Builder status(Status status) { - infoBuilder.status(status); + Builder setStatus(Status status) { + infoBuilder.setStatus(status); return this; } @Override - Builder usage(Usage usage) { - infoBuilder.usage(usage); + Builder setUsage(Usage usage) { + infoBuilder.setUsage(usage); return this; } @@ -137,7 +155,7 @@ public boolean exists() { * @throws ComputeException upon failure */ public Address reload(AddressOption... options) { - return compute.getAddress(addressId(), options); + return compute.getAddress(getAddressId(), options); } /** @@ -148,13 +166,21 @@ public Address reload(AddressOption... options) { * @throws ComputeException upon failure */ public Operation delete(OperationOption... options) { - return compute.deleteAddress(addressId(), options); + return compute.deleteAddress(getAddressId(), options); } /** * Returns the address's {@code Compute} object used to issue requests. */ + @Deprecated public Compute compute() { + return getCompute(); + } + + /** + * Returns the address's {@code Compute} object used to issue requests. + */ + public Compute getCompute() { return compute; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/AddressId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/AddressId.java index e5440e6f6d34..756955bb1065 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/AddressId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/AddressId.java @@ -54,8 +54,14 @@ enum Type { /** * Returns the type of this address identity. */ + @Deprecated public abstract Type type(); + /** + * Returns the type of this address identity. + */ + public abstract Type getType(); + /** * Returns the name of the address resource. The name must be 1-63 characters long and comply with * RFC1035. Specifically, the name must match the regular expression @@ -65,7 +71,21 @@ enum Type { * * @see RFC1035 */ + @Deprecated public String address() { + return getAddress(); + } + + /** + * Returns the name of the address resource. The name must be 1-63 characters long and comply with + * RFC1035. Specifically, the name must match the regular expression + * {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a lowercase letter, + * and all following characters must be a dash, lowercase letter, or digit, except the last + * character, which cannot be a dash. + * + * @see RFC1035 + */ + public String getAddress() { return address; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/AddressInfo.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/AddressInfo.java index 9a95c77119c8..b0f6e2716d3c 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/AddressInfo.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/AddressInfo.java @@ -106,17 +106,23 @@ public abstract static class Usage implements Serializable { /** * Returns the identities of resources currently using this address. */ + @Deprecated public abstract List users(); + /** + * Returns the identities of resources currently using this address. + */ + public abstract List getUsers(); + final boolean baseEquals(Usage usage) { return Objects.equals(toPb(), usage.toPb()); } Address toPb() { - return new Address().setUsers(Lists.transform(users(), new Function() { + return new Address().setUsers(Lists.transform(getUsers(), new Function() { @Override public String apply(ResourceId resourceId) { - return resourceId.selfLink(); + return resourceId.getSelfLink(); } })); } @@ -153,12 +159,26 @@ public static final class InstanceUsage extends Usage { /** * Returns the identity of the instance using the address. */ + @Deprecated public InstanceId instance() { + return getInstance(); + } + + /** + * Returns the identity of the instance using the address. + */ + public InstanceId getInstance() { return instance; } @Override + @Deprecated public List users() { + return getUsers(); + } + + @Override + public List getUsers() { return ImmutableList.of(instance); } @@ -200,12 +220,26 @@ public static final class RegionForwardingUsage extends Usage { /** * Returns a list of identities of region forwarding rules that are currently using the address. */ + @Deprecated public List forwardingRules() { + return getForwardingRules(); + } + + /** + * Returns a list of identities of region forwarding rules that are currently using the address. + */ + public List getForwardingRules() { return forwardingRules; } @Override + @Deprecated public List users() { + return getUsers(); + } + + @Override + public List getUsers() { return forwardingRules; } @@ -248,12 +282,26 @@ public static final class GlobalForwardingUsage extends Usage { /** * Returns a list of identities of global forwarding rules that are currently using the address. */ + @Deprecated public List forwardingRules() { + return getForwardingRules(); + } + + /** + * Returns a list of identities of global forwarding rules that are currently using the address. + */ + public List getForwardingRules() { return forwardingRules; } @Override + @Deprecated public List users() { + return getUsers(); + } + + @Override + public List getUsers() { return forwardingRules; } @@ -287,22 +335,37 @@ public abstract static class Builder { /** * Sets the actual IP address. */ + @Deprecated public abstract Builder address(String address); - abstract Builder creationTimestamp(Long creationTimestamp); + /** + * Sets the actual IP address. + */ + public abstract Builder setAddress(String address); + + abstract Builder setCreationTimestamp(Long creationTimestamp); /** * Sets an optional textual description of the address. */ + @Deprecated public abstract Builder description(String description); - abstract Builder generatedId(String generatedId); + /** + * Sets an optional textual description of the address. + */ + public abstract Builder setDescription(String description); + + abstract Builder setGeneratedId(String generatedId); + @Deprecated public abstract Builder addressId(AddressId addressId); - abstract Builder status(Status status); + public abstract Builder setAddressId(AddressId addressId); - abstract Builder usage(Usage usage); + abstract Builder setStatus(Status status); + + abstract Builder setUsage(Usage usage); /** * Creates an {@code AddressInfo} object. @@ -355,43 +418,61 @@ static final class BuilderImpl extends Builder { } @Override + @Deprecated public BuilderImpl address(String address) { + return setAddress(address); + } + + @Override + public BuilderImpl setAddress(String address) { this.address = address; return this; } @Override - BuilderImpl creationTimestamp(Long creationTimestamp) { + BuilderImpl setCreationTimestamp(Long creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } @Override + @Deprecated public BuilderImpl description(String description) { + return setDescription(description); + } + + @Override + public BuilderImpl setDescription(String description) { this.description = description; return this; } @Override - BuilderImpl generatedId(String generatedId) { + BuilderImpl setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } @Override + @Deprecated public BuilderImpl addressId(AddressId addressId) { + return setAddressId(addressId); + } + + @Override + public BuilderImpl setAddressId(AddressId addressId) { this.addressId = checkNotNull(addressId); return this; } @Override - BuilderImpl status(Status status) { + BuilderImpl setStatus(Status status) { this.status = status; return this; } @Override - BuilderImpl usage(Usage usage) { + BuilderImpl setUsage(Usage usage) { this.usage = usage; return this; } @@ -415,28 +496,60 @@ public AddressInfo build() { /** * Returns the static external IP address represented by this object. */ + @Deprecated public String address() { + return getAddress(); + } + + /** + * Returns the static external IP address represented by this object. + */ + public String getAddress() { return address; } /** * Returns the creation timestamp in milliseconds since epoch. */ + @Deprecated public Long creationTimestamp() { + return getCreationTimestamp(); + } + + /** + * Returns the creation timestamp in milliseconds since epoch. + */ + public Long getCreationTimestamp() { return creationTimestamp; } /** * Returns an optional textual description of the address. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns an optional textual description of the address. + */ + public String getDescription() { return description; } /** * Returns the service-generated unique identifier for the address. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated unique identifier for the address. + */ + public String getGeneratedId() { return generatedId; } @@ -445,14 +558,32 @@ public String generatedId() { * {@link RegionAddressId} for a region address. */ @SuppressWarnings("unchecked") + @Deprecated public T addressId() { + return getAddressId(); + } + + /** + * Returns the address identity. Returns {@link GlobalAddressId} for a global address, returns + * {@link RegionAddressId} for a region address. + */ + @SuppressWarnings("unchecked") + public T getAddressId() { return (T) addressId; } /** * Returns the status of the address. */ + @Deprecated public Status status() { + return getStatus(); + } + + /** + * Returns the status of the address. + */ + public Status getStatus() { return status; } @@ -464,7 +595,20 @@ public Status status() { * Returns {@code null} if the address is not in use. */ @SuppressWarnings("unchecked") + @Deprecated public T usage() { + return getUsage(); + } + + /** + * Returns the usage information of the address. Returns an {@link InstanceUsage} object for + * region addresses that are assigned to VM instances. Returns a {@link RegionForwardingUsage} + * object for region addresses assigned to region forwarding rules. Returns a + * {@link GlobalForwardingUsage} object for global addresses assigned to global forwarding rules. + * Returns {@code null} if the address is not in use. + */ + @SuppressWarnings("unchecked") + public T getUsage() { return (T) usage; } @@ -503,10 +647,10 @@ public boolean equals(Object obj) { } AddressInfo setProjectId(String projectId) { - if (addressId().project() != null) { + if (getAddressId().getProject() != null) { return this; } - return toBuilder().addressId(addressId.setProjectId(projectId)).build(); + return toBuilder().setAddressId(addressId.setProjectId(projectId)).build(); } Address toPb() { @@ -519,29 +663,37 @@ Address toPb() { if (generatedId != null) { addressPb.setId(new BigInteger(generatedId)); } - addressPb.setName(addressId.address()); - if (addressId.type() == AddressId.Type.REGION) { - addressPb.setRegion(this.addressId().regionId().selfLink()); + addressPb.setName(addressId.getAddress()); + if (addressId.getType() == AddressId.Type.REGION) { + addressPb.setRegion(this.getAddressId().getRegionId().getSelfLink()); } if (status != null) { addressPb.setStatus(status.name()); } - addressPb.setSelfLink(addressId.selfLink()); + addressPb.setSelfLink(addressId.getSelfLink()); return addressPb; } /** * Returns a builder for the {@code AddressInfo} object given it's identity. */ + @Deprecated public static Builder builder(AddressId addressId) { - return new BuilderImpl().addressId(addressId); + return newBuilder(addressId); + } + + /** + * Returns a builder for the {@code AddressInfo} object given it's identity. + */ + public static Builder newBuilder(AddressId addressId) { + return new BuilderImpl().setAddressId(addressId); } /** * Returns an {@code AddressInfo} object for the provided identity. */ public static AddressInfo of(AddressId addressId) { - return builder(addressId).build(); + return newBuilder(addressId).build(); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/AttachedDisk.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/AttachedDisk.java index d4ad674a8a5e..fc4d0181bed0 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/AttachedDisk.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/AttachedDisk.java @@ -114,7 +114,15 @@ public enum InterfaceType { /** * Returns the type of the attached disk. */ + @Deprecated public Type type() { + return getType(); + } + + /** + * Returns the type of the attached disk. + */ + public Type getType() { return type; } @@ -122,7 +130,16 @@ public Type type() { * Returns the interface to use to attach the disk. If not specified, {@link InterfaceType#SCSI} * is used. */ + @Deprecated public InterfaceType interfaceType() { + return getInterfaceType(); + } + + /** + * Returns the interface to use to attach the disk. If not specified, {@link InterfaceType#SCSI} + * is used. + */ + public InterfaceType getInterfaceType() { return interfaceType; } @@ -246,7 +263,15 @@ private Builder(PersistentDiskConfiguration configuration) { /** * Sets the identity of the persistent disk to be attached. */ + @Deprecated public Builder sourceDisk(DiskId sourceDisk) { + return setSourceDisk(sourceDisk); + } + + /** + * Sets the identity of the persistent disk to be attached. + */ + public Builder setSourceDisk(DiskId sourceDisk) { this.sourceDisk = checkNotNull(sourceDisk); return this; } @@ -255,7 +280,16 @@ public Builder sourceDisk(DiskId sourceDisk) { * Sets the mode in which to attach this disk. If not specified, the disk is attached in * {@link Mode#READ_WRITE} mode. */ + @Deprecated public Builder mode(Mode mode) { + return setMode(mode); + } + + /** + * Sets the mode in which to attach this disk. If not specified, the disk is attached in + * {@link Mode#READ_WRITE} mode. + */ + public Builder setMode(Mode mode) { this.mode = mode; return this; } @@ -265,7 +299,17 @@ public Builder mode(Mode mode) { * instance will use the first partition of the disk for its root filesystem. If not * specified, the isk is not used as a boot disk. */ + @Deprecated public Builder boot(boolean boot) { + return setBoot(boot); + } + + /** + * Sets whether to use the attached disk as a boot disk. If {@code true} the virtual machine + * instance will use the first partition of the disk for its root filesystem. If not + * specified, the isk is not used as a boot disk. + */ + public Builder setBoot(boolean boot) { this.boot = boot; return this; } @@ -274,7 +318,16 @@ public Builder boot(boolean boot) { * Sets whether the disk should auto-delete when the instance to which it's attached is * deleted. If not specified, the disk is not deleted automatically. */ + @Deprecated public Builder autoDelete(boolean autoDelete) { + return setAutoDelete(autoDelete); + } + + /** + * Sets whether the disk should auto-delete when the instance to which it's attached is + * deleted. If not specified, the disk is not deleted automatically. + */ + public Builder setAutoDelete(boolean autoDelete) { this.autoDelete = autoDelete; return this; } @@ -296,7 +349,15 @@ private PersistentDiskConfiguration(Builder builder) { /** * Returns the identity of the persistent disk to be attached. */ + @Deprecated public DiskId sourceDisk() { + return getSourceDisk(); + } + + /** + * Returns the identity of the persistent disk to be attached. + */ + public DiskId getSourceDisk() { return sourceDisk; } @@ -304,7 +365,16 @@ public DiskId sourceDisk() { * Returns the mode in which to attach this disk. If not specified, the disk is attached in * {@link Mode#READ_WRITE} mode. */ + @Deprecated public Mode mode() { + return getMode(); + } + + /** + * Returns the mode in which to attach this disk. If not specified, the disk is attached in + * {@link Mode#READ_WRITE} mode. + */ + public Mode getMode() { return mode; } @@ -335,16 +405,16 @@ public boolean equals(Object obj) { @Override PersistentDiskConfiguration setProjectId(String projectId) { - if (sourceDisk.project() != null) { + if (sourceDisk.getProject() != null) { return this; } - return toBuilder().sourceDisk(sourceDisk.setProjectId(projectId)).build(); + return toBuilder().setSourceDisk(sourceDisk.setProjectId(projectId)).build(); } @Override com.google.api.services.compute.model.AttachedDisk toPb() { com.google.api.services.compute.model.AttachedDisk attachedDiskPb = super.toPb(); - attachedDiskPb.setSource(sourceDisk.selfLink()); + attachedDiskPb.setSource(sourceDisk.getSelfLink()); attachedDiskPb.setMode(mode != null ? mode.toString() : null); return attachedDiskPb; } @@ -353,7 +423,16 @@ com.google.api.services.compute.model.AttachedDisk toPb() { * Returns a builder for a {@code PersistentDiskConfiguration} object given the identity of the * persistent disk to attach. */ + @Deprecated public static Builder builder(DiskId sourceDisk) { + return newBuilder(sourceDisk); + } + + /** + * Returns a builder for a {@code PersistentDiskConfiguration} object given the identity of the + * persistent disk to attach. + */ + public static Builder newBuilder(DiskId sourceDisk) { return new Builder(sourceDisk); } @@ -362,7 +441,7 @@ public static Builder builder(DiskId sourceDisk) { * disk to attach. */ public static PersistentDiskConfiguration of(DiskId sourceDisk) { - return builder(sourceDisk).build(); + return newBuilder(sourceDisk).build(); } @SuppressWarnings("unchecked") @@ -370,13 +449,13 @@ static PersistentDiskConfiguration fromPb( com.google.api.services.compute.model.AttachedDisk diskPb) { Builder builder = new Builder(DiskId.fromUrl(diskPb.getSource())); if (diskPb.getMode() != null) { - builder.mode(Mode.valueOf(diskPb.getMode())); + builder.setMode(Mode.valueOf(diskPb.getMode())); } if (diskPb.getBoot() != null) { - builder.boot(diskPb.getBoot()); + builder.setBoot(diskPb.getBoot()); } if (diskPb.getAutoDelete() != null) { - builder.autoDelete(diskPb.getAutoDelete()); + builder.setAutoDelete(diskPb.getAutoDelete()); } return builder.build(); } @@ -425,7 +504,16 @@ private Builder(CreateDiskConfiguration configuration) { * Sets the name to be assigned to the disk. If not specified, the disk is given the * instance's name. */ + @Deprecated public Builder diskName(String diskName) { + return setDiskName(diskName); + } + + /** + * Sets the name to be assigned to the disk. If not specified, the disk is given the + * instance's name. + */ + public Builder setDiskName(String diskName) { this.diskName = diskName; return this; } @@ -433,7 +521,15 @@ public Builder diskName(String diskName) { /** * Sets the identity of the disk type. If not specified, {@code pd-standard} is used. */ + @Deprecated public Builder diskType(DiskTypeId diskType) { + return setDiskType(diskType); + } + + /** + * Sets the identity of the disk type. If not specified, {@code pd-standard} is used. + */ + public Builder setDiskType(DiskTypeId diskType) { this.diskType = diskType; return this; } @@ -443,7 +539,17 @@ public Builder diskType(DiskTypeId diskType) { * source image. This value can be larger than the image's size. If the provided size is * smaller than the image's size, then instance creation will fail. */ + @Deprecated public Builder diskSizeGb(Long diskSizeGb) { + return setDiskSizeGb(diskSizeGb); + } + + /** + * Sets the size of the persistent disk, in GB. If not set the disk will have the size of the + * source image. This value can be larger than the image's size. If the provided size is + * smaller than the image's size, then instance creation will fail. + */ + public Builder setDiskSizeGb(Long diskSizeGb) { this.diskSizeGb = diskSizeGb; return this; } @@ -451,7 +557,15 @@ public Builder diskSizeGb(Long diskSizeGb) { /** * Sets the identity of the source image used to create the disk. */ + @Deprecated public Builder sourceImage(ImageId sourceImage) { + return setSourceImage(sourceImage); + } + + /** + * Sets the identity of the source image used to create the disk. + */ + public Builder setSourceImage(ImageId sourceImage) { this.sourceImage = checkNotNull(sourceImage); return this; } @@ -460,7 +574,16 @@ public Builder sourceImage(ImageId sourceImage) { * Sets whether the disk should auto-delete when the instance to which it's attached is * deleted. If not specified, the disk is not deleted automatically. */ + @Deprecated public Builder autoDelete(Boolean autoDelete) { + return setAutoDelete(autoDelete); + } + + /** + * Sets whether the disk should auto-delete when the instance to which it's attached is + * deleted. If not specified, the disk is not deleted automatically. + */ + public Builder setAutoDelete(Boolean autoDelete) { this.autoDelete = autoDelete; return this; } @@ -485,14 +608,31 @@ private CreateDiskConfiguration(Builder builder) { * Returns the name to be assigned to the disk. If not specified, the disk is given the * instance's name. */ + @Deprecated public String diskName() { + return getDiskName(); + } + + /** + * Returns the name to be assigned to the disk. If not specified, the disk is given the + * instance's name. + */ + public String getDiskName() { return diskName; } /** * Returns the identity of the disk type. If not specified, {@code pd-standard} is used. */ + @Deprecated public DiskTypeId diskType() { + return getDiskType(); + } + + /** + * Returns the identity of the disk type. If not specified, {@code pd-standard} is used. + */ + public DiskTypeId getDiskType() { return diskType; } @@ -501,14 +641,32 @@ public DiskTypeId diskType() { * source image. This value can be larger than the image's size. If the provided size is smaller * than the image's size then instance creation will fail. */ + @Deprecated public Long diskSizeGb() { + return getDiskSizeGb(); + } + + /** + * Returns the size of the persistent disk, in GB. If not set the disk will have the size of the + * source image. This value can be larger than the image's size. If the provided size is smaller + * than the image's size then instance creation will fail. + */ + public Long getDiskSizeGb() { return diskSizeGb; } /** * Returns the identity of the source image used to create the disk. */ + @Deprecated public ImageId sourceImage() { + return getSourceImage(); + } + + /** + * Returns the identity of the source image used to create the disk. + */ + public ImageId getSourceImage() { return sourceImage; } @@ -545,10 +703,10 @@ public boolean equals(Object obj) { CreateDiskConfiguration setProjectId(String projectId) { Builder builder = toBuilder(); if (builder.diskType != null) { - builder.diskType(diskType.setProjectId(projectId)); + builder.setDiskType(diskType.setProjectId(projectId)); } if (builder.sourceImage != null) { - builder.sourceImage(sourceImage.setProjectId(projectId)); + builder.setSourceImage(sourceImage.setProjectId(projectId)); } return builder.build(); } @@ -558,9 +716,9 @@ com.google.api.services.compute.model.AttachedDisk toPb() { AttachedDiskInitializeParams initializeParamsPb = new AttachedDiskInitializeParams(); initializeParamsPb.setDiskName(diskName); initializeParamsPb.setDiskSizeGb(diskSizeGb); - initializeParamsPb.setSourceImage(sourceImage.selfLink()); + initializeParamsPb.setSourceImage(sourceImage.getSelfLink()); if (diskType != null) { - initializeParamsPb.setDiskType(diskType.selfLink()); + initializeParamsPb.setDiskType(diskType.getSelfLink()); } com.google.api.services.compute.model.AttachedDisk attachedDiskPb = super.toPb(); attachedDiskPb.setInitializeParams(initializeParamsPb); @@ -571,7 +729,16 @@ com.google.api.services.compute.model.AttachedDisk toPb() { * Returns a builder for a {@code CreateDiskConfiguration} object given the source image that * will be used to create the disk. */ + @Deprecated public static Builder builder(ImageId sourceImage) { + return newBuilder(sourceImage); + } + + /** + * Returns a builder for a {@code CreateDiskConfiguration} object given the source image that + * will be used to create the disk. + */ + public static Builder newBuilder(ImageId sourceImage) { return new Builder(sourceImage); } @@ -580,22 +747,22 @@ public static Builder builder(ImageId sourceImage) { * create the disk. */ public static CreateDiskConfiguration of(ImageId sourceImage) { - return builder(sourceImage).build(); + return newBuilder(sourceImage).build(); } @SuppressWarnings("unchecked") static CreateDiskConfiguration fromPb( com.google.api.services.compute.model.AttachedDisk diskPb) { AttachedDiskInitializeParams initializeParamsPb = diskPb.getInitializeParams(); - Builder builder = builder(ImageId.fromUrl(initializeParamsPb.getSourceImage())); + Builder builder = newBuilder(ImageId.fromUrl(initializeParamsPb.getSourceImage())); if (initializeParamsPb.getDiskType() != null) { - builder.diskType(DiskTypeId.fromUrl(initializeParamsPb.getDiskType())); + builder.setDiskType(DiskTypeId.fromUrl(initializeParamsPb.getDiskType())); } - builder.diskName(initializeParamsPb.getDiskName()); - builder.diskSizeGb(initializeParamsPb.getDiskSizeGb()); - builder.autoDelete(diskPb.getAutoDelete()); + builder.setDiskName(initializeParamsPb.getDiskName()); + builder.setDiskSizeGb(initializeParamsPb.getDiskSizeGb()); + builder.setAutoDelete(diskPb.getAutoDelete()); if (initializeParamsPb.getDiskType() != null) { - builder.diskType(DiskTypeId.fromUrl(initializeParamsPb.getDiskType())); + builder.setDiskType(DiskTypeId.fromUrl(initializeParamsPb.getDiskType())); } return builder.build(); } @@ -623,13 +790,21 @@ private Builder() {} private Builder(ScratchDiskConfiguration configuration) { this.diskType = configuration.diskType; - this.interfaceType = configuration.interfaceType(); + this.interfaceType = configuration.getInterfaceType(); } /** * Sets the identity of the disk type for the scratch disk to attach. */ + @Deprecated public Builder diskType(DiskTypeId diskType) { + return setDiskType(diskType); + } + + /** + * Sets the identity of the disk type for the scratch disk to attach. + */ + public Builder setDiskType(DiskTypeId diskType) { this.diskType = diskType; return this; } @@ -637,7 +812,15 @@ public Builder diskType(DiskTypeId diskType) { /** * Sets the interface type. If not specified, {@code SCSI} is used. */ + @Deprecated public Builder interfaceType(InterfaceType interfaceType) { + return setInterfaceType(interfaceType); + } + + /** + * Sets the interface type. If not specified, {@code SCSI} is used. + */ + public Builder setInterfaceType(InterfaceType interfaceType) { this.interfaceType = interfaceType; return this; } @@ -658,10 +841,18 @@ private ScratchDiskConfiguration(Builder builder) { /** * Returns the identity of the disk type for the scratch disk to attach. */ + @Deprecated public DiskTypeId diskType() { return diskType; } + /** + * Returns the identity of the disk type for the scratch disk to attach. + */ + public DiskTypeId getDiskType() { + return diskType; + } + /** * Returns a builder for the current configuration. */ @@ -689,10 +880,10 @@ public boolean equals(Object obj) { @Override ScratchDiskConfiguration setProjectId(String projectId) { - if (diskType.project() != null) { + if (diskType.getProject() != null) { return this; } - return toBuilder().diskType(diskType.setProjectId(projectId)).build(); + return toBuilder().setDiskType(diskType.setProjectId(projectId)).build(); } @Override @@ -700,7 +891,7 @@ com.google.api.services.compute.model.AttachedDisk toPb() { com.google.api.services.compute.model.AttachedDisk attachedDiskPb = super.toPb(); if (diskType != null) { AttachedDiskInitializeParams initializeParamsPb = new AttachedDiskInitializeParams(); - initializeParamsPb.setDiskType(diskType.selfLink()); + initializeParamsPb.setDiskType(diskType.getSelfLink()); attachedDiskPb.setInitializeParams(initializeParamsPb); } return attachedDiskPb; @@ -709,8 +900,16 @@ com.google.api.services.compute.model.AttachedDisk toPb() { /** * Returns a builder for {@code ScratchDiskConfiguration} objects given the disk type identity. */ + @Deprecated public static Builder builder(DiskTypeId diskType) { - return new Builder().diskType(diskType); + return newBuilder(diskType); + } + + /** + * Returns a builder for {@code ScratchDiskConfiguration} objects given the disk type identity. + */ + public static Builder newBuilder(DiskTypeId diskType) { + return new Builder().setDiskType(diskType); } /** @@ -718,7 +917,7 @@ public static Builder builder(DiskTypeId diskType) { * be attached via the default interface ({@link InterfaceType#SCSI}). */ public static ScratchDiskConfiguration of(DiskTypeId diskType) { - return builder(diskType).build(); + return newBuilder(diskType).build(); } @SuppressWarnings("unchecked") @@ -726,11 +925,11 @@ static ScratchDiskConfiguration fromPb( com.google.api.services.compute.model.AttachedDisk diskPb) { Builder builder = new Builder(); if (diskPb.getInterface() != null) { - builder.interfaceType(InterfaceType.valueOf(diskPb.getInterface())); + builder.setInterfaceType(InterfaceType.valueOf(diskPb.getInterface())); } if (diskPb.getInitializeParams() != null && diskPb.getInitializeParams().getDiskType() != null) { - builder.diskType(DiskTypeId.fromUrl(diskPb.getInitializeParams().getDiskType())); + builder.setDiskType(DiskTypeId.fromUrl(diskPb.getInitializeParams().getDiskType())); } return builder.build(); } @@ -765,7 +964,20 @@ public static final class Builder { * apply to this disk, in the form {@code persistent-disks-x}, where x is a number assigned by * Google Compute Engine. */ + @Deprecated public Builder deviceName(String deviceName) { + return setDeviceName(deviceName); + } + + /** + * Sets the unique device name of your choice that is reflected into the + * {@code /dev/disk/by-id/google-*} tree of a Linux operating system running within the + * instance. This name can be used to reference the device for mounting, resizing, and so on, + * from within the instance. If not specified, the service chooses a default device name to + * apply to this disk, in the form {@code persistent-disks-x}, where x is a number assigned by + * Google Compute Engine. + */ + public Builder setDeviceName(String deviceName) { this.deviceName = deviceName; return this; } @@ -775,7 +987,17 @@ public Builder deviceName(String deviceName) { * if you have many disks attached to an instance, each disk would have an unique index number. * If not specified, the service will choose an appropriate value. */ + @Deprecated public Builder index(Integer index) { + return setIndex(index); + } + + /** + * Sets a zero-based index to this disk, where 0 is reserved for the boot disk. For example, + * if you have many disks attached to an instance, each disk would have an unique index number. + * If not specified, the service will choose an appropriate value. + */ + public Builder setIndex(Integer index) { this.index = index; return this; } @@ -786,12 +1008,23 @@ public Builder index(Integer index) { * persistent disk to the instance. Use {@link CreateDiskConfiguration} to create and attach * a new persistent disk. */ + @Deprecated public Builder configuration(AttachedDiskConfiguration configuration) { + return setConfiguration(configuration); + } + + /** + * Sets the attached disk configuration. Use {@link ScratchDiskConfiguration} to attach a + * scratch disk to the instance. Use {@link PersistentDiskConfiguration} to attach a + * persistent disk to the instance. Use {@link CreateDiskConfiguration} to create and attach + * a new persistent disk. + */ + public Builder setConfiguration(AttachedDiskConfiguration configuration) { this.configuration = checkNotNull(configuration); return this; } - Builder licenses(List licenses) { + Builder setLicenses(List licenses) { this.licenses = licenses; return this; } @@ -819,14 +1052,35 @@ private AttachedDisk(Builder builder) { * apply to this disk, in the form {@code persistent-disks-x}, where x is a number assigned by * Google Compute Engine. */ + @Deprecated public String deviceName() { + return getDeviceName(); + } + + /** + * Returns the unique device name of your choice that is reflected into the + * {@code /dev/disk/by-id/google-*} tree of a Linux operating system running within the + * instance. This name can be used to reference the device for mounting, resizing, and so on, + * from within the instance. If not specified, the service chooses a default device name to + * apply to this disk, in the form {@code persistent-disks-x}, where x is a number assigned by + * Google Compute Engine. + */ + public String getDeviceName() { return deviceName; } /** * Returns a zero-based index to this disk, where 0 is reserved for the boot disk. */ + @Deprecated public Integer index() { + return getIndex(); + } + + /** + * Returns a zero-based index to this disk, where 0 is reserved for the boot disk. + */ + public Integer getIndex() { return index; } @@ -837,14 +1091,34 @@ public Integer index() { * a new persistent disk. */ @SuppressWarnings("unchecked") + @Deprecated public T configuration() { + return getConfiguration(); + } + + /** + * Returns the attached disk configuration. Returns {@link ScratchDiskConfiguration} to attach a + * scratch disk to the instance. Returns {@link PersistentDiskConfiguration} to attach a + * persistent disk to the instance. Returns {@link CreateDiskConfiguration} to create and attach + * a new persistent disk. + */ + @SuppressWarnings("unchecked") + public T getConfiguration() { return (T) configuration; } /** * Returns a list of publicly accessible licenses for the attached disk. */ + @Deprecated public List licenses() { + return getLicenses(); + } + + /** + * Returns a list of publicly accessible licenses for the attached disk. + */ + public List getLicenses() { return licenses; } @@ -879,7 +1153,7 @@ public final boolean equals(Object obj) { } AttachedDisk setProjectId(String projectId) { - return toBuilder().configuration(configuration.setProjectId(projectId)).build(); + return toBuilder().setConfiguration(configuration.setProjectId(projectId)).build(); } com.google.api.services.compute.model.AttachedDisk toPb() { @@ -895,31 +1169,39 @@ com.google.api.services.compute.model.AttachedDisk toPb() { /** * Returns a builder for an {@code AttachedDisk} object given its configuration. */ + @Deprecated public static Builder builder(AttachedDiskConfiguration configuration) { - return new Builder(configuration).configuration(configuration); + return newBuilder(configuration); + } + + /** + * Returns a builder for an {@code AttachedDisk} object given its configuration. + */ + public static Builder newBuilder(AttachedDiskConfiguration configuration) { + return new Builder(configuration); } /** * Returns an {@code AttachedDisk} object given its configuration. */ public static AttachedDisk of(AttachedDiskConfiguration configuration) { - return builder(configuration).build(); + return newBuilder(configuration).build(); } /** * Returns an {@code AttachedDisk} object given the device name and its configuration. */ public static AttachedDisk of(String deviceName, AttachedDiskConfiguration configuration) { - return builder(configuration).deviceName(deviceName).build(); + return newBuilder(configuration).setDeviceName(deviceName).build(); } static AttachedDisk fromPb(com.google.api.services.compute.model.AttachedDisk diskPb) { AttachedDiskConfiguration configuration = AttachedDiskConfiguration.fromPb(diskPb); - Builder builder = builder(configuration); - builder.deviceName(diskPb.getDeviceName()); - builder.index(diskPb.getIndex()); + Builder builder = newBuilder(configuration); + builder.setDeviceName(diskPb.getDeviceName()); + builder.setIndex(diskPb.getIndex()); if (diskPb.getLicenses() != null) { - builder.licenses(Lists.transform(diskPb.getLicenses(), LicenseId.FROM_URL_FUNCTION)); + builder.setLicenses(Lists.transform(diskPb.getLicenses(), LicenseId.FROM_URL_FUNCTION)); } return builder.build(); } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeImpl.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeImpl.java index 23501f93bcc6..637b47cc6ff6 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeImpl.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeImpl.java @@ -469,7 +469,7 @@ public DiskType getDiskType(final DiskTypeId diskTypeId, DiskTypeOption... optio runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.DiskType call() { - return computeRpc.getDiskType(diskTypeId.zone(), diskTypeId.type(), optionsMap); + return computeRpc.getDiskType(diskTypeId.getZone(), diskTypeId.getType(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : DiskType.fromPb(answer); @@ -557,7 +557,8 @@ public MachineType getMachineType(final MachineTypeId machineType, MachineTypeOp runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.MachineType call() { - return computeRpc.getMachineType(machineType.zone(), machineType.type(), optionsMap); + return computeRpc.getMachineType(machineType.getZone(), machineType.getType(), + optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : MachineType.fromPb(answer); @@ -755,7 +756,8 @@ public License getLicense(LicenseId license, LicenseOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.License call() { - return computeRpc.getLicense(completeId.project(), completeId.license(), optionsMap); + return computeRpc.getLicense(completeId.getProject(), completeId.getLicense(), + optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : License.fromPb(answer); @@ -772,17 +774,17 @@ public Operation getOperation(final OperationId operationId, OperationOption... runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - switch (operationId.type()) { + switch (operationId.getType()) { case REGION: RegionOperationId regionOperationId = (RegionOperationId) operationId; - return computeRpc.getRegionOperation(regionOperationId.region(), - regionOperationId.operation(), optionsMap); + return computeRpc.getRegionOperation(regionOperationId.getRegion(), + regionOperationId.getOperation(), optionsMap); case ZONE: ZoneOperationId zoneOperationId = (ZoneOperationId) operationId; - return computeRpc.getZoneOperation(zoneOperationId.zone(), - zoneOperationId.operation(), optionsMap); + return computeRpc.getZoneOperation(zoneOperationId.getZone(), + zoneOperationId.getOperation(), optionsMap); case GLOBAL: - return computeRpc.getGlobalOperation(operationId.operation(), optionsMap); + return computeRpc.getGlobalOperation(operationId.getOperation(), optionsMap); default: throw new IllegalArgumentException("Unexpected operation identity type"); } @@ -894,17 +896,17 @@ public boolean deleteOperation(final OperationId operation) { return runWithRetries(new Callable() { @Override public Boolean call() { - switch (operation.type()) { + switch (operation.getType()) { case REGION: RegionOperationId regionOperationId = (RegionOperationId) operation; - return computeRpc.deleteRegionOperation(regionOperationId.region(), - regionOperationId.operation()); + return computeRpc.deleteRegionOperation(regionOperationId.getRegion(), + regionOperationId.getOperation()); case ZONE: ZoneOperationId zoneOperationId = (ZoneOperationId) operation; - return computeRpc.deleteZoneOperation(zoneOperationId.zone(), - zoneOperationId.operation()); + return computeRpc.deleteZoneOperation(zoneOperationId.getZone(), + zoneOperationId.getOperation()); case GLOBAL: - return computeRpc.deleteGlobalOperation(operation.operation()); + return computeRpc.deleteGlobalOperation(operation.getOperation()); default: throw new IllegalArgumentException("Unexpected operation identity type"); } @@ -923,13 +925,13 @@ public Address getAddress(final AddressId addressId, AddressOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Address call() { - switch (addressId.type()) { + switch (addressId.getType()) { case REGION: RegionAddressId regionAddressId = (RegionAddressId) addressId; - return computeRpc.getRegionAddress(regionAddressId.region(), - regionAddressId.address(), optionsMap); + return computeRpc.getRegionAddress(regionAddressId.getRegion(), + regionAddressId.getAddress(), optionsMap); case GLOBAL: - return computeRpc.getGlobalAddress(addressId.address(), optionsMap); + return computeRpc.getGlobalAddress(addressId.getAddress(), optionsMap); default: throw new IllegalArgumentException("Unexpected address identity type"); } @@ -951,10 +953,10 @@ public Operation create(final AddressInfo address, OperationOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - switch (address.addressId().type()) { + switch (address.getAddressId().getType()) { case REGION: - RegionAddressId regionAddressId = address.addressId(); - return computeRpc.createRegionAddress(regionAddressId.region(), addressPb, + RegionAddressId regionAddressId = address.getAddressId(); + return computeRpc.createRegionAddress(regionAddressId.getRegion(), addressPb, optionsMap); case GLOBAL: return computeRpc.createGlobalAddress(addressPb, optionsMap); @@ -1076,13 +1078,13 @@ public Operation deleteAddress(final AddressId addressId, OperationOption... opt runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - switch (addressId.type()) { + switch (addressId.getType()) { case REGION: RegionAddressId regionAddressId = (RegionAddressId) addressId; - return computeRpc.deleteRegionAddress(regionAddressId.region(), - regionAddressId.address(), optionsMap); + return computeRpc.deleteRegionAddress(regionAddressId.getRegion(), + regionAddressId.getAddress(), optionsMap); case GLOBAL: - return computeRpc.deleteGlobalAddress(addressId.address(), optionsMap); + return computeRpc.deleteGlobalAddress(addressId.getAddress(), optionsMap); default: throw new IllegalArgumentException("Unexpected address identity type"); } @@ -1103,9 +1105,10 @@ public Operation create(SnapshotInfo snapshot, OperationOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.createSnapshot(completeSnapshot.sourceDisk().zone(), - completeSnapshot.sourceDisk().disk(), completeSnapshot.snapshotId().snapshot(), - completeSnapshot.description(), optionsMap); + return computeRpc.createSnapshot(completeSnapshot.getSourceDisk().getZone(), + completeSnapshot.getSourceDisk().getDisk(), + completeSnapshot.getSnapshotId().getSnapshot(), completeSnapshot.getDescription(), + optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Operation.fromPb(this, answer); @@ -1167,7 +1170,7 @@ public Snapshot apply(com.google.api.services.compute.model.Snapshot snapshot) { @Override public Operation deleteSnapshot(SnapshotId snapshot, OperationOption... options) { - return deleteSnapshot(snapshot.snapshot(), options); + return deleteSnapshot(snapshot.getSnapshot(), options); } @Override @@ -1214,7 +1217,7 @@ public Image getImage(ImageId imageId, ImageOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Image call() { - return computeRpc.getImage(completeImageId.project(), completeImageId.image(), + return computeRpc.getImage(completeImageId.getProject(), completeImageId.getImage(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -1272,7 +1275,8 @@ public Operation deleteImage(ImageId image, OperationOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.deleteImage(completeId.project(), completeId.image(), optionsMap); + return computeRpc.deleteImage(completeId.getProject(), completeId.getImage(), + optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Operation.fromPb(this, answer); @@ -1291,7 +1295,7 @@ public Operation deprecate(ImageId image, runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.deprecateImage(completeId.project(), completeId.image(), + return computeRpc.deprecateImage(completeId.getProject(), completeId.getImage(), deprecationStatus.toPb(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -1309,7 +1313,7 @@ public Disk getDisk(final DiskId diskId, DiskOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Disk call() { - return computeRpc.getDisk(diskId.zone(), diskId.disk(), optionsMap); + return computeRpc.getDisk(diskId.getZone(), diskId.getDisk(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Disk.fromPb(this, answer); @@ -1328,7 +1332,7 @@ public Operation create(final DiskInfo disk, OperationOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.createDisk(disk.diskId().zone(), diskPb, optionsMap); + return computeRpc.createDisk(disk.getDiskId().getZone(), diskPb, optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); } catch (RetryHelper.RetryHelperException e) { @@ -1410,7 +1414,7 @@ public Operation deleteDisk(final DiskId disk, OperationOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.deleteDisk(disk.zone(), disk.disk(), optionsMap); + return computeRpc.deleteDisk(disk.getZone(), disk.getDisk(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Operation.fromPb(this, answer); @@ -1427,7 +1431,7 @@ public Operation resize(final DiskId disk, final long sizeGb, OperationOption... runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.resizeDisk(disk.zone(), disk.disk(), sizeGb, optionsMap); + return computeRpc.resizeDisk(disk.getZone(), disk.getDisk(), sizeGb, optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Operation.fromPb(this, answer); @@ -1444,7 +1448,7 @@ public Operation create(SubnetworkInfo subnetwork, OperationOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.createSubnetwork(completeSubnetwork.subnetworkId().region(), + return computeRpc.createSubnetwork(completeSubnetwork.getSubnetworkId().getRegion(), completeSubnetwork.toPb(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -1462,8 +1466,8 @@ public Subnetwork getSubnetwork(final SubnetworkId subnetworkId, SubnetworkOptio runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Subnetwork call() { - return computeRpc.getSubnetwork(subnetworkId.region(), subnetworkId.subnetwork(), - optionsMap); + return computeRpc.getSubnetwork(subnetworkId.getRegion(), + subnetworkId.getSubnetwork(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Subnetwork.fromPb(this, answer); @@ -1546,7 +1550,7 @@ public Operation deleteSubnetwork(final SubnetworkId subnetwork, OperationOption runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.deleteSubnetwork(subnetwork.region(), subnetwork.subnetwork(), + return computeRpc.deleteSubnetwork(subnetwork.getRegion(), subnetwork.getSubnetwork(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -1633,7 +1637,7 @@ public Operation deleteNetwork(final NetworkId network, OperationOption... optio runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.deleteNetwork(network.network(), optionsMap); + return computeRpc.deleteNetwork(network.getNetwork(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Operation.fromPb(this, answer); @@ -1656,7 +1660,7 @@ public Operation create(InstanceInfo instance, OperationOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.createInstance(completeInstance.instanceId().zone(), + return computeRpc.createInstance(completeInstance.getInstanceId().getZone(), completeInstance.toPb(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -1674,7 +1678,7 @@ public Instance getInstance(final InstanceId instance, InstanceOption... options runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Instance call() { - return computeRpc.getInstance(instance.zone(), instance.instance(), optionsMap); + return computeRpc.getInstance(instance.getZone(), instance.getInstance(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Instance.fromPb(this, answer); @@ -1757,7 +1761,8 @@ public Operation deleteInstance(final InstanceId instance, OperationOption... op runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.deleteInstance(instance.zone(), instance.instance(), optionsMap); + return computeRpc.deleteInstance(instance.getZone(), instance.getInstance(), + optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Operation.fromPb(this, answer); @@ -1775,7 +1780,7 @@ public Operation addAccessConfig(final InstanceId instance, final String network runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.addAccessConfig(instance.zone(), instance.instance(), + return computeRpc.addAccessConfig(instance.getZone(), instance.getInstance(), networkInterface, accessConfig.toPb(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -1794,7 +1799,7 @@ private Operation attachDisk(final InstanceId instance, AttachedDisk diskToAttac runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.attachDisk(instance.zone(), instance.instance(), + return computeRpc.attachDisk(instance.getZone(), instance.getInstance(), completeDisk.toPb(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -1819,9 +1824,9 @@ public Operation attachDisk(InstanceId instance, String deviceName, @Override public Operation attachDisk(InstanceId instance, String deviceName, PersistentDiskConfiguration configuration, int index, OperationOption... options) { - AttachedDisk attachedDisk = AttachedDisk.builder(configuration) - .deviceName(deviceName) - .index(index) + AttachedDisk attachedDisk = AttachedDisk.newBuilder(configuration) + .setDeviceName(deviceName) + .setIndex(index) .build(); return attachDisk(instance, attachedDisk, options); } @@ -1835,7 +1840,7 @@ public Operation deleteAccessConfig(final InstanceId instance, final String netw runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.deleteAccessConfig(instance.zone(), instance.instance(), + return computeRpc.deleteAccessConfig(instance.getZone(), instance.getInstance(), networkInterface, accessConfig, optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -1854,7 +1859,7 @@ public Operation detachDisk(final InstanceId instance, final String deviceName, runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.detachDisk(instance.zone(), instance.instance(), deviceName, + return computeRpc.detachDisk(instance.getZone(), instance.getInstance(), deviceName, optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -1870,7 +1875,7 @@ public String getSerialPortOutput(final InstanceId instance, final int port) { return runWithRetries(new Callable() { @Override public String call() { - return computeRpc.getSerialPortOutput(instance.zone(), instance.instance(), port, + return computeRpc.getSerialPortOutput(instance.getZone(), instance.getInstance(), port, optionMap()); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -1885,7 +1890,7 @@ public String getSerialPortOutput(final InstanceId instance) { return runWithRetries(new Callable() { @Override public String call() { - return computeRpc.getSerialPortOutput(instance.zone(), instance.instance(), null, + return computeRpc.getSerialPortOutput(instance.getZone(), instance.getInstance(), null, optionMap()); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -1902,7 +1907,7 @@ public Operation reset(final InstanceId instance, OperationOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.reset(instance.zone(), instance.instance(), optionsMap); + return computeRpc.reset(instance.getZone(), instance.getInstance(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Operation.fromPb(this, answer); @@ -1920,8 +1925,8 @@ public Operation setDiskAutoDelete(final InstanceId instance, final String devic runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.setDiskAutoDelete(instance.zone(), instance.instance(), deviceName, - autoDelete, optionsMap); + return computeRpc.setDiskAutoDelete(instance.getZone(), instance.getInstance(), + deviceName, autoDelete, optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Operation.fromPb(this, answer); @@ -1933,15 +1938,15 @@ public com.google.api.services.compute.model.Operation call() { @Override public Operation setMachineType(final InstanceId instance, final MachineTypeId machineType, OperationOption... options) { - final String machineTypeUrl = machineType.setProjectId(options().projectId()).selfLink(); + final String machineTypeUrl = machineType.setProjectId(options().projectId()).getSelfLink(); final Map optionsMap = optionMap(options); try { com.google.api.services.compute.model.Operation answer = runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.setMachineType(instance.zone(), instance.instance(), machineTypeUrl, - optionsMap); + return computeRpc.setMachineType(instance.getZone(), instance.getInstance(), + machineTypeUrl, optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Operation.fromPb(this, answer); @@ -1959,8 +1964,8 @@ public Operation setMetadata(final InstanceId instance, final Metadata metadata, runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.setMetadata(instance.zone(), instance.instance(), metadata.toPb(), - optionsMap); + return computeRpc.setMetadata(instance.getZone(), instance.getInstance(), + metadata.toPb(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Operation.fromPb(this, answer); @@ -1978,7 +1983,7 @@ public Operation setSchedulingOptions(final InstanceId instance, runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.setScheduling(instance.zone(), instance.instance(), + return computeRpc.setScheduling(instance.getZone(), instance.getInstance(), schedulingOptions.toPb(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -1996,7 +2001,7 @@ public Operation setTags(final InstanceId instance, final Tags tags, OperationOp runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.setTags(instance.zone(), instance.instance(), tags.toPb(), + return computeRpc.setTags(instance.getZone(), instance.getInstance(), tags.toPb(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); @@ -2014,7 +2019,7 @@ public Operation start(final InstanceId instance, OperationOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.start(instance.zone(), instance.instance(), optionsMap); + return computeRpc.start(instance.getZone(), instance.getInstance(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Operation.fromPb(this, answer); @@ -2031,7 +2036,7 @@ public Operation stop(final InstanceId instance, OperationOption... options) { runWithRetries(new Callable() { @Override public com.google.api.services.compute.model.Operation call() { - return computeRpc.stop(instance.zone(), instance.instance(), optionsMap); + return computeRpc.stop(instance.getZone(), instance.getInstance(), optionsMap); } }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); return answer == null ? null : Operation.fromPb(this, answer); @@ -2043,7 +2048,7 @@ public com.google.api.services.compute.model.Operation call() { private Map optionMap(Option... options) { Map optionMap = Maps.newEnumMap(ComputeRpc.Option.class); for (Option option : options) { - Object prev = optionMap.put(option.rpcOption(), option.value()); + Object prev = optionMap.put(option.getRpcOption(), option.getValue()); checkArgument(prev == null, "Duplicate option %s", option); } return optionMap; diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/DeprecationStatus.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/DeprecationStatus.java index 44174c66da15..2e8a720d0c26 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/DeprecationStatus.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/DeprecationStatus.java @@ -97,7 +97,7 @@ public static final class Builder { * @see RFC3339 */ // Wrongly-formatted timestamps were allowed, we must still support them (see #732 for details) - Builder deleted(String deleted) { + Builder setDeleted(String deleted) { this.deleted = deleted; return this; } @@ -109,7 +109,7 @@ Builder deleted(String deleted) { * @see RFC3339 */ // Wrongly-formatted timestamps were allowed, we must still support them (see #732 for details) - Builder deprecated(String deprecated) { + Builder setDeprecated(String deprecated) { this.deprecated = deprecated; return this; } @@ -121,7 +121,7 @@ Builder deprecated(String deprecated) { * @see RFC3339 */ // Wrongly-formatted timestamps were allowed, we must still support them (see #732 for details) - Builder obsolete(String obsolete) { + Builder setObsolete(String obsolete) { this.obsolete = obsolete; return this; } @@ -130,7 +130,16 @@ Builder obsolete(String obsolete) { * Sets the timestamp on or after which the deprecation state of this resource will be changed * to {@link Status#DELETED}. In milliseconds since epoch. */ + @Deprecated public Builder deleted(long deleted) { + return setDeleted(deleted); + } + + /** + * Sets the timestamp on or after which the deprecation state of this resource will be changed + * to {@link Status#DELETED}. In milliseconds since epoch. + */ + public Builder setDeleted(long deleted) { this.deleted = TIMESTAMP_FORMATTER.print(deleted); return this; } @@ -139,7 +148,16 @@ public Builder deleted(long deleted) { * Sets the timestamp on or after which the deprecation state of this resource will be changed * to {@link Status#DEPRECATED}. In milliseconds since epoch. */ + @Deprecated public Builder deprecated(long deprecated) { + return setDeprecated(deprecated); + } + + /** + * Sets the timestamp on or after which the deprecation state of this resource will be changed + * to {@link Status#DEPRECATED}. In milliseconds since epoch. + */ + public Builder setDeprecated(long deprecated) { this.deprecated = TIMESTAMP_FORMATTER.print(deprecated); return this; } @@ -148,7 +166,16 @@ public Builder deprecated(long deprecated) { * Sets the timestamp on or after which the deprecation state of this resource will be changed * to {@link Status#OBSOLETE}. In milliseconds since epoch. */ + @Deprecated public Builder obsolete(long obsolete) { + return setObsolete(obsolete); + } + + /** + * Sets the timestamp on or after which the deprecation state of this resource will be changed + * to {@link Status#OBSOLETE}. In milliseconds since epoch. + */ + public Builder setObsolete(long obsolete) { this.obsolete = TIMESTAMP_FORMATTER.print(obsolete); return this; } @@ -157,7 +184,16 @@ public Builder obsolete(long obsolete) { * Sets the identity of the suggested replacement for a deprecated resource. The suggested * replacement resource must be the same kind of resource as the deprecated resource. */ + @Deprecated public Builder replacement(T replacement) { + return setReplacement(replacement); + } + + /** + * Sets the identity of the suggested replacement for a deprecated resource. The suggested + * replacement resource must be the same kind of resource as the deprecated resource. + */ + public Builder setReplacement(T replacement) { this.replacement = replacement; return this; } @@ -165,7 +201,15 @@ public Builder replacement(T replacement) { /** * Sets the status of the deprecated resource. */ + @Deprecated public Builder status(Status status) { + return setStatus(status); + } + + /** + * Sets the status of the deprecated resource. + */ + public Builder setStatus(Status status) { this.status = checkNotNull(status); return this; } @@ -194,7 +238,20 @@ public DeprecationStatus build() { * @see RFC3339 */ // Wrongly-formatted timestamps were allowed, we must still support them (see #732 for details) + @Deprecated public String deleted() { + return getDeleted(); + } + + /** + * Returns the timestamp on or after which the deprecation state of this resource will be changed + * to {@link Status#DELETED}. Returns {@code null} if not set. This value should be in RFC3339 + * format. + * + * @see RFC3339 + */ + // Wrongly-formatted timestamps were allowed, we must still support them (see #732 for details) + public String getDeleted() { return deleted; } @@ -206,7 +263,20 @@ public String deleted() { * @see RFC3339 */ // Wrongly-formatted timestamps were allowed, we must still support them (see #732 for details) + @Deprecated public String deprecated() { + return getDeprecated(); + } + + /** + * Returns the timestamp on or after which the deprecation state of this resource will be changed + * to {@link Status#DEPRECATED}. Returns {@code null} if not set. This value should be in RFC3339 + * format. + * + * @see RFC3339 + */ + // Wrongly-formatted timestamps were allowed, we must still support them (see #732 for details) + public String getDeprecated() { return deprecated; } @@ -218,7 +288,20 @@ public String deprecated() { * @see RFC3339 */ // Wrongly-formatted timestamps were allowed, we must still support them (see #732 for details) + @Deprecated public String obsolete() { + return getObsolete(); + } + + /** + * Returns the timestamp on or after which the deprecation state of this resource will be changed + * to {@link Status#OBSOLETE}. Returns {@code null} if not set. This value should be in RFC3339 + * format. + * + * @see RFC3339 + */ + // Wrongly-formatted timestamps were allowed, we must still support them (see #732 for details) + public String getObsolete() { return obsolete; } @@ -228,7 +311,18 @@ public String obsolete() { * * @throws IllegalStateException if {@link #deleted()} is not a valid date, time or datetime */ + @Deprecated public Long deletedMillis() { + return getDeletedMillis(); + } + + /** + * Returns the timestamp (in milliseconds since epoch) on or after which the deprecation state of + * this resource will be changed to {@link Status#DELETED}. Returns {@code null} if not set. + * + * @throws IllegalStateException if {@link #deleted()} is not a valid date, time or datetime + */ + public Long getDeletedMillis() { try { return deleted != null ? TIMESTAMP_PARSER.parseMillis(deleted) : null; } catch (IllegalArgumentException ex) { @@ -242,7 +336,18 @@ public Long deletedMillis() { * * @throws IllegalStateException if {@link #deprecated()} is not a valid date, time or datetime */ + @Deprecated public Long deprecatedMillis() { + return getDeprecatedMillis(); + } + + /** + * Returns the timestamp (in milliseconds since epoch) on or after which the deprecation state of + * this resource will be changed to {@link Status#DEPRECATED}. Returns {@code null} if not set. + * + * @throws IllegalStateException if {@link #deprecated()} is not a valid date, time or datetime + */ + public Long getDeprecatedMillis() { try { return deprecated != null ? TIMESTAMP_PARSER.parseMillis(deprecated) : null; } catch (IllegalArgumentException ex) { @@ -256,7 +361,18 @@ public Long deprecatedMillis() { * * @throws IllegalStateException if {@link #obsolete()} is not a valid date, time or datetime */ + @Deprecated public Long obsoleteMillis() { + return getObsoleteMillis(); + } + + /** + * Returns the timestamp (in milliseconds since epoch) on or after which the deprecation state of + * this resource will be changed to {@link Status#OBSOLETE}. Returns {@code null} if not set. + * + * @throws IllegalStateException if {@link #obsolete()} is not a valid date, time or datetime + */ + public Long getObsoleteMillis() { try { return obsolete != null ? TIMESTAMP_PARSER.parseMillis(obsolete) : null; } catch (IllegalArgumentException ex) { @@ -268,14 +384,31 @@ public Long obsoleteMillis() { * Returns the identity of the suggested replacement for a deprecated resource. The suggested * replacement resource must be the same kind of resource as the deprecated resource. */ + @Deprecated public T replacement() { + return getReplacement(); + } + + /** + * Returns the identity of the suggested replacement for a deprecated resource. The suggested + * replacement resource must be the same kind of resource as the deprecated resource. + */ + public T getReplacement() { return replacement; } /** * Returns the deprecation state of this resource. */ + @Deprecated public Status status() { + return getStatus(); + } + + /** + * Returns the deprecation state of this resource. + */ + public Status getStatus() { return status; } @@ -315,7 +448,7 @@ com.google.api.services.compute.model.DeprecationStatus toPb() { deprecationStatusPb.setDeleted(deleted); deprecationStatusPb.setDeprecated(deprecated); deprecationStatusPb.setObsolete(obsolete); - deprecationStatusPb.setReplacement(replacement.selfLink()); + deprecationStatusPb.setReplacement(replacement.getSelfLink()); deprecationStatusPb.setState(status.name()); return deprecationStatusPb; } @@ -323,37 +456,54 @@ com.google.api.services.compute.model.DeprecationStatus toPb() { /** * Returns the builder for a {@code DeprecationStatus} object given the status. */ + @Deprecated public static Builder builder(Status status) { - return new Builder().status(status); + return newBuilder(status); + } + + /** + * Returns the builder for a {@code DeprecationStatus} object given the status. + */ + public static Builder newBuilder(Status status) { + return new Builder().setStatus(status); } /** * Returns the builder for a {@code DeprecationStatus} object given the status and replacement's * identity. */ + @Deprecated public static Builder builder(Status status, T replacement) { - return new Builder().status(status).replacement(replacement); + return newBuilder(status, replacement); + } + + /** + * Returns the builder for a {@code DeprecationStatus} object given the status and replacement's + * identity. + */ + public static Builder newBuilder(Status status, T replacement) { + return new Builder().setStatus(status).setReplacement(replacement); } /** * Returns a {@code DeprecationStatus} object given the status and replacement's identity. */ public static DeprecationStatus of(Status status, T replacement) { - return builder(status, replacement).build(); + return newBuilder(status, replacement).build(); } static DeprecationStatus fromPb( com.google.api.services.compute.model.DeprecationStatus deprecationStatusPb, Function fromUrl) { Builder builder = new Builder<>(); - builder.deleted(deprecationStatusPb.getDeleted()); - builder.deprecated(deprecationStatusPb.getDeprecated()); - builder.obsolete(deprecationStatusPb.getObsolete()); + builder.setDeleted(deprecationStatusPb.getDeleted()); + builder.setDeprecated(deprecationStatusPb.getDeprecated()); + builder.setObsolete(deprecationStatusPb.getObsolete()); if (deprecationStatusPb.getReplacement() != null) { - builder.replacement(fromUrl.apply(deprecationStatusPb.getReplacement())); + builder.setReplacement(fromUrl.apply(deprecationStatusPb.getReplacement())); } if (deprecationStatusPb.getState() != null) { - builder.status(Status.valueOf(deprecationStatusPb.getState())); + builder.setStatus(Status.valueOf(deprecationStatusPb.getState())); } return builder.build(); } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Disk.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Disk.java index f1c6cd26291c..41a7f95b91b5 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Disk.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Disk.java @@ -60,62 +60,80 @@ public static class Builder extends DiskInfo.Builder { } @Override - Builder generatedId(String generatedId) { - infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + infoBuilder.setGeneratedId(generatedId); return this; } @Override + @Deprecated public Builder configuration(DiskConfiguration configuration) { - infoBuilder.configuration(configuration); + return setConfiguration(configuration); + } + + @Override + public Builder setConfiguration(DiskConfiguration configuration) { + infoBuilder.setConfiguration(configuration); return this; } @Override + @Deprecated public Builder diskId(DiskId diskId) { - infoBuilder.diskId(diskId); + return setDiskId(diskId); + } + + @Override + public Builder setDiskId(DiskId diskId) { + infoBuilder.setDiskId(diskId); return this; } @Override - Builder creationTimestamp(Long creationTimestamp) { - infoBuilder.creationTimestamp(creationTimestamp); + Builder setCreationTimestamp(Long creationTimestamp) { + infoBuilder.setCreationTimestamp(creationTimestamp); return this; } @Override - Builder creationStatus(CreationStatus creationStatus) { - infoBuilder.creationStatus(creationStatus); + Builder setCreationStatus(CreationStatus creationStatus) { + infoBuilder.setCreationStatus(creationStatus); return this; } @Override + @Deprecated public Builder description(String description) { - infoBuilder.description(description); + return setDescription(description); + } + + @Override + public Builder setDescription(String description) { + infoBuilder.setDescription(description); return this; } @Override - Builder licenses(List licenses) { - infoBuilder.licenses(licenses); + Builder setLicenses(List licenses) { + infoBuilder.setLicenses(licenses); return this; } @Override - Builder attachedInstances(List attachedInstances) { - infoBuilder.attachedInstances(attachedInstances); + Builder setAttachedInstances(List attachedInstances) { + infoBuilder.setAttachedInstances(attachedInstances); return this; } @Override - Builder lastAttachTimestamp(Long lastAttachTimestamp) { - infoBuilder.lastAttachTimestamp(lastAttachTimestamp); + Builder setLastAttachTimestamp(Long lastAttachTimestamp) { + infoBuilder.setLastAttachTimestamp(lastAttachTimestamp); return this; } @Override - Builder lastDetachTimestamp(Long lastDetachTimestamp) { - infoBuilder.lastDetachTimestamp(lastDetachTimestamp); + Builder setLastDetachTimestamp(Long lastDetachTimestamp) { + infoBuilder.setLastDetachTimestamp(lastDetachTimestamp); return this; } @@ -149,7 +167,7 @@ public boolean exists() { * @throws ComputeException upon failure */ public Disk reload(DiskOption... options) { - return compute.getDisk(diskId(), options); + return compute.getDisk(getDiskId(), options); } /** @@ -160,7 +178,7 @@ public Disk reload(DiskOption... options) { * @throws ComputeException upon failure */ public Operation delete(OperationOption... options) { - return compute.deleteDisk(diskId(), options); + return compute.deleteDisk(getDiskId(), options); } /** @@ -170,7 +188,7 @@ public Operation delete(OperationOption... options) { * @throws ComputeException upon failure */ public Operation createSnapshot(String snapshot, OperationOption... options) { - return compute.create(SnapshotInfo.of(SnapshotId.of(snapshot), diskId()), options); + return compute.create(SnapshotInfo.of(SnapshotId.of(snapshot), getDiskId()), options); } /** @@ -180,8 +198,8 @@ public Operation createSnapshot(String snapshot, OperationOption... options) { * @throws ComputeException upon failure */ public Operation createSnapshot(String snapshot, String description, OperationOption... options) { - SnapshotInfo snapshotInfo = SnapshotInfo.builder(SnapshotId.of(snapshot), diskId()) - .description(description) + SnapshotInfo snapshotInfo = SnapshotInfo.newBuilder(SnapshotId.of(snapshot), getDiskId()) + .setDescription(description) .build(); return compute.create(snapshotInfo, options); } @@ -193,7 +211,7 @@ public Operation createSnapshot(String snapshot, String description, OperationOp * @throws ComputeException upon failure */ public Operation createImage(String image, OperationOption... options) { - ImageInfo imageInfo = ImageInfo.of(ImageId.of(image), DiskImageConfiguration.of(diskId())); + ImageInfo imageInfo = ImageInfo.of(ImageId.of(image), DiskImageConfiguration.of(getDiskId())); return compute.create(imageInfo, options); } @@ -204,9 +222,10 @@ public Operation createImage(String image, OperationOption... options) { * @throws ComputeException upon failure */ public Operation createImage(String image, String description, OperationOption... options) { - ImageInfo imageInfo = ImageInfo.builder(ImageId.of(image), DiskImageConfiguration.of(diskId())) - .description(description) - .build(); + ImageInfo imageInfo = + ImageInfo.newBuilder(ImageId.of(image), DiskImageConfiguration.of(getDiskId())) + .setDescription(description) + .build(); return compute.create(imageInfo, options); } @@ -218,13 +237,21 @@ public Operation createImage(String image, String description, OperationOption.. * @throws ComputeException upon failure or if the new disk size is smaller than the previous one */ public Operation resize(long sizeGb, OperationOption... options) { - return compute.resize(diskId(), sizeGb, options); + return compute.resize(getDiskId(), sizeGb, options); } /** * Returns the disk's {@code Compute} object used to issue requests. */ + @Deprecated public Compute compute() { + return getCompute(); + } + + /** + * Returns the disk's {@code Compute} object used to issue requests. + */ + public Compute getCompute() { return compute; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskConfiguration.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskConfiguration.java index 1670bcf8b56b..32c12b96aa56 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskConfiguration.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskConfiguration.java @@ -95,7 +95,7 @@ protected B self() { return (B) this; } - B type(Type type) { + B setType(Type type) { this.type = type; return self(); } @@ -103,7 +103,15 @@ B type(Type type) { /** * Sets the size of the persistent disk, in GB. */ + @Deprecated public B sizeGb(Long sizeGb) { + return setSizeGb(sizeGb); + } + + /** + * Sets the size of the persistent disk, in GB. + */ + public B setSizeGb(Long sizeGb) { this.sizeGb = sizeGb; return self(); } @@ -111,7 +119,15 @@ public B sizeGb(Long sizeGb) { /** * Sets the identity of the disk type. If not set {@code pd-standard} will be used. */ + @Deprecated public B diskType(DiskTypeId diskType) { + return setDiskType(diskType); + } + + /** + * Sets the identity of the disk type. If not set {@code pd-standard} will be used. + */ + public B setDiskType(DiskTypeId diskType) { this.diskType = diskType; return self(); } @@ -135,21 +151,49 @@ public B diskType(DiskTypeId diskType) { * snapshot. This method returns {@link Type#IMAGE} for a configuration that creates a disk * from a Google Compute Engine image. */ + @Deprecated public Type type() { + return getType(); + } + + /** + * Returns the disk configuration's type. This method returns {@link Type#STANDARD} for a standard + * configuration that creates a disk given its type and size. This method returns + * {@link Type#SNAPSHOT} for a configuration that creates a disk from a Google Compute Engine + * snapshot. This method returns {@link Type#IMAGE} for a configuration that creates a disk + * from a Google Compute Engine image. + */ + public Type getType() { return type; } /** * Returns the size of the persistent disk, in GB. */ + @Deprecated public Long sizeGb() { + return getSizeGb(); + } + + /** + * Returns the size of the persistent disk, in GB. + */ + public Long getSizeGb() { return sizeGb; } /** * Returns the identity of the disk type. */ + @Deprecated public DiskTypeId diskType() { + return getDiskType(); + } + + /** + * Returns the identity of the disk type. + */ + public DiskTypeId getDiskType() { return diskType; } @@ -186,7 +230,7 @@ Disk toPb() { Disk diskPb = new Disk(); diskPb.setSizeGb(sizeGb); if (diskType != null) { - diskPb.setType(diskType.selfLink()); + diskPb.setType(diskType.getSelfLink()); } return diskPb; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskId.java index 58f55beb9a9a..f3d060eceaf4 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskId.java @@ -45,15 +45,31 @@ private DiskId(String project, String zone, String disk) { /** * Returns the name of the zone this disk belongs to. */ + @Deprecated public String zone() { + return getZone(); + } + + /** + * Returns the name of the zone this disk belongs to. + */ + public String getZone() { return zone; } /** * Returns the identity of the zone this disk belongs to. */ + @Deprecated public ZoneId zoneId() { - return ZoneId.of(project(), zone); + return getZoneId(); + } + + /** + * Returns the identity of the zone this disk belongs to. + */ + public ZoneId getZoneId() { + return ZoneId.of(getProject(), zone); } /** @@ -64,13 +80,32 @@ public ZoneId zoneId() { * * @see RFC1035 */ + @Deprecated public String disk() { + return getDisk(); + } + + /** + * Returns the name of the disk. The name must be 1-63 characters long and comply with RFC1035. + * Specifically, the name must match the regular expression {@code [a-z]([-a-z0-9]*[a-z0-9])?} + * which means the first character must be a lowercase letter, and all following characters must + * be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. + * + * @see RFC1035 + */ + public String getDisk() { return disk; } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/zones/" + zone + "/disks/" + disk; + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/zones/" + zone + "/disks/" + disk; } @Override @@ -99,7 +134,7 @@ public boolean equals(Object obj) { @Override DiskId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } return DiskId.of(projectId, zone, disk); @@ -115,7 +150,7 @@ DiskId setProjectId(String projectId) { * @see RFC1035 */ public static DiskId of(ZoneId zoneId, String disk) { - return new DiskId(zoneId.project(), zoneId.zone(), disk); + return new DiskId(zoneId.getProject(), zoneId.getZone(), disk); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskImageConfiguration.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskImageConfiguration.java index a31c8199ec07..7aa16b683f44 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskImageConfiguration.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskImageConfiguration.java @@ -62,12 +62,20 @@ private Builder(Image imagePb) { /** * Sets the identity of the source disk used to create the image. */ + @Deprecated public Builder sourceDisk(DiskId sourceDisk) { + return setSourceDisk(sourceDisk); + } + + /** + * Sets the identity of the source disk used to create the image. + */ + public Builder setSourceDisk(DiskId sourceDisk) { this.sourceDisk = checkNotNull(sourceDisk); return this; } - Builder sourceDiskId(String sourceDiskId) { + Builder setSourceDiskId(String sourceDiskId) { this.sourceDiskId = sourceDiskId; return this; } @@ -90,7 +98,15 @@ private DiskImageConfiguration(Builder builder) { /** * Returns the identity of the source disk used to create this image. */ + @Deprecated public DiskId sourceDisk() { + return getSourceDisk(); + } + + /** + * Returns the identity of the source disk used to create this image. + */ + public DiskId getSourceDisk() { return sourceDisk; } @@ -99,7 +115,17 @@ public DiskId sourceDisk() { * be used to determine whether the image was taken from the current or a previous instance of a * given disk name. */ + @Deprecated public String sourceDiskId() { + return getSourceDiskId(); + } + + /** + * Returns the service-generated unique id of the disk used to create this image. This value may + * be used to determine whether the image was taken from the current or a previous instance of a + * given disk name. + */ + public String getSourceDiskId() { return sourceDiskId; } @@ -130,16 +156,16 @@ public final boolean equals(Object obj) { @Override DiskImageConfiguration setProjectId(String projectId) { - if (sourceDisk.project() != null) { + if (sourceDisk.getProject() != null) { return this; } - return toBuilder().sourceDisk(sourceDisk.setProjectId(projectId)).build(); + return toBuilder().setSourceDisk(sourceDisk.setProjectId(projectId)).build(); } @Override Image toPb() { Image imagePb = super.toPb(); - imagePb.setSourceDisk(sourceDisk.selfLink()); + imagePb.setSourceDisk(sourceDisk.getSelfLink()); imagePb.setSourceDiskId(sourceDiskId); return imagePb; } @@ -147,15 +173,23 @@ Image toPb() { /** * Creates a builder for a {@code DiskImageConfiguration} given the source disk identity. */ + @Deprecated public static Builder builder(DiskId sourceDisk) { - return new Builder().sourceDisk(sourceDisk); + return newBuilder(sourceDisk); + } + + /** + * Creates a builder for a {@code DiskImageConfiguration} given the source disk identity. + */ + public static Builder newBuilder(DiskId sourceDisk) { + return new Builder().setSourceDisk(sourceDisk); } /** * Creates a {@code DiskImageConfiguration} object given the source disk identity. */ public static DiskImageConfiguration of(DiskId sourceId) { - return builder(sourceId).build(); + return newBuilder(sourceId).build(); } @SuppressWarnings("unchecked") diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskInfo.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskInfo.java index aab6d90ff345..eec4c8de8b54 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskInfo.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskInfo.java @@ -99,34 +99,52 @@ public enum CreationStatus { */ public abstract static class Builder { - abstract Builder generatedId(String generatedId); + abstract Builder setGeneratedId(String generatedId); /** * Sets the disk configuration. */ + @Deprecated public abstract Builder configuration(DiskConfiguration configuration); + /** + * Sets the disk configuration. + */ + public abstract Builder setConfiguration(DiskConfiguration configuration); + /** * Sets the disk identity. */ + @Deprecated public abstract Builder diskId(DiskId diskId); - abstract Builder creationTimestamp(Long creationTimestamp); + /** + * Sets the disk identity. + */ + public abstract Builder setDiskId(DiskId diskId); + + abstract Builder setCreationTimestamp(Long creationTimestamp); - abstract Builder creationStatus(CreationStatus creationStatus); + abstract Builder setCreationStatus(CreationStatus creationStatus); /** * Sets an optional textual description of the resource. */ + @Deprecated public abstract Builder description(String description); - abstract Builder licenses(List licenses); + /** + * Sets an optional textual description of the resource. + */ + public abstract Builder setDescription(String description); + + abstract Builder setLicenses(List licenses); - abstract Builder attachedInstances(List attachedInstances); + abstract Builder setAttachedInstances(List attachedInstances); - abstract Builder lastAttachTimestamp(Long lastAttachTimestamp); + abstract Builder setLastAttachTimestamp(Long lastAttachTimestamp); - abstract Builder lastDetachTimestamp(Long lastDetachTimestamp); + abstract Builder setLastDetachTimestamp(Long lastDetachTimestamp); /** * Creates a {@code DiskInfo} object. @@ -193,62 +211,80 @@ static final class BuilderImpl extends Builder { } @Override - BuilderImpl generatedId(String generatedId) { + BuilderImpl setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } @Override + @Deprecated public BuilderImpl configuration(DiskConfiguration configuration) { + return setConfiguration(configuration); + } + + @Override + public BuilderImpl setConfiguration(DiskConfiguration configuration) { this.configuration = checkNotNull(configuration); return this; } @Override + @Deprecated public BuilderImpl diskId(DiskId diskId) { + return setDiskId(diskId); + } + + @Override + public BuilderImpl setDiskId(DiskId diskId) { this.diskId = checkNotNull(diskId); return this; } @Override - BuilderImpl creationTimestamp(Long creationTimestamp) { + BuilderImpl setCreationTimestamp(Long creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } @Override - BuilderImpl creationStatus(CreationStatus creationStatus) { + BuilderImpl setCreationStatus(CreationStatus creationStatus) { this.creationStatus = creationStatus; return this; } @Override + @Deprecated public BuilderImpl description(String description) { + return setDescription(description); + } + + @Override + public BuilderImpl setDescription(String description) { this.description = description; return this; } @Override - BuilderImpl licenses(List licenses) { + BuilderImpl setLicenses(List licenses) { this.licenses = licenses != null ? ImmutableList.copyOf(licenses) : null; return this; } @Override - BuilderImpl attachedInstances(List attachedInstances) { + BuilderImpl setAttachedInstances(List attachedInstances) { this.attachedInstances = attachedInstances != null ? ImmutableList.copyOf(attachedInstances) : null; return this; } @Override - BuilderImpl lastAttachTimestamp(Long lastAttachTimestamp) { + BuilderImpl setLastAttachTimestamp(Long lastAttachTimestamp) { this.lastAttachTimestamp = lastAttachTimestamp; return this; } @Override - BuilderImpl lastDetachTimestamp(Long lastDetachTimestamp) { + BuilderImpl setLastDetachTimestamp(Long lastDetachTimestamp) { this.lastDetachTimestamp = lastDetachTimestamp; return this; } @@ -275,14 +311,30 @@ public DiskInfo build() { /** * Returns the creation timestamp in milliseconds since epoch. */ + @Deprecated public Long creationTimestamp() { + return getCreationTimestamp(); + } + + /** + * Returns the creation timestamp in milliseconds since epoch. + */ + public Long getCreationTimestamp() { return creationTimestamp; } /** * Returns the service-generated unique identifier for the disk. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated unique identifier for the disk. + */ + public String getGeneratedId() { return generatedId; } @@ -290,56 +342,121 @@ public String generatedId() { * Returns the disk configuration. */ @SuppressWarnings("unchecked") + @Deprecated public T configuration() { + return getConfiguration(); + } + + /** + * Returns the disk configuration. + */ + @SuppressWarnings("unchecked") + public T getConfiguration() { return (T) configuration; } /** * Returns the disk identity. */ + @Deprecated public DiskId diskId() { + return getDiskId(); + } + + /** + * Returns the disk identity. + */ + public DiskId getDiskId() { return diskId; } /** * Returns the creation status of the disk. */ + @Deprecated public CreationStatus creationStatus() { + return getCreationStatus(); + } + + /** + * Returns the creation status of the disk. + */ + public CreationStatus getCreationStatus() { return creationStatus; } /** * Returns a textual description of the disk. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns a textual description of the disk. + */ + public String getDescription() { return description; } /** * Returns all applicable publicly visible licenses for the disk. */ + @Deprecated public List licenses() { + return getLicenses(); + } + + /** + * Returns all applicable publicly visible licenses for the disk. + */ + public List getLicenses() { return licenses; } /** * Returns all the identities of the instances this disk is attached to. */ + @Deprecated public List attachedInstances() { + return getAttachedInstances(); + } + + /** + * Returns all the identities of the instances this disk is attached to. + */ + public List getAttachedInstances() { return attachedInstances; } /** * Returns the last attach timestamp in milliseconds since epoch. */ + @Deprecated public Long lastAttachTimestamp() { + return getLastAttachTimestamp(); + } + + /** + * Returns the last attach timestamp in milliseconds since epoch. + */ + public Long getLastAttachTimestamp() { return lastAttachTimestamp; } /** * Returns the last detach timestamp in milliseconds since epoch. */ + @Deprecated public Long lastDetachTimestamp() { + return getLastDetachTimestamp(); + } + + /** + * Returns the last detach timestamp in milliseconds since epoch. + */ + public Long getLastDetachTimestamp() { return lastDetachTimestamp; } @@ -386,7 +503,18 @@ public boolean equals(Object obj) { * {@link SnapshotDiskConfiguration} to create a disk from a snapshot. Use * {@link ImageDiskConfiguration} to create a disk from a disk image. */ + @Deprecated public static Builder builder(DiskId diskId, DiskConfiguration configuration) { + return newBuilder(diskId, configuration); + } + + /** + * Returns a builder for a {@code DiskInfo} object given its identity and configuration. Use + * {@link StandardDiskConfiguration} to create a simple disk given its type and size. Use + * {@link SnapshotDiskConfiguration} to create a disk from a snapshot. Use + * {@link ImageDiskConfiguration} to create a disk from a disk image. + */ + public static Builder newBuilder(DiskId diskId, DiskConfiguration configuration) { return new BuilderImpl(diskId, configuration); } @@ -397,13 +525,13 @@ public static Builder builder(DiskId diskId, DiskConfiguration configuration) { * {@link ImageDiskConfiguration} to create a disk from a disk image. */ public static DiskInfo of(DiskId diskId, DiskConfiguration configuration) { - return builder(diskId, configuration).build(); + return newBuilder(diskId, configuration).build(); } DiskInfo setProjectId(String projectId) { return toBuilder() - .diskId(diskId.setProjectId(projectId)) - .configuration(configuration.setProjectId(projectId)) + .setDiskId(diskId.setProjectId(projectId)) + .setConfiguration(configuration.setProjectId(projectId)) .build(); } @@ -415,13 +543,13 @@ Disk toPb() { if (creationTimestamp != null) { diskPb.setCreationTimestamp(TIMESTAMP_FORMATTER.print(creationTimestamp)); } - diskPb.setZone(diskId.zoneId().selfLink()); + diskPb.setZone(diskId.getZoneId().getSelfLink()); if (creationStatus != null) { diskPb.setStatus(creationStatus.toString()); } - diskPb.setName(diskId.disk()); + diskPb.setName(diskId.getDisk()); diskPb.setDescription(description); - diskPb.setSelfLink(diskId.selfLink()); + diskPb.setSelfLink(diskId.getSelfLink()); if (licenses != null) { diskPb.setLicenses(Lists.transform(licenses, LicenseId.TO_URL_FUNCTION)); } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskType.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskType.java index cbe6f625e764..5a9c6dca3d13 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskType.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskType.java @@ -72,37 +72,37 @@ static final class Builder { private Builder() {} - Builder generatedId(String generatedId) { + Builder setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } - Builder creationTimestamp(Long creationTimestamp) { + Builder setCreationTimestamp(Long creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } - Builder diskTypeId(DiskTypeId diskTypeId) { + Builder setDiskTypeId(DiskTypeId diskTypeId) { this.diskTypeId = diskTypeId; return this; } - Builder description(String description) { + Builder setDescription(String description) { this.description = description; return this; } - Builder validDiskSize(String validDiskSize) { + Builder setValidDiskSize(String validDiskSize) { this.validDiskSize = validDiskSize; return this; } - Builder defaultDiskSizeGb(Long defaultDiskSizeGb) { + Builder setDefaultDiskSizeGb(Long defaultDiskSizeGb) { this.defaultDiskSizeGb = defaultDiskSizeGb; return this; } - Builder deprecationStatus(DeprecationStatus deprecationStatus) { + Builder setDeprecationStatus(DeprecationStatus deprecationStatus) { this.deprecationStatus = deprecationStatus; return this; } @@ -125,42 +125,90 @@ private DiskType(Builder builder) { /** * Returns the creation timestamp in milliseconds since epoch. */ + @Deprecated public Long creationTimestamp() { + return getCreationTimestamp(); + } + + /** + * Returns the creation timestamp in milliseconds since epoch. + */ + public Long getCreationTimestamp() { return creationTimestamp; } /** * Returns the disk type's identity. */ + @Deprecated public DiskTypeId diskTypeId() { + return getDiskTypeId(); + } + + /** + * Returns the disk type's identity. + */ + public DiskTypeId getDiskTypeId() { return diskTypeId; } /** * Returns the service-generated unique identifier for the disk type. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated unique identifier for the disk type. + */ + public String getGeneratedId() { return generatedId; } /** * Returns a textual description of the disk type. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns a textual description of the disk type. + */ + public String getDescription() { return description; } /** * Returns an optional textual description of the valid disk size, such as "10GB-10TB". */ + @Deprecated public String validDiskSize() { + return getValidDiskSize(); + } + + /** + * Returns an optional textual description of the valid disk size, such as "10GB-10TB". + */ + public String getValidDiskSize() { return validDiskSize; } /** * Returns the service-defined default disk size in GB. */ + @Deprecated public Long defaultDiskSizeGb() { + return getDefaultDiskSizeGb(); + } + + /** + * Returns the service-defined default disk size in GB. + */ + public Long getDefaultDiskSizeGb() { return defaultDiskSizeGb; } @@ -169,7 +217,17 @@ public Long defaultDiskSizeGb() { * either {@link DeprecationStatus.Status#DELETED} or {@link DeprecationStatus.Status#OBSOLETE} * the disk type should not be used. Returns {@code null} if the disk type is not deprecated. */ + @Deprecated public DeprecationStatus deprecationStatus() { + return getDeprecationStatus(); + } + + /** + * Returns the deprecation status of the disk type. If {@link DeprecationStatus#status()} is + * either {@link DeprecationStatus.Status#DELETED} or {@link DeprecationStatus.Status#OBSOLETE} + * the disk type should not be used. Returns {@code null} if the disk type is not deprecated. + */ + public DeprecationStatus getDeprecationStatus() { return deprecationStatus; } @@ -209,33 +267,34 @@ com.google.api.services.compute.model.DiskType toPb() { } diskTypePb.setDescription(description); diskTypePb.setValidDiskSize(validDiskSize); - diskTypePb.setSelfLink(diskTypeId.selfLink()); + diskTypePb.setSelfLink(diskTypeId.getSelfLink()); diskTypePb.setDefaultDiskSizeGb(defaultDiskSizeGb); - diskTypePb.setZone(diskTypeId.zoneId().selfLink()); + diskTypePb.setZone(diskTypeId.getZoneId().getSelfLink()); if (deprecationStatus != null) { diskTypePb.setDeprecated(deprecationStatus.toPb()); } return diskTypePb; } - static Builder builder() { + static Builder newBuilder() { return new Builder(); } static DiskType fromPb(com.google.api.services.compute.model.DiskType diskTypePb) { - Builder builder = builder(); + Builder builder = newBuilder(); if (diskTypePb.getId() != null) { - builder.generatedId(diskTypePb.getId().toString()); + builder.setGeneratedId(diskTypePb.getId().toString()); } if (diskTypePb.getCreationTimestamp() != null) { - builder.creationTimestamp(TIMESTAMP_FORMATTER.parseMillis(diskTypePb.getCreationTimestamp())); + builder.setCreationTimestamp( + TIMESTAMP_FORMATTER.parseMillis(diskTypePb.getCreationTimestamp())); } - builder.diskTypeId(DiskTypeId.fromUrl(diskTypePb.getSelfLink())); - builder.description(diskTypePb.getDescription()); - builder.validDiskSize(diskTypePb.getValidDiskSize()); - builder.defaultDiskSizeGb(diskTypePb.getDefaultDiskSizeGb()); + builder.setDiskTypeId(DiskTypeId.fromUrl(diskTypePb.getSelfLink())); + builder.setDescription(diskTypePb.getDescription()); + builder.setValidDiskSize(diskTypePb.getValidDiskSize()); + builder.setDefaultDiskSizeGb(diskTypePb.getDefaultDiskSizeGb()); if (diskTypePb.getDeprecated() != null) { - builder.deprecationStatus( + builder.setDeprecationStatus( DeprecationStatus.fromPb(diskTypePb.getDeprecated(), DiskTypeId.FROM_URL_FUNCTION)); } return builder.build(); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskTypeId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskTypeId.java index 1ed0cfdea472..644d027e7bc0 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskTypeId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/DiskTypeId.java @@ -39,7 +39,7 @@ public DiskTypeId apply(String pb) { static final Function TO_URL_FUNCTION = new Function() { @Override public String apply(DiskTypeId diskTypeId) { - return diskTypeId.selfLink(); + return diskTypeId.getSelfLink(); } }; @@ -59,27 +59,57 @@ private DiskTypeId(String project, String zone, String type) { /** * Returns the name of the disk type. */ + @Deprecated public String type() { + return getType(); + } + + /** + * Returns the name of the disk type. + */ + public String getType() { return type; } /** * Returns the name of the zone this disk type belongs to. */ + @Deprecated public String zone() { + return getZone(); + } + + /** + * Returns the name of the zone this disk type belongs to. + */ + public String getZone() { return zone; } /** * Returns the identity of the zone this disk type belongs to. */ + @Deprecated public ZoneId zoneId() { - return ZoneId.of(project(), zone); + return getZoneId(); + } + + /** + * Returns the identity of the zone this disk type belongs to. + */ + public ZoneId getZoneId() { + return ZoneId.of(getProject(), zone); } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/zones/" + zone + "/diskTypes/" + type; + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/zones/" + zone + "/diskTypes/" + type; } @Override @@ -108,7 +138,7 @@ public boolean equals(Object obj) { @Override DiskTypeId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } return DiskTypeId.of(projectId, zone, type); @@ -118,7 +148,7 @@ DiskTypeId setProjectId(String projectId) { * Returns a disk type identity given the zone identity and the disk type name. */ public static DiskTypeId of(ZoneId zoneId, String type) { - return new DiskTypeId(zoneId.project(), zoneId.zone(), type); + return new DiskTypeId(zoneId.getProject(), zoneId.getZone(), type); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ForwardingRuleId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ForwardingRuleId.java index 09d447cb8072..d43925f1c599 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ForwardingRuleId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ForwardingRuleId.java @@ -56,8 +56,14 @@ enum Type { /** * Returns the type of this forwarding rule identity. */ + @Deprecated public abstract Type type(); + /** + * Returns the type of this forwarding rule identity. + */ + public abstract Type getType(); + /** * Returns the name of the forwarding rule. The forwarding rule name must be 1-63 characters long * and comply with RFC1035. Specifically, the name must match the regular expression @@ -67,7 +73,21 @@ enum Type { * * @see RFC1035 */ + @Deprecated public String rule() { + return getRule(); + } + + /** + * Returns the name of the forwarding rule. The forwarding rule name must be 1-63 characters long + * and comply with RFC1035. Specifically, the name must match the regular expression + * {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a lowercase letter, + * and all following characters must be a dash, lowercase letter, or digit, except the last + * character, which cannot be a dash. + * + * @see RFC1035 + */ + public String getRule() { return rule; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/GlobalAddressId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/GlobalAddressId.java index 45232edeff48..1773c6d4ae0e 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/GlobalAddressId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/GlobalAddressId.java @@ -33,13 +33,25 @@ private GlobalAddressId(String project, String address) { } @Override + @Deprecated public Type type() { + return getType(); + } + + @Override + public Type getType() { return Type.GLOBAL; } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/global/addresses/" + address(); + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/global/addresses/" + getAddress(); } @Override @@ -54,10 +66,10 @@ public boolean equals(Object obj) { @Override GlobalAddressId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } - return GlobalAddressId.of(projectId, address()); + return GlobalAddressId.of(projectId, getAddress()); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/GlobalForwardingRuleId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/GlobalForwardingRuleId.java index b9acfa989b85..1c189eca929e 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/GlobalForwardingRuleId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/GlobalForwardingRuleId.java @@ -37,7 +37,7 @@ public GlobalForwardingRuleId apply(String pb) { new Function() { @Override public String apply(GlobalForwardingRuleId forwardingRuleId) { - return forwardingRuleId.selfLink(); + return forwardingRuleId.getSelfLink(); } }; @@ -50,13 +50,25 @@ private GlobalForwardingRuleId(String project, String rule) { } @Override + @Deprecated public Type type() { + return getType(); + } + + @Override + public Type getType() { return Type.GLOBAL; } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/global/forwardingRules/" + rule(); + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/global/forwardingRules/" + getRule(); } @Override @@ -73,10 +85,10 @@ public boolean equals(Object obj) { @Override GlobalForwardingRuleId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } - return GlobalForwardingRuleId.of(projectId, rule()); + return GlobalForwardingRuleId.of(projectId, getRule()); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/GlobalOperationId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/GlobalOperationId.java index ee3e4fc2d40e..0e5fb162dd7f 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/GlobalOperationId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/GlobalOperationId.java @@ -33,13 +33,25 @@ private GlobalOperationId(String project, String operation) { } @Override + @Deprecated public Type type() { + return getType(); + } + + @Override + public Type getType() { return Type.GLOBAL; } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/global/operations/" + operation(); + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/global/operations/" + getOperation(); } @Override @@ -54,10 +66,10 @@ public boolean equals(Object obj) { @Override GlobalOperationId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } - return GlobalOperationId.of(projectId, operation()); + return GlobalOperationId.of(projectId, getOperation()); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Image.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Image.java index e457ee71da13..0b5fbb8487e3 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Image.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Image.java @@ -55,8 +55,8 @@ public static class Builder extends ImageInfo.Builder { Builder(Compute compute, ImageId imageId, ImageConfiguration configuration) { this.compute = compute; this.infoBuilder = new ImageInfo.BuilderImpl(); - this.infoBuilder.imageId(imageId); - this.infoBuilder.configuration(configuration); + this.infoBuilder.setImageId(imageId); + this.infoBuilder.setConfiguration(configuration); } Builder(Image image) { @@ -65,56 +65,74 @@ public static class Builder extends ImageInfo.Builder { } @Override - Builder generatedId(String generatedId) { - infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + infoBuilder.setGeneratedId(generatedId); return this; } @Override - Builder creationTimestamp(Long creationTimestamp) { - infoBuilder.creationTimestamp(creationTimestamp); + Builder getCreationTimestamp(Long creationTimestamp) { + infoBuilder.getCreationTimestamp(creationTimestamp); return this; } @Override + @Deprecated public Builder imageId(ImageId imageId) { - infoBuilder.imageId(imageId); + return setImageId(imageId); + } + + @Override + public Builder setImageId(ImageId imageId) { + infoBuilder.setImageId(imageId); return this; } @Override + @Deprecated public Builder description(String description) { - infoBuilder.description(description); + return setDescription(description); + } + + @Override + public Builder setDescription(String description) { + infoBuilder.setDescription(description); return this; } @Override + @Deprecated public Builder configuration(ImageConfiguration configuration) { - infoBuilder.configuration(configuration); + return setConfiguration(configuration); + } + + @Override + public Builder setConfiguration(ImageConfiguration configuration) { + infoBuilder.setConfiguration(configuration); return this; } @Override - Builder status(Status status) { - infoBuilder.status(status); + Builder setStatus(Status status) { + infoBuilder.setStatus(status); return this; } @Override - Builder diskSizeGb(Long diskSizeGb) { - infoBuilder.diskSizeGb(diskSizeGb); + Builder setDiskSizeGb(Long diskSizeGb) { + infoBuilder.setDiskSizeGb(diskSizeGb); return this; } @Override - Builder licenses(List licenses) { - infoBuilder.licenses(licenses); + Builder setLicenses(List licenses) { + infoBuilder.setLicenses(licenses); return this; } @Override - Builder deprecationStatus(DeprecationStatus deprecationStatus) { - infoBuilder.deprecationStatus(deprecationStatus); + Builder setDeprecationStatus(DeprecationStatus deprecationStatus) { + infoBuilder.setDeprecationStatus(deprecationStatus); return this; } @@ -148,7 +166,7 @@ public boolean exists() { * @throws ComputeException upon failure */ public Image reload(ImageOption... options) { - return compute.getImage(imageId(), options); + return compute.getImage(getImageId(), options); } /** @@ -159,7 +177,7 @@ public Image reload(ImageOption... options) { * @throws ComputeException upon failure or if this image is a publicly-available image */ public Operation delete(OperationOption... options) { - return compute.deleteImage(imageId(), options); + return compute.deleteImage(getImageId(), options); } /** @@ -171,13 +189,21 @@ public Operation delete(OperationOption... options) { */ public Operation deprecate(DeprecationStatus deprecationStatus, OperationOption... options) { - return compute.deprecate(imageId(), deprecationStatus, options); + return compute.deprecate(getImageId(), deprecationStatus, options); } /** * Returns the image's {@code Compute} object used to issue requests. */ + @Deprecated public Compute compute() { + return getCompute(); + } + + /** + * Returns the image's {@code Compute} object used to issue requests. + */ + public Compute getCompute() { return compute; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageConfiguration.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageConfiguration.java index 34b12dab16af..916456f196b3 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageConfiguration.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageConfiguration.java @@ -92,17 +92,17 @@ B self() { return (B) this; } - B type(Type type) { + B setType(Type type) { this.type = type; return self(); } - B sourceType(SourceType sourceType) { + B setSourceType(SourceType sourceType) { this.sourceType = sourceType; return self(); } - B archiveSizeBytes(Long archiveSizeBytes) { + B setArchiveSizeBytes(Long archiveSizeBytes) { this.archiveSizeBytes = archiveSizeBytes; return self(); } @@ -124,21 +124,47 @@ B archiveSizeBytes(Long archiveSizeBytes) { * an existing disk. This method returns {@link Type#STORAGE} if this image was created from a * file in Google Cloud Storage. */ + @Deprecated public Type type() { + return getType(); + } + + /** + * Returns the image's type. This method returns {@link Type#DISK} if this image was created from + * an existing disk. This method returns {@link Type#STORAGE} if this image was created from a + * file in Google Cloud Storage. + */ + public Type getType() { return type; } /** * Returns the source type of the disk. The default and only value is {@link SourceType#RAW}. */ + @Deprecated public SourceType sourceType() { + return getSourceType(); + } + + /** + * Returns the source type of the disk. The default and only value is {@link SourceType#RAW}. + */ + public SourceType getSourceType() { return sourceType; } /** * Returns the size of the image archive stored in Google Cloud Storage (in bytes). */ + @Deprecated public Long archiveSizeBytes() { + return getArchiveSizeBytes(); + } + + /** + * Returns the size of the image archive stored in Google Cloud Storage (in bytes). + */ + public Long getArchiveSizeBytes() { return archiveSizeBytes; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageDiskConfiguration.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageDiskConfiguration.java index cf8ede2f061a..41c99247316c 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageDiskConfiguration.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageDiskConfiguration.java @@ -67,20 +67,39 @@ private Builder(Disk diskPb) { * the image's size then disk creation will fail. */ @Override + @Deprecated public Builder sizeGb(Long sizeGb) { - super.sizeGb(sizeGb); + return setSizeGb(sizeGb); + } + + /** + * Sets the size of the persistent disk, in GB. If not set the disk will have the size of the + * image. This value can be larger than the image's size. If the provided size is smaller than + * the image's size then disk creation will fail. + */ + @Override + public Builder setSizeGb(Long sizeGb) { + super.setSizeGb(sizeGb); return this; } /** * Sets the identity of the source image used to create the disk. */ + @Deprecated public Builder sourceImage(ImageId sourceImage) { + return setSourceImage(sourceImage); + } + + /** + * Sets the identity of the source image used to create the disk. + */ + public Builder setSourceImage(ImageId sourceImage) { this.sourceImage = checkNotNull(sourceImage); return this; } - Builder sourceImageId(String sourceImageId) { + Builder setSourceImageId(String sourceImageId) { this.sourceImageId = sourceImageId; return this; } @@ -103,7 +122,15 @@ private ImageDiskConfiguration(Builder builder) { /** * Returns the identity of the source image used to create the disk. */ + @Deprecated public ImageId sourceImage() { + return getSourceImage(); + } + + /** + * Returns the identity of the source image used to create the disk. + */ + public ImageId getSourceImage() { return sourceImage; } @@ -114,7 +141,19 @@ public ImageId sourceImage() { * name, the source image service-generated id would identify the exact version of the image that * was used. */ + @Deprecated public String sourceImageId() { + return getSourceImageId(); + } + + /** + * Returns the service-generated unique id of the image used to create this disk. This value + * identifies the exact image that was used to create this persistent disk. For example, if you + * created the persistent disk from an image that was later deleted and recreated under the same + * name, the source image service-generated id would identify the exact version of the image that + * was used. + */ + public String getSourceImageId() { return sourceImageId; } @@ -145,22 +184,30 @@ public final boolean equals(Object obj) { @Override ImageDiskConfiguration setProjectId(String projectId) { - Builder builder = toBuilder().sourceImage(sourceImage.setProjectId(projectId)); - if (diskType() != null) { - builder.diskType(diskType().setProjectId(projectId)); + Builder builder = toBuilder().setSourceImage(sourceImage.setProjectId(projectId)); + if (getDiskType() != null) { + builder.setDiskType(getDiskType().setProjectId(projectId)); } return builder.build(); } @Override Disk toPb() { - return super.toPb().setSourceImage(sourceImage.selfLink()).setSourceImageId(sourceImageId); + return super.toPb().setSourceImage(sourceImage.getSelfLink()).setSourceImageId(sourceImageId); } /** * Returns a builder for an {@code ImageDiskConfiguration} object given the image identity. */ + @Deprecated public static Builder builder(ImageId imageId) { + return newBuilder(imageId); + } + + /** + * Returns a builder for an {@code ImageDiskConfiguration} object given the image identity. + */ + public static Builder newBuilder(ImageId imageId) { return new Builder(imageId); } @@ -168,7 +215,7 @@ public static Builder builder(ImageId imageId) { * Returns an {@code ImageDiskConfiguration} object given the image identity. */ public static ImageDiskConfiguration of(ImageId imageId) { - return builder(imageId).build(); + return newBuilder(imageId).build(); } @SuppressWarnings("unchecked") diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageId.java index 51a252afd6cc..b85c5a9b3eec 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageId.java @@ -39,7 +39,7 @@ public ImageId apply(String pb) { static final Function TO_URL_FUNCTION = new Function() { @Override public String apply(ImageId imageId) { - return imageId.selfLink(); + return imageId.getSelfLink(); } }; @@ -62,13 +62,32 @@ private ImageId(String project, String image) { * * @see RFC1035 */ + @Deprecated public String image() { + return getImage(); + } + + /** + * Returns the name of the image. The name must be 1-63 characters long and comply with RFC1035. + * Specifically, the name must match the regular expression {@code [a-z]([-a-z0-9]*[a-z0-9])?} + * which means the first character must be a lowercase letter, and all following characters must + * be a dash, lowercase letter, or digit, except the last character, which cannot be a dash. + * + * @see RFC1035 + */ + public String getImage() { return image; } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/global/images/" + image; + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/global/images/" + image; } @Override @@ -95,7 +114,7 @@ public boolean equals(Object obj) { @Override ImageId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } return ImageId.of(projectId, image); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageInfo.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageInfo.java index 102e2c742d71..c128b5e2461b 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageInfo.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ImageInfo.java @@ -99,34 +99,54 @@ public enum Status { */ public abstract static class Builder { - abstract Builder generatedId(String generatedId); + abstract Builder setGeneratedId(String generatedId); - abstract Builder creationTimestamp(Long creationTimestamp); + abstract Builder getCreationTimestamp(Long creationTimestamp); /** * Sets the image identity. */ + @Deprecated public abstract Builder imageId(ImageId imageId); + /** + * Sets the image identity. + */ + public abstract Builder setImageId(ImageId imageId); + /** * Sets an optional textual description of the image. */ + @Deprecated public abstract Builder description(String description); + /** + * Sets an optional textual description of the image. + */ + public abstract Builder setDescription(String description); + /** * Sets the image configuration. Use {@link DiskImageConfiguration} to create an image from an * existing disk. Use {@link StorageImageConfiguration} to create an image from a file stored in * Google Cloud Storage. */ + @Deprecated public abstract Builder configuration(ImageConfiguration configuration); - abstract Builder status(Status status); + /** + * Sets the image configuration. Use {@link DiskImageConfiguration} to create an image from an + * existing disk. Use {@link StorageImageConfiguration} to create an image from a file stored in + * Google Cloud Storage. + */ + public abstract Builder setConfiguration(ImageConfiguration configuration); + + abstract Builder setStatus(Status status); - abstract Builder diskSizeGb(Long diskSizeGb); + abstract Builder setDiskSizeGb(Long diskSizeGb); - abstract Builder licenses(List licenses); + abstract Builder setLicenses(List licenses); - abstract Builder deprecationStatus(DeprecationStatus deprecationStatus); + abstract Builder setDeprecationStatus(DeprecationStatus deprecationStatus); /** * Creates a {@code ImageInfo} object. @@ -184,55 +204,73 @@ static final class BuilderImpl extends Builder { } @Override - BuilderImpl generatedId(String generatedId) { + BuilderImpl setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } @Override - BuilderImpl creationTimestamp(Long creationTimestamp) { + BuilderImpl getCreationTimestamp(Long creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } @Override + @Deprecated public BuilderImpl imageId(ImageId imageId) { + return setImageId(imageId); + } + + @Override + public BuilderImpl setImageId(ImageId imageId) { this.imageId = checkNotNull(imageId); return this; } @Override + @Deprecated public BuilderImpl description(String description) { + return setDescription(description); + } + + @Override + public BuilderImpl setDescription(String description) { this.description = description; return this; } @Override + @Deprecated public BuilderImpl configuration(ImageConfiguration configuration) { + return setConfiguration(configuration); + } + + @Override + public BuilderImpl setConfiguration(ImageConfiguration configuration) { this.configuration = checkNotNull(configuration); return this; } @Override - BuilderImpl status(Status status) { + BuilderImpl setStatus(Status status) { this.status = status; return this; } @Override - BuilderImpl diskSizeGb(Long diskSizeGb) { + BuilderImpl setDiskSizeGb(Long diskSizeGb) { this.diskSizeGb = diskSizeGb; return this; } @Override - BuilderImpl licenses(List licenses) { + BuilderImpl setLicenses(List licenses) { this.licenses = licenses != null ? ImmutableList.copyOf(licenses) : null; return this; } @Override - BuilderImpl deprecationStatus(DeprecationStatus deprecationStatus) { + BuilderImpl setDeprecationStatus(DeprecationStatus deprecationStatus) { this.deprecationStatus = deprecationStatus; return this; } @@ -258,28 +296,60 @@ public ImageInfo build() { /** * Returns the service-generated unique identifier for the image. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated unique identifier for the image. + */ + public String getGeneratedId() { return generatedId; } /** * Returns the creation timestamp in milliseconds since epoch. */ + @Deprecated public Long creationTimestamp() { + return getCreationTimestamp(); + } + + /** + * Returns the creation timestamp in milliseconds since epoch. + */ + public Long getCreationTimestamp() { return creationTimestamp; } /** * Returns the image identity. */ + @Deprecated public ImageId imageId() { + return getImageId(); + } + + /** + * Returns the image identity. + */ + public ImageId getImageId() { return imageId; } /** * Returns a textual description of the image. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns a textual description of the image. + */ + public String getDescription() { return description; } @@ -290,14 +360,34 @@ public String description() { * from a file stored in Google Cloud Storage. */ @SuppressWarnings("unchecked") + @Deprecated public T configuration() { + return getConfiguration(); + } + + /** + * Returns the image configuration. This method returns an instance of + * {@link DiskImageConfiguration} if the the image was created from a Google Compute Engine disk. + * This method returns an instance of {@link StorageImageConfiguration} if the image was created + * from a file stored in Google Cloud Storage. + */ + @SuppressWarnings("unchecked") + public T getConfiguration() { return (T) configuration; } /** * Returns all applicable publicly visible licenses. */ + @Deprecated public List licenses() { + return getLicenses(); + } + + /** + * Returns all applicable publicly visible licenses. + */ + public List getLicenses() { return licenses; } @@ -305,14 +395,31 @@ public List licenses() { * Returns the status of the image. An image can be used to create other disks only after it has * been successfully created and its status is set to {@link Status#READY}. */ + @Deprecated public Status status() { + return getStatus(); + } + + /** + * Returns the status of the image. An image can be used to create other disks only after it has + * been successfully created and its status is set to {@link Status#READY}. + */ + public Status getStatus() { return status; } /** * Returns the size of the image when restored onto a persistent disk (in GB). */ + @Deprecated public Long diskSizeGb() { + return getDiskSizeGb(); + } + + /** + * Returns the size of the image when restored onto a persistent disk (in GB). + */ + public Long getDiskSizeGb() { return diskSizeGb; } @@ -321,7 +428,17 @@ public Long diskSizeGb() { * {@link DeprecationStatus.Status#DELETED} or {@link DeprecationStatus.Status#OBSOLETE} the * image must not be used. Returns {@code null} if the image is not deprecated. */ + @Deprecated public DeprecationStatus deprecationStatus() { + return getDeprecationStatus(); + } + + /** + * Returns the deprecation status of the image. If {@link DeprecationStatus#status()} is either + * {@link DeprecationStatus.Status#DELETED} or {@link DeprecationStatus.Status#OBSOLETE} the + * image must not be used. Returns {@code null} if the image is not deprecated. + */ + public DeprecationStatus getDeprecationStatus() { return deprecationStatus; } @@ -362,8 +479,8 @@ public boolean equals(Object obj) { ImageInfo setProjectId(String projectId) { return toBuilder() - .imageId(imageId.setProjectId(projectId)) - .configuration(configuration.setProjectId(projectId)) + .setImageId(imageId.setProjectId(projectId)) + .setConfiguration(configuration.setProjectId(projectId)) .build(); } @@ -375,9 +492,9 @@ Image toPb() { if (creationTimestamp != null) { imagePb.setCreationTimestamp(TIMESTAMP_FORMATTER.print(creationTimestamp)); } - imagePb.setName(imageId.image()); + imagePb.setName(imageId.getImage()); imagePb.setDescription(description); - imagePb.setSelfLink(imageId.selfLink()); + imagePb.setSelfLink(imageId.getSelfLink()); if (status != null) { imagePb.setStatus(status.name()); } @@ -397,8 +514,19 @@ Image toPb() { * {@link StorageImageConfiguration} to create an image from a file stored in Google Cloud * Storage. */ + @Deprecated public static Builder builder(ImageId imageId, ImageConfiguration configuration) { - return new BuilderImpl().imageId(imageId).configuration(configuration); + return newBuilder(imageId, configuration); + } + + /** + * Returns a builder for an {@code ImageInfo} object given the image identity and an image + * configuration. Use {@link DiskImageConfiguration} to create an image from an existing disk. Use + * {@link StorageImageConfiguration} to create an image from a file stored in Google Cloud + * Storage. + */ + public static Builder newBuilder(ImageId imageId, ImageConfiguration configuration) { + return new BuilderImpl().setImageId(imageId).setConfiguration(configuration); } /** @@ -408,7 +536,7 @@ public static Builder builder(ImageId imageId, ImageConfiguration configuration) * Storage. */ public static ImageInfo of(ImageId imageId, ImageConfiguration configuration) { - return builder(imageId, configuration).build(); + return newBuilder(imageId, configuration).build(); } static ImageInfo fromPb(Image imagePb) { diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Instance.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Instance.java index e1ee91f4e58d..c28761cbeaa9 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Instance.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Instance.java @@ -59,9 +59,9 @@ public static class Builder extends InstanceInfo.Builder { AttachedDisk attachedDisk, NetworkInterface networkInterface) { this.compute = compute; this.infoBuilder = new InstanceInfo.BuilderImpl(instanceId); - this.infoBuilder.machineType(machineType); - this.infoBuilder.attachedDisks(ImmutableList.of(attachedDisk)); - this.infoBuilder.networkInterfaces(ImmutableList.of(networkInterface)); + this.infoBuilder.setMachineType(machineType); + this.infoBuilder.setAttachedDisks(ImmutableList.of(attachedDisk)); + this.infoBuilder.setNetworkInterfaces(ImmutableList.of(networkInterface)); } Builder(Instance instance) { @@ -70,104 +70,176 @@ public static class Builder extends InstanceInfo.Builder { } @Override - Builder generatedId(String generatedId) { - this.infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + this.infoBuilder.setGeneratedId(generatedId); return this; } @Override + @Deprecated public Builder instanceId(InstanceId instanceId) { - this.infoBuilder.instanceId(instanceId); + return setInstanceId(instanceId); + } + + @Override + public Builder setInstanceId(InstanceId instanceId) { + this.infoBuilder.setInstanceId(instanceId); return this; } @Override - Builder creationTimestamp(Long creationTimestamp) { - this.infoBuilder.creationTimestamp(creationTimestamp); + Builder setCreationTimestamp(Long creationTimestamp) { + this.infoBuilder.setCreationTimestamp(creationTimestamp); return this; } @Override + @Deprecated public Builder description(String description) { - this.infoBuilder.description(description); + return setDescription(description); + } + + @Override + public Builder setDescription(String description) { + this.infoBuilder.setDescription(description); return this; } @Override - Builder status(Status status) { - this.infoBuilder.status(status); + Builder setStatus(Status status) { + this.infoBuilder.setStatus(status); return this; } @Override - Builder statusMessage(String statusMessage) { - this.infoBuilder.statusMessage(statusMessage); + Builder setStatusMessage(String statusMessage) { + this.infoBuilder.setStatusMessage(statusMessage); return this; } @Override + @Deprecated public Builder tags(Tags tags) { - this.infoBuilder.tags(tags); + return setTags(tags); + } + + @Override + public Builder setTags(Tags tags) { + this.infoBuilder.setTags(tags); return this; } @Override + @Deprecated public Builder machineType(MachineTypeId machineType) { - this.infoBuilder.machineType(machineType); + return setMachineType(machineType); + } + + @Override + public Builder setMachineType(MachineTypeId machineType) { + this.infoBuilder.setMachineType(machineType); return this; } @Override + @Deprecated public Builder canIpForward(Boolean canIpForward) { - this.infoBuilder.canIpForward(canIpForward); + return setCanIpForward(canIpForward); + } + + @Override + public Builder setCanIpForward(Boolean canIpForward) { + this.infoBuilder.setCanIpForward(canIpForward); return this; } @Override + @Deprecated public Builder networkInterfaces(List networkInterfaces) { - this.infoBuilder.networkInterfaces(networkInterfaces); + return setNetworkInterfaces(networkInterfaces); + } + + @Override + public Builder setNetworkInterfaces(List networkInterfaces) { + this.infoBuilder.setNetworkInterfaces(networkInterfaces); return this; } @Override + @Deprecated public Builder networkInterfaces(NetworkInterface... networkInterfaces) { - this.infoBuilder.networkInterfaces(networkInterfaces); + return setNetworkInterfaces(networkInterfaces); + } + + @Override + public Builder setNetworkInterfaces(NetworkInterface... networkInterfaces) { + this.infoBuilder.setNetworkInterfaces(networkInterfaces); return this; } @Override + @Deprecated public Builder attachedDisks(List attachedDisks) { - this.infoBuilder.attachedDisks(attachedDisks); + return setAttachedDisks(attachedDisks); + } + + @Override + public Builder setAttachedDisks(List attachedDisks) { + this.infoBuilder.setAttachedDisks(attachedDisks); return this; } @Override + @Deprecated public Builder attachedDisks(AttachedDisk... attachedDisks) { - this.infoBuilder.attachedDisks(attachedDisks); + return setAttachedDisks(attachedDisks); + } + + @Override + public Builder setAttachedDisks(AttachedDisk... attachedDisks) { + this.infoBuilder.setAttachedDisks(attachedDisks); return this; } @Override + @Deprecated public Builder metadata(Metadata metadata) { - this.infoBuilder.metadata(metadata); + return setMetadata(metadata); + } + + @Override + public Builder setMetadata(Metadata metadata) { + this.infoBuilder.setMetadata(metadata); return this; } @Override + @Deprecated public Builder serviceAccounts(List serviceAccounts) { - this.infoBuilder.serviceAccounts(serviceAccounts); + return setServiceAccounts(serviceAccounts); + } + + @Override + public Builder setServiceAccounts(List serviceAccounts) { + this.infoBuilder.setServiceAccounts(serviceAccounts); return this; } @Override + @Deprecated public Builder schedulingOptions(SchedulingOptions schedulingOptions) { - this.infoBuilder.schedulingOptions(schedulingOptions); + return setSchedulingOptions(schedulingOptions); + } + + @Override + public Builder setSchedulingOptions(SchedulingOptions schedulingOptions) { + this.infoBuilder.setSchedulingOptions(schedulingOptions); return this; } @Override - Builder cpuPlatform(String cpuPlatform) { - this.infoBuilder.cpuPlatform(cpuPlatform); + Builder setCpuPlatform(String cpuPlatform) { + this.infoBuilder.setCpuPlatform(cpuPlatform); return this; } @@ -202,7 +274,7 @@ public boolean exists() { * @throws ComputeException upon failure */ public Instance reload(InstanceOption... options) { - return compute.getInstance(instanceId(), options); + return compute.getInstance(getInstanceId(), options); } /** @@ -213,7 +285,7 @@ public Instance reload(InstanceOption... options) { * @throws ComputeException upon failure */ public Operation delete(OperationOption... options) { - return compute.deleteInstance(instanceId(), options); + return compute.deleteInstance(getInstanceId(), options); } /** @@ -225,7 +297,7 @@ public Operation delete(OperationOption... options) { */ public Operation addAccessConfig(String networkInterface, AccessConfig accessConfig, OperationOption... options) { - return compute.addAccessConfig(instanceId(), networkInterface, accessConfig, options); + return compute.addAccessConfig(getInstanceId(), networkInterface, accessConfig, options); } /** @@ -237,7 +309,7 @@ public Operation addAccessConfig(String networkInterface, AccessConfig accessCon */ public Operation attachDisk(PersistentDiskConfiguration configuration, OperationOption... options) { - return compute.attachDisk(instanceId(), configuration, options); + return compute.attachDisk(getInstanceId(), configuration, options); } /** @@ -249,7 +321,7 @@ public Operation attachDisk(PersistentDiskConfiguration configuration, */ public Operation attachDisk(String deviceName, PersistentDiskConfiguration configuration, OperationOption... options) { - return compute.attachDisk(instanceId(), deviceName, configuration, options); + return compute.attachDisk(getInstanceId(), deviceName, configuration, options); } /** @@ -262,7 +334,7 @@ public Operation attachDisk(String deviceName, PersistentDiskConfiguration confi */ public Operation attachDisk(String deviceName, PersistentDiskConfiguration configuration, int index, OperationOption... options) { - return compute.attachDisk(instanceId(), deviceName, configuration, index, options); + return compute.attachDisk(getInstanceId(), deviceName, configuration, index, options); } /** @@ -274,7 +346,7 @@ public Operation attachDisk(String deviceName, PersistentDiskConfiguration confi */ public Operation deleteAccessConfig(String networkInterface, String accessConfig, OperationOption... options) { - return compute.deleteAccessConfig(instanceId(), networkInterface, accessConfig, options); + return compute.deleteAccessConfig(getInstanceId(), networkInterface, accessConfig, options); } /** @@ -285,7 +357,7 @@ public Operation deleteAccessConfig(String networkInterface, String accessConfig * @throws ComputeException upon failure */ public Operation detachDisk(String deviceName, OperationOption... options) { - return compute.detachDisk(instanceId(), deviceName, options); + return compute.detachDisk(getInstanceId(), deviceName, options); } /** @@ -296,7 +368,7 @@ public Operation detachDisk(String deviceName, OperationOption... options) { * @throws ComputeException upon failure */ public String getSerialPortOutput(int port) { - return compute.getSerialPortOutput(instanceId(), port); + return compute.getSerialPortOutput(getInstanceId(), port); } /** @@ -307,7 +379,7 @@ public String getSerialPortOutput(int port) { * @throws ComputeException upon failure */ public String getSerialPortOutput() { - return compute.getSerialPortOutput(instanceId()); + return compute.getSerialPortOutput(getInstanceId()); } /** @@ -318,7 +390,7 @@ public String getSerialPortOutput() { * @throws ComputeException upon failure */ public Operation reset(OperationOption... options) { - return compute.reset(instanceId(), options); + return compute.reset(getInstanceId(), options); } /** @@ -330,7 +402,7 @@ public Operation reset(OperationOption... options) { */ public Operation setDiskAutoDelete(String deviceName, boolean autoDelete, OperationOption... options) { - return compute.setDiskAutoDelete(instanceId(), deviceName, autoDelete, options); + return compute.setDiskAutoDelete(getInstanceId(), deviceName, autoDelete, options); } /** @@ -342,7 +414,7 @@ public Operation setDiskAutoDelete(String deviceName, boolean autoDelete, * @throws ComputeException upon failure */ public Operation setMachineType(MachineTypeId machineType, OperationOption... options) { - return compute.setMachineType(instanceId(), machineType, options); + return compute.setMachineType(getInstanceId(), machineType, options); } /** @@ -353,7 +425,7 @@ public Operation setMachineType(MachineTypeId machineType, OperationOption... op * @throws ComputeException upon failure */ public Operation setMetadata(Metadata metadata, OperationOption... options) { - return compute.setMetadata(instanceId(), metadata, options); + return compute.setMetadata(getInstanceId(), metadata, options); } /** @@ -365,7 +437,7 @@ public Operation setMetadata(Metadata metadata, OperationOption... options) { * @throws ComputeException upon failure */ public Operation setMetadata(Map metadata, OperationOption... options) { - return setMetadata(metadata().toBuilder().values(metadata).build(), options); + return setMetadata(getMetadata().toBuilder().setValues(metadata).build(), options); } /** @@ -376,7 +448,7 @@ public Operation setMetadata(Map metadata, OperationOption... op * @throws ComputeException upon failure */ public Operation setSchedulingOptions(SchedulingOptions scheduling, OperationOption... options) { - return compute.setSchedulingOptions(instanceId(), scheduling, options); + return compute.setSchedulingOptions(getInstanceId(), scheduling, options); } /** @@ -387,7 +459,7 @@ public Operation setSchedulingOptions(SchedulingOptions scheduling, OperationOpt * @throws ComputeException upon failure */ public Operation setTags(Tags tags, OperationOption... options) { - return compute.setTags(instanceId(), tags, options); + return compute.setTags(getInstanceId(), tags, options); } /** @@ -399,7 +471,7 @@ public Operation setTags(Tags tags, OperationOption... options) { * @throws ComputeException upon failure */ public Operation setTags(Iterable tags, OperationOption... options) { - return setTags(tags().toBuilder().values(tags).build(), options); + return setTags(getTags().toBuilder().setValues(tags).build(), options); } /** @@ -410,7 +482,7 @@ public Operation setTags(Iterable tags, OperationOption... options) { * @throws ComputeException upon failure */ public Operation start(OperationOption... options) { - return compute.start(instanceId(), options); + return compute.start(getInstanceId(), options); } /** @@ -421,13 +493,21 @@ public Operation start(OperationOption... options) { * @throws ComputeException upon failure */ public Operation stop(OperationOption... options) { - return compute.stop(instanceId(), options); + return compute.stop(getInstanceId(), options); } /** * Returns the snapshot's {@code Compute} object used to issue requests. */ + @Deprecated public Compute compute() { + return getCompute(); + } + + /** + * Returns the snapshot's {@code Compute} object used to issue requests. + */ + public Compute getCompute() { return compute; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/InstanceId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/InstanceId.java index 8fde843020f3..607abeacd999 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/InstanceId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/InstanceId.java @@ -39,7 +39,7 @@ public InstanceId apply(String pb) { static final Function TO_URL_FUNCTION = new Function() { @Override public String apply(InstanceId instanceId) { - return instanceId.selfLink(); + return instanceId.getSelfLink(); } }; @@ -65,27 +65,63 @@ private InstanceId(String project, String zone, String instance) { * * @see RFC1035 */ + @Deprecated public String instance() { + return getInstance(); + } + + /** + * Returns the name of the instance. The name must be 1-63 characters long and comply with + * RFC1035. Specifically, the name must match the regular expression + * {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a lowercase letter, + * and all following characters must be a dash, lowercase letter, or digit, except the last + * character, which cannot be a dash. + * + * @see RFC1035 + */ + public String getInstance() { return instance; } /** * Returns the name of the zone this instance belongs to. */ + @Deprecated public String zone() { + return getZone(); + } + + /** + * Returns the name of the zone this instance belongs to. + */ + public String getZone() { return zone; } /** * Returns the identity of the zone this instance belongs to. */ + @Deprecated public ZoneId zoneId() { - return ZoneId.of(project(), zone); + return getZoneId(); + } + + /** + * Returns the identity of the zone this instance belongs to. + */ + public ZoneId getZoneId() { + return ZoneId.of(getProject(), zone); } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/zones/" + zone + "/instances/" + instance; + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/zones/" + zone + "/instances/" + instance; } @Override @@ -114,7 +150,7 @@ public boolean equals(Object obj) { @Override InstanceId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } return InstanceId.of(projectId, zone, instance); @@ -130,7 +166,7 @@ InstanceId setProjectId(String projectId) { * @see RFC1035 */ public static InstanceId of(ZoneId zoneId, String instance) { - return new InstanceId(zoneId.project(), zoneId.zone(), instance); + return new InstanceId(zoneId.getProject(), zoneId.getZone(), instance); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/InstanceInfo.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/InstanceInfo.java index 7f85985afd2d..05dfd52d7e70 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/InstanceInfo.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/InstanceInfo.java @@ -125,35 +125,60 @@ public enum Status { */ public abstract static class Builder { - abstract Builder generatedId(String generatedId); + abstract Builder setGeneratedId(String generatedId); /** * Sets the identity of the virtual machine instance. */ + @Deprecated public abstract Builder instanceId(InstanceId instanceId); - abstract Builder creationTimestamp(Long creationTimestamp); + /** + * Sets the identity of the virtual machine instance. + */ + public abstract Builder setInstanceId(InstanceId instanceId); + + abstract Builder setCreationTimestamp(Long creationTimestamp); /** * Sets an optional description of this Google Compute Engine instance. */ + @Deprecated public abstract Builder description(String description); - abstract Builder status(Status status); + /** + * Sets an optional description of this Google Compute Engine instance. + */ + public abstract Builder setDescription(String description); + + abstract Builder setStatus(Status status); - abstract Builder statusMessage(String statusMessage); + abstract Builder setStatusMessage(String statusMessage); /** * Sets the tags to apply to this instance. Tags are used to identify valid sources or targets * for network firewalls. */ + @Deprecated public abstract Builder tags(Tags tags); + /** + * Sets the tags to apply to this instance. Tags are used to identify valid sources or targets + * for network firewalls. + */ + public abstract Builder setTags(Tags tags); + /** * Sets the machine type identity. */ + @Deprecated public abstract Builder machineType(MachineTypeId machineType); + /** + * Sets the machine type identity. + */ + public abstract Builder setMachineType(MachineTypeId machineType); + /** * Sets whether to allow this instance to send and receive packets with non-matching destination * or source IPs. This is required if you plan to use this instance to forward routes. @@ -161,13 +186,24 @@ public abstract static class Builder { * @see Enabling IP * Forwarding */ + @Deprecated public abstract Builder canIpForward(Boolean canIpForward); + /** + * Sets whether to allow this instance to send and receive packets with non-matching destination + * or source IPs. This is required if you plan to use this instance to forward routes. + * + * @see Enabling IP + * Forwarding + */ + public abstract Builder setCanIpForward(Boolean canIpForward); + /** * Sets a list of network interfaces. This specifies how this instance is configured to interact * with other network services, such as connecting to the internet. At the moment, instances * only support one network interface. */ + @Deprecated public abstract Builder networkInterfaces(List networkInterfaces); /** @@ -175,25 +211,60 @@ public abstract static class Builder { * with other network services, such as connecting to the internet. At the moment, instances * only support one network interface. */ + public abstract Builder setNetworkInterfaces(List networkInterfaces); + + /** + * Sets a list of network interfaces. This specifies how this instance is configured to interact + * with other network services, such as connecting to the internet. At the moment, instances + * only support one network interface. + */ + @Deprecated public abstract Builder networkInterfaces(NetworkInterface... networkInterfaces); + /** + * Sets a list of network interfaces. This specifies how this instance is configured to interact + * with other network services, such as connecting to the internet. At the moment, instances + * only support one network interface. + */ + public abstract Builder setNetworkInterfaces(NetworkInterface... networkInterfaces); + /** * Sets a list of disks to attach to the instance. One boot disk must be provided (i.e. an * attached disk such that {@link AttachedDisk.AttachedDiskConfiguration#boot()} returns * {@code true}). */ + @Deprecated public abstract Builder attachedDisks(List attachedDisks); + /** + * Sets a list of disks to attach to the instance. One boot disk must be provided (i.e. an + * attached disk such that {@link AttachedDisk.AttachedDiskConfiguration#boot()} returns + * {@code true}). + */ + public abstract Builder setAttachedDisks(List attachedDisks); + /** * Sets a list of disks to attach to the instance. One boot disk must be provided. */ + @Deprecated public abstract Builder attachedDisks(AttachedDisk... attachedDisks); + /** + * Sets a list of disks to attach to the instance. One boot disk must be provided. + */ + public abstract Builder setAttachedDisks(AttachedDisk... attachedDisks); + /** * Sets the instance metadata. */ + @Deprecated public abstract Builder metadata(Metadata metadata); + /** + * Sets the instance metadata. + */ + public abstract Builder setMetadata(Metadata metadata); + /** * Sets a list of service accounts, with their specified scopes, authorized for this instance. * Service accounts generate access tokens that can be accessed through the metadata server and @@ -202,14 +273,31 @@ public abstract static class Builder { * @see Authenticating from * Google Compute Engine */ + @Deprecated public abstract Builder serviceAccounts(List serviceAccounts); + /** + * Sets a list of service accounts, with their specified scopes, authorized for this instance. + * Service accounts generate access tokens that can be accessed through the metadata server and + * used to authenticate applications on the instance. + * + * @see Authenticating from + * Google Compute Engine + */ + public abstract Builder setServiceAccounts(List serviceAccounts); + /** * Sets the scheduling options for the instance. */ + @Deprecated public abstract Builder schedulingOptions(SchedulingOptions schedulingOptions); - abstract Builder cpuPlatform(String cpuPlatform); + /** + * Sets the scheduling options for the instance. + */ + public abstract Builder setSchedulingOptions(SchedulingOptions schedulingOptions); + + abstract Builder setCpuPlatform(String cpuPlatform); /** * Creates an {@code InstanceInfo} object. @@ -298,103 +386,175 @@ public static final class BuilderImpl extends Builder { } @Override - Builder generatedId(String generatedId) { + Builder setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } @Override + @Deprecated public Builder instanceId(InstanceId instanceId) { + return setInstanceId(instanceId); + } + + @Override + public Builder setInstanceId(InstanceId instanceId) { this.instanceId = checkNotNull(instanceId); return this; } @Override - Builder creationTimestamp(Long creationTimestamp) { + Builder setCreationTimestamp(Long creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } @Override + @Deprecated public Builder description(String description) { + return setDescription(description); + } + + @Override + public Builder setDescription(String description) { this.description = description; return this; } @Override - Builder status(Status status) { + Builder setStatus(Status status) { this.status = status; return this; } @Override - Builder statusMessage(String statusMessage) { + Builder setStatusMessage(String statusMessage) { this.statusMessage = statusMessage; return this; } @Override + @Deprecated public Builder tags(Tags tags) { + return setTags(tags); + } + + @Override + public Builder setTags(Tags tags) { this.tags = tags; return this; } @Override + @Deprecated public Builder machineType(MachineTypeId machineType) { + return setMachineType(machineType); + } + + @Override + public Builder setMachineType(MachineTypeId machineType) { this.machineType = checkNotNull(machineType); return this; } @Override + @Deprecated public Builder canIpForward(Boolean canIpForward) { + return setCanIpForward(canIpForward); + } + + @Override + public Builder setCanIpForward(Boolean canIpForward) { this.canIpForward = canIpForward; return this; } @Override + @Deprecated public Builder networkInterfaces(List networkInterfaces) { + return setNetworkInterfaces(networkInterfaces); + } + + @Override + public Builder setNetworkInterfaces(List networkInterfaces) { this.networkInterfaces = ImmutableList.copyOf(checkNotNull(networkInterfaces)); return this; } @Override + @Deprecated public Builder networkInterfaces(NetworkInterface... networkInterfaces) { + return setNetworkInterfaces(networkInterfaces); + } + + @Override + public Builder setNetworkInterfaces(NetworkInterface... networkInterfaces) { this.networkInterfaces = Arrays.asList(networkInterfaces); return this; } @Override + @Deprecated public Builder attachedDisks(List attachedDisks) { + return setAttachedDisks(attachedDisks); + } + + @Override + public Builder setAttachedDisks(List attachedDisks) { this.attachedDisks = ImmutableList.copyOf(checkNotNull(attachedDisks)); return this; } @Override + @Deprecated public Builder attachedDisks(AttachedDisk... attachedDisks) { + return setAttachedDisks(attachedDisks); + } + + @Override + public Builder setAttachedDisks(AttachedDisk... attachedDisks) { this.attachedDisks = Arrays.asList(attachedDisks); return this; } @Override + @Deprecated public Builder metadata(Metadata metadata) { + return setMetadata(metadata); + } + + @Override + public Builder setMetadata(Metadata metadata) { this.metadata = metadata; return this; } @Override + @Deprecated public Builder serviceAccounts(List serviceAccounts) { + return setServiceAccounts(serviceAccounts); + } + + @Override + public Builder setServiceAccounts(List serviceAccounts) { this.serviceAccounts = ImmutableList.copyOf(checkNotNull(serviceAccounts)); return this; } @Override + @Deprecated public Builder schedulingOptions(SchedulingOptions schedulingOptions) { + return setSchedulingOptions(schedulingOptions); + } + + @Override + public Builder setSchedulingOptions(SchedulingOptions schedulingOptions) { this.schedulingOptions = schedulingOptions; return this; } @Override - Builder cpuPlatform(String cpuPlatform) { + Builder setCpuPlatform(String cpuPlatform) { this.cpuPlatform = cpuPlatform; return this; } @@ -428,42 +588,90 @@ public InstanceInfo build() { /** * Returns the service-generated unique identifier for the instance. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated unique identifier for the instance. + */ + public String getGeneratedId() { return generatedId; } /** * Returns the instance identity. */ + @Deprecated public InstanceId instanceId() { + return getInstanceId(); + } + + /** + * Returns the instance identity. + */ + public InstanceId getInstanceId() { return instanceId; } /** * Returns the creation timestamp in milliseconds since epoch. */ + @Deprecated public Long creationTimestamp() { + return getCreationTimestamp(); + } + + /** + * Returns the creation timestamp in milliseconds since epoch. + */ + public Long getCreationTimestamp() { return creationTimestamp; } /** * Returns a textual description of the instance. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns a textual description of the instance. + */ + public String getDescription() { return description; } /** * Returns the status of the instance. */ + @Deprecated public Status status() { + return getStatus(); + } + + /** + * Returns the status of the instance. + */ + public Status getStatus() { return status; } /** * Returns an optional, human-readable explanation of the status. */ + @Deprecated public String statusMessage() { + return getStatusMessage(); + } + + /** + * Returns an optional, human-readable explanation of the status. + */ + public String getStatusMessage() { return statusMessage; } @@ -471,14 +679,31 @@ public String statusMessage() { * Returns the tags of this instance. Tags are used to identify valid sources or targets for * network firewalls. */ + @Deprecated public Tags tags() { + return getTags(); + } + + /** + * Returns the tags of this instance. Tags are used to identify valid sources or targets for + * network firewalls. + */ + public Tags getTags() { return tags; } /** * Returns the machine type identity. */ + @Deprecated public MachineTypeId machineType() { + return getMachineType(); + } + + /** + * Returns the machine type identity. + */ + public MachineTypeId getMachineType() { return machineType; } @@ -497,21 +722,46 @@ public Boolean canIpForward() { * Returns a list of network interfaces. This specifies how this instance is configured to * interact with other network services, such as connecting to the internet. */ + @Deprecated public List networkInterfaces() { + return getNetworkInterfaces(); + } + + /** + * Returns a list of network interfaces. This specifies how this instance is configured to + * interact with other network services, such as connecting to the internet. + */ + public List getNetworkInterfaces() { return networkInterfaces; } /** * Returns a list of disks attached to the instance. */ + @Deprecated public List attachedDisks() { + return getAttachedDisks(); + } + + /** + * Returns a list of disks attached to the instance. + */ + public List getAttachedDisks() { return attachedDisks; } /** * Returns the instance metadata. */ + @Deprecated public Metadata metadata() { + return getMetadata(); + } + + /** + * Returns the instance metadata. + */ + public Metadata getMetadata() { return metadata; } @@ -523,21 +773,50 @@ public Metadata metadata() { * @see Authenticating from * Google Compute Engine */ + @Deprecated public List serviceAccounts() { + return getServiceAccounts(); + } + + /** + * Returns a list of service accounts, with their specified scopes, authorized for this instance. + * Service accounts generate access tokens that can be accessed through the metadata server and + * used to authenticate applications on the instance. + * + * @see Authenticating from + * Google Compute Engine + */ + public List getServiceAccounts() { return serviceAccounts; } /** * Returns the scheduling options for the instance. */ + @Deprecated public SchedulingOptions schedulingOptions() { + return getSchedulingOptions(); + } + + /** + * Returns the scheduling options for the instance. + */ + public SchedulingOptions getSchedulingOptions() { return schedulingOptions; } /** * Returns the CPU platform used by this instance. */ + @Deprecated public String cpuPlatform() { + return getCpuPlatform(); + } + + /** + * Returns the CPU platform used by this instance. + */ + public String getCpuPlatform() { return cpuPlatform; } @@ -586,22 +865,22 @@ public boolean equals(Object obj) { InstanceInfo setProjectId(final String projectId) { Builder builder = toBuilder(); - builder.networkInterfaces(Lists.transform(networkInterfaces, + builder.setNetworkInterfaces(Lists.transform(networkInterfaces, new Function() { @Override public NetworkInterface apply(NetworkInterface networkInterface) { return networkInterface.setProjectId(projectId); } })); - builder.attachedDisks(Lists.transform(attachedDisks, + builder.setAttachedDisks(Lists.transform(attachedDisks, new Function() { @Override public AttachedDisk apply(AttachedDisk attachedDisk) { return attachedDisk.setProjectId(projectId); } })); - return builder.instanceId(instanceId.setProjectId(projectId)) - .machineType(machineType.setProjectId(projectId)) + return builder.setInstanceId(instanceId.setProjectId(projectId)) + .setMachineType(machineType.setProjectId(projectId)) .build(); } @@ -613,10 +892,10 @@ Instance toPb() { if (creationTimestamp != null) { instancePb.setCreationTimestamp(TIMESTAMP_FORMATTER.print(creationTimestamp)); } - instancePb.setName(instanceId.instance()); + instancePb.setName(instanceId.getInstance()); instancePb.setDescription(description); - instancePb.setSelfLink(instanceId.selfLink()); - instancePb.setZone(instanceId.zoneId().selfLink()); + instancePb.setSelfLink(instanceId.getSelfLink()); + instancePb.setZone(instanceId.getZoneId().getSelfLink()); if (status != null) { instancePb.setStatus(status.name()); } @@ -625,7 +904,7 @@ Instance toPb() { instancePb.setTags(tags.toPb()); } if (machineType != null) { - instancePb.setMachineType(machineType.selfLink()); + instancePb.setMachineType(machineType.getSelfLink()); } instancePb.setCanIpForward(canIpForward); if (networkInterfaces != null) { @@ -653,8 +932,17 @@ Instance toPb() { * Returns a builder for an {@code InstanceInfo} object given the instance identity and the * machine type. */ + @Deprecated public static Builder builder(InstanceId instanceId, MachineTypeId machineType) { - return new BuilderImpl(instanceId).machineType(machineType); + return newBuilder(instanceId, machineType); + } + + /** + * Returns a builder for an {@code InstanceInfo} object given the instance identity and the + * machine type. + */ + public static Builder newBuilder(InstanceId instanceId, MachineTypeId machineType) { + return new BuilderImpl(instanceId).setMachineType(machineType); } /** @@ -664,9 +952,9 @@ public static Builder builder(InstanceId instanceId, MachineTypeId machineType) */ public static InstanceInfo of(InstanceId instanceId, MachineTypeId machineType, AttachedDisk disk, NetworkInterface networkInterface) { - return builder(instanceId, machineType) - .attachedDisks(ImmutableList.of(disk)) - .networkInterfaces(ImmutableList.of(networkInterface)) + return newBuilder(instanceId, machineType) + .setAttachedDisks(ImmutableList.of(disk)) + .setNetworkInterfaces(ImmutableList.of(networkInterface)) .build(); } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/License.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/License.java index dc0e49bace31..d57add1f1a29 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/License.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/License.java @@ -44,10 +44,18 @@ public class License implements Serializable { /** * Returns the identity of the license. */ + @Deprecated public LicenseId licenseId() { return licenseId; } + /** + * Returns the identity of the license. + */ + public LicenseId getLicenseId() { + return licenseId; + } + /** * Returns {@code true} if the customer will be charged a license fee for running software that * contains this license on an instance. @@ -80,9 +88,9 @@ public final boolean equals(Object obj) { com.google.api.services.compute.model.License toPb() { com.google.api.services.compute.model.License licensePb = new com.google.api.services.compute.model.License(); - licensePb.setName(licenseId.license()); + licensePb.setName(licenseId.getLicense()); licensePb.setChargesUseFee(chargesUseFee); - licensePb.setSelfLink(licenseId.selfLink()); + licensePb.setSelfLink(licenseId.getSelfLink()); return licensePb; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/LicenseId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/LicenseId.java index 284572ba58bb..273c36d1050f 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/LicenseId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/LicenseId.java @@ -39,7 +39,7 @@ public LicenseId apply(String pb) { static final Function TO_URL_FUNCTION = new Function() { @Override public String apply(LicenseId licenseId) { - return licenseId.selfLink(); + return licenseId.getSelfLink(); } }; @@ -57,13 +57,27 @@ private LicenseId(String project, String license) { /** * Returns the name of the license. */ + @Deprecated public String license() { return license; } + /** + * Returns the name of the license. + */ + public String getLicense() { + return license; + } + @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/global/licenses/" + license; + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/global/licenses/" + license; } @Override @@ -90,7 +104,7 @@ public boolean equals(Object obj) { @Override LicenseId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } return LicenseId.of(projectId, license); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/MachineType.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/MachineType.java index c850b351c946..4ce7aff7c11d 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/MachineType.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/MachineType.java @@ -84,52 +84,52 @@ static final class Builder { private Builder() {} - Builder machineTypeId(MachineTypeId machineTypeId) { + Builder setMachineTypeId(MachineTypeId machineTypeId) { this.machineTypeId = machineTypeId; return this; } - Builder generatedId(String generatedId) { + Builder setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } - Builder creationTimestamp(Long creationTimestamp) { + Builder setCreationTimestamp(Long creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } - Builder description(String description) { + Builder setDescription(String description) { this.description = description; return this; } - Builder cpus(Integer cpus) { + Builder setCpus(Integer cpus) { this.cpus = cpus; return this; } - Builder memoryMb(Integer memoryMb) { + Builder setMemoryMb(Integer memoryMb) { this.memoryMb = memoryMb; return this; } - Builder scratchDisksSizeGb(List scratchDisksSizeGb) { + Builder setScratchDisksSizeGb(List scratchDisksSizeGb) { this.scratchDisksSizeGb = scratchDisksSizeGb; return this; } - Builder maximumPersistentDisks(Integer maximumPersistentDisks) { + Builder setMaximumPersistentDisks(Integer maximumPersistentDisks) { this.maximumPersistentDisks = maximumPersistentDisks; return this; } - Builder maximumPersistentDisksSizeGb(Long maximumPersistentDisksSizeGb) { + Builder setMaximumPersistentDisksSizeGb(Long maximumPersistentDisksSizeGb) { this.maximumPersistentDisksSizeGb = maximumPersistentDisksSizeGb; return this; } - Builder deprecationStatus(DeprecationStatus deprecationStatus) { + Builder setDeprecationStatus(DeprecationStatus deprecationStatus) { this.deprecationStatus = deprecationStatus; return this; } @@ -155,63 +155,135 @@ private MachineType(Builder builder) { /** * Returns the machine type's identity. */ + @Deprecated public MachineTypeId machineTypeId() { + return getMachineTypeId(); + } + + /** + * Returns the machine type's identity. + */ + public MachineTypeId getMachineTypeId() { return machineTypeId; } /** * Returns the service-generated unique identifier for the machine type. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated unique identifier for the machine type. + */ + public String getGeneratedId() { return generatedId; } /** * Returns the creation timestamp in milliseconds since epoch. */ + @Deprecated public Long creationTimestamp() { + return getCreationTimestamp(); + } + + /** + * Returns the creation timestamp in milliseconds since epoch. + */ + public Long getCreationTimestamp() { return creationTimestamp; } /** * Returns an optional textual description of the machine type. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns an optional textual description of the machine type. + */ + public String getDescription() { return description; } /** * Returns the number of virtual CPUs that are available to the instance. */ + @Deprecated public Integer cpus() { + return getCpus(); + } + + /** + * Returns the number of virtual CPUs that are available to the instance. + */ + public Integer getCpus() { return cpus; } /** * Returns the amount of physical memory available to the instance, defined in MB. */ + @Deprecated public Integer memoryMb() { + return getMemoryMb(); + } + + /** + * Returns the amount of physical memory available to the instance, defined in MB. + */ + public Integer getMemoryMb() { return memoryMb; } /** * Returns the size of all extended scratch disks assigned to the instance, defined in GB. */ + @Deprecated public List scratchDisksSizeGb() { + return getScratchDisksSizeGb(); + } + + /** + * Returns the size of all extended scratch disks assigned to the instance, defined in GB. + */ + public List getScratchDisksSizeGb() { return scratchDisksSizeGb; } /** * Returns the maximum number of persistent disks allowed by this instance type. */ + @Deprecated public Integer maximumPersistentDisks() { + return getMaximumPersistentDisks(); + } + + /** + * Returns the maximum number of persistent disks allowed by this instance type. + */ + public Integer getMaximumPersistentDisks() { return maximumPersistentDisks; } /** * Returns the maximum total persistent disks size allowed, defined in GB. */ + @Deprecated public Long maximumPersistentDisksSizeGb() { + return getMaximumPersistentDisksSizeGb(); + } + + /** + * Returns the maximum total persistent disks size allowed, defined in GB. + */ + public Long getMaximumPersistentDisksSizeGb() { return maximumPersistentDisksSizeGb; } @@ -221,7 +293,18 @@ public Long maximumPersistentDisksSizeGb() { * the machine type should not be used. Returns {@code null} if the machine type is not * deprecated. */ + @Deprecated public DeprecationStatus deprecationStatus() { + return getDeprecationStatus(); + } + + /** + * Returns the deprecation status of the machine type. If {@link DeprecationStatus#status()} is + * either {@link DeprecationStatus.Status#DELETED} or {@link DeprecationStatus.Status#OBSOLETE} + * the machine type should not be used. Returns {@code null} if the machine type is not + * deprecated. + */ + public DeprecationStatus getDeprecationStatus() { return deprecationStatus; } @@ -263,9 +346,9 @@ com.google.api.services.compute.model.MachineType toPb() { if (creationTimestamp != null) { machineTypePb.setCreationTimestamp(TIMESTAMP_FORMATTER.print(creationTimestamp)); } - machineTypePb.setName(machineTypeId.type()); + machineTypePb.setName(machineTypeId.getType()); machineTypePb.setDescription(description); - machineTypePb.setSelfLink(machineTypeId.selfLink()); + machineTypePb.setSelfLink(machineTypeId.getSelfLink()); machineTypePb.setGuestCpus(cpus); machineTypePb.setMemoryMb(memoryMb); if (scratchDisksSizeGb != null) { @@ -279,32 +362,32 @@ public ScratchDisks apply(Integer diskSize) { } machineTypePb.setMaximumPersistentDisks(maximumPersistentDisks); machineTypePb.setMaximumPersistentDisksSizeGb(maximumPersistentDisksSizeGb); - machineTypePb.setZone(machineTypeId.zoneId().zone()); + machineTypePb.setZone(machineTypeId.getZoneId().getZone()); if (deprecationStatus != null) { machineTypePb.setDeprecated(deprecationStatus.toPb()); } return machineTypePb; } - static Builder builder() { + static Builder newBuilder() { return new Builder(); } static MachineType fromPb(com.google.api.services.compute.model.MachineType machineTypePb) { - Builder builder = builder(); - builder.machineTypeId(MachineTypeId.fromUrl(machineTypePb.getSelfLink())); + Builder builder = newBuilder(); + builder.setMachineTypeId(MachineTypeId.fromUrl(machineTypePb.getSelfLink())); if (machineTypePb.getId() != null) { - builder.generatedId(machineTypePb.getId().toString()); + builder.setGeneratedId(machineTypePb.getId().toString()); } if (machineTypePb.getCreationTimestamp() != null) { - builder.creationTimestamp( + builder.setCreationTimestamp( TIMESTAMP_FORMATTER.parseMillis(machineTypePb.getCreationTimestamp())); } - builder.description(machineTypePb.getDescription()); - builder.cpus(machineTypePb.getGuestCpus()); - builder.memoryMb(machineTypePb.getMemoryMb()); + builder.setDescription(machineTypePb.getDescription()); + builder.setCpus(machineTypePb.getGuestCpus()); + builder.setMemoryMb(machineTypePb.getMemoryMb()); if (machineTypePb.getScratchDisks() != null) { - builder.scratchDisksSizeGb( + builder.setScratchDisksSizeGb( Lists.transform(machineTypePb.getScratchDisks(), new Function() { @Override public Integer apply(ScratchDisks scratchDiskPb) { @@ -312,10 +395,10 @@ public Integer apply(ScratchDisks scratchDiskPb) { } })); } - builder.maximumPersistentDisks(machineTypePb.getMaximumPersistentDisks()); - builder.maximumPersistentDisksSizeGb(machineTypePb.getMaximumPersistentDisksSizeGb()); + builder.setMaximumPersistentDisks(machineTypePb.getMaximumPersistentDisks()); + builder.setMaximumPersistentDisksSizeGb(machineTypePb.getMaximumPersistentDisksSizeGb()); if (machineTypePb.getDeprecated() != null) { - builder.deprecationStatus( + builder.setDeprecationStatus( DeprecationStatus.fromPb(machineTypePb.getDeprecated(), MachineTypeId.FROM_URL_FUNCTION)); } return builder.build(); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/MachineTypeId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/MachineTypeId.java index bb439c1e29fe..d85bca911ac7 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/MachineTypeId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/MachineTypeId.java @@ -41,7 +41,7 @@ public MachineTypeId apply(String pb) { new Function() { @Override public String apply(MachineTypeId machineTypeId) { - return machineTypeId.selfLink(); + return machineTypeId.getSelfLink(); } }; @@ -61,27 +61,57 @@ private MachineTypeId(String project, String zone, String type) { /** * Returns the name of the machine type. */ + @Deprecated public String type() { + return getType(); + } + + /** + * Returns the name of the machine type. + */ + public String getType() { return type; } /** * Returns the name of the zone this machine type belongs to. */ + @Deprecated public String zone() { + return getZone(); + } + + /** + * Returns the name of the zone this machine type belongs to. + */ + public String getZone() { return zone; } /** * Returns the identity of the zone this machine type belongs to. */ + @Deprecated public ZoneId zoneId() { - return ZoneId.of(project(), zone); + return getZoneId(); + } + + /** + * Returns the identity of the zone this machine type belongs to. + */ + public ZoneId getZoneId() { + return ZoneId.of(getProject(), zone); } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/zones/" + zone + "/machineTypes/" + type; + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/zones/" + zone + "/machineTypes/" + type; } @Override @@ -110,7 +140,7 @@ public boolean equals(Object obj) { @Override MachineTypeId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } return MachineTypeId.of(projectId, zone, type); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Metadata.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Metadata.java index 22ba59834d4b..0c62fc7bda8a 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Metadata.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Metadata.java @@ -83,7 +83,19 @@ public static final class Builder { * a URL in the metadata server. Additionally, to avoid ambiguity, keys must not conflict with * any other metadata keys for the project. Values must be less than or equal to 32768 bytes. */ + @Deprecated public Builder values(Map values) { + return setValues(values); + } + + /** + * Sets the metadata for the instance as key/value pairs. The total size of all keys and + * values must be less than 512 KB. Keys must conform to the following regexp: + * {@code [a-zA-Z0-9-_]+}, and be less than 128 bytes in length. This is reflected as part of + * a URL in the metadata server. Additionally, to avoid ambiguity, keys must not conflict with + * any other metadata keys for the project. Values must be less than or equal to 32768 bytes. + */ + public Builder setValues(Map values) { this.values = Maps.newHashMap(checkNotNull(values)); return this; } @@ -104,7 +116,16 @@ public Builder add(String key, String value) { * Sets the fingerprint for the metadata. This value can be used to update instance's * metadata. */ + @Deprecated public Builder fingerprint(String fingerprint) { + return setFingerprint(fingerprint); + } + + /** + * Sets the fingerprint for the metadata. This value can be used to update instance's + * metadata. + */ + public Builder setFingerprint(String fingerprint) { this.fingerprint = fingerprint; return this; } @@ -125,18 +146,35 @@ private Metadata(Builder builder) { /** * Returns instance's metadata as key/value pairs. */ + @Deprecated public Map values() { return values; } + /** + * Returns instance's metadata as key/value pairs. + */ + public Map getValues() { + return values; + } + /** * Returns the fingerprint for the metadata. This value can be used to update instance's * metadata. */ + @Deprecated public String fingerprint() { return fingerprint; } + /** + * Returns the fingerprint for the metadata. This value can be used to update instance's + * metadata. + */ + public String getFingerprint() { + return fingerprint; + } + /** * Returns a builder for the current instance metadata. */ @@ -182,7 +220,15 @@ com.google.api.services.compute.model.Metadata toPb() { /** * Returns a builder for a {@code Metadata} object. */ + @Deprecated public static Builder builder() { + return newBuilder(); + } + + /** + * Returns a builder for a {@code Metadata} object. + */ + public static Builder newBuilder() { return new Builder(); } @@ -194,19 +240,19 @@ public static Builder builder() { * other metadata keys for the project. Values must be less than or equal to 32768 bytes. */ public static Metadata of(Map values) { - return builder().values(values).build(); + return newBuilder().setValues(values).build(); } static Metadata fromPb(com.google.api.services.compute.model.Metadata metadataPb) { - Builder builder = builder(); + Builder builder = newBuilder(); if (metadataPb.getItems() != null) { Map metadataValues = Maps.newHashMapWithExpectedSize(metadataPb.getItems().size()); for (com.google.api.services.compute.model.Metadata.Items item : metadataPb.getItems()) { metadataValues.put(item.getKey(), item.getValue()); } - builder.values(metadataValues); + builder.setValues(metadataValues); } - return builder.fingerprint(metadataPb.getFingerprint()).build(); + return builder.setFingerprint(metadataPb.getFingerprint()).build(); } } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Network.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Network.java index 51a0287f3fed..3f57619db859 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Network.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Network.java @@ -53,8 +53,8 @@ public static class Builder extends NetworkInfo.Builder { Builder(Compute compute, NetworkId networkId, NetworkConfiguration configuration) { this.compute = compute; this.infoBuilder = new NetworkInfo.BuilderImpl(networkId, configuration); - this.infoBuilder.networkId(networkId); - this.infoBuilder.configuration(configuration); + this.infoBuilder.setNetworkId(networkId); + this.infoBuilder.setConfiguration(configuration); } Builder(Network subnetwork) { @@ -63,32 +63,50 @@ public static class Builder extends NetworkInfo.Builder { } @Override - Builder generatedId(String generatedId) { - infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + infoBuilder.setGeneratedId(generatedId); return this; } @Override - Builder creationTimestamp(Long creationTimestamp) { - infoBuilder.creationTimestamp(creationTimestamp); + Builder setCreationTimestamp(Long creationTimestamp) { + infoBuilder.setCreationTimestamp(creationTimestamp); return this; } @Override + @Deprecated public Builder networkId(NetworkId networkId) { - infoBuilder.networkId(networkId); + return setNetworkId(networkId); + } + + @Override + public Builder setNetworkId(NetworkId networkId) { + infoBuilder.setNetworkId(networkId); return this; } @Override + @Deprecated public Builder description(String description) { - infoBuilder.description(description); + return setDescription(description); + } + + @Override + public Builder setDescription(String description) { + infoBuilder.setDescription(description); return this; } @Override + @Deprecated public Builder configuration(NetworkConfiguration configuration) { - infoBuilder.configuration(configuration); + return setConfiguration(configuration); + } + + @Override + public Builder setConfiguration(NetworkConfiguration configuration) { + infoBuilder.setConfiguration(configuration); return this; } @@ -123,7 +141,7 @@ public boolean exists() { * @throws ComputeException upon failure */ public Network reload(NetworkOption... options) { - return compute.getNetwork(networkId().network(), options); + return compute.getNetwork(getNetworkId().getNetwork(), options); } /** @@ -134,7 +152,7 @@ public Network reload(NetworkOption... options) { * @throws ComputeException upon failure */ public Operation delete(OperationOption... options) { - return compute.deleteNetwork(networkId().network(), options); + return compute.deleteNetwork(getNetworkId().getNetwork(), options); } /** @@ -150,13 +168,21 @@ public Operation delete(OperationOption... options) { */ public Operation createSubnetwork(SubnetworkId subnetworkId, String ipRange, OperationOption... options) { - return compute.create(SubnetworkInfo.of(subnetworkId, networkId(), ipRange), options); + return compute.create(SubnetworkInfo.of(subnetworkId, getNetworkId(), ipRange), options); } /** * Returns the network's {@code Compute} object used to issue requests. */ + @Deprecated public Compute compute() { + return getCompute(); + } + + /** + * Returns the network's {@code Compute} object used to issue requests. + */ + public Compute getCompute() { return compute; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkConfiguration.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkConfiguration.java index 4a7500f66d07..6728784fadf8 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkConfiguration.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkConfiguration.java @@ -62,7 +62,17 @@ public enum Type { * with no subnetworks. This method returns {@link Type#SUBNET} for a network that supports the * creation of subnetworks (either automatic or manual). */ + @Deprecated public Type type() { + return getType(); + } + + /** + * Returns the network's type. This method returns {@link Type#STANDARD} for a standard networks + * with no subnetworks. This method returns {@link Type#SUBNET} for a network that supports the + * creation of subnetworks (either automatic or manual). + */ + public Type getType() { return type; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkId.java index 1108f126588b..298d78ad3d96 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkId.java @@ -41,8 +41,8 @@ public final class NetworkId extends ResourceId { } private NetworkId(NetworkId networkId) { - super(networkId.project()); - this.network = checkNotNull(networkId.network()); + super(networkId.getProject()); + this.network = checkNotNull(networkId.getNetwork()); } /** @@ -54,13 +54,33 @@ private NetworkId(NetworkId networkId) { * * @see RFC1035 */ + @Deprecated public String network() { return network; } + /** + * Returns the name of the network. The network name must be 1-63 characters long and comply with + * RFC1035. Specifically, the name must match the regular expression + * {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a lowercase letter, + * and all following characters must be a dash, lowercase letter, or digit, except the last + * character, which cannot be a dash. + * + * @see RFC1035 + */ + public String getNetwork() { + return network; + } + @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/global/networks/" + network; + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/global/networks/" + network; } @Override @@ -87,7 +107,7 @@ public boolean equals(Object obj) { @Override NetworkId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } return NetworkId.of(projectId, network); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkInfo.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkInfo.java index a7864135b810..74cde200c509 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkInfo.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkInfo.java @@ -71,28 +71,49 @@ public Network apply(NetworkInfo network) { */ public abstract static class Builder { - abstract Builder generatedId(String generatedId); + abstract Builder setGeneratedId(String generatedId); - abstract Builder creationTimestamp(Long creationTimestamp); + abstract Builder setCreationTimestamp(Long creationTimestamp); /** * Sets the identity of the network. */ + @Deprecated public abstract Builder networkId(NetworkId networkId); + /** + * Sets the identity of the network. + */ + public abstract Builder setNetworkId(NetworkId networkId); + /** * Sets an optional textual description of the network. */ + @Deprecated public abstract Builder description(String description); + /** + * Sets an optional textual description of the network. + */ + public abstract Builder setDescription(String description); + /** * Sets the network configuration. Use {@link StandardNetworkConfiguration} to create a standard * network with associated IPv4 range. Use {@link SubnetNetworkConfiguration} to create a * network that could be divided into subnetworks, up to one per region, each with its own * address range. */ + @Deprecated public abstract Builder configuration(NetworkConfiguration configuration); + /** + * Sets the network configuration. Use {@link StandardNetworkConfiguration} to create a standard + * network with associated IPv4 range. Use {@link SubnetNetworkConfiguration} to create a + * network that could be divided into subnetworks, up to one per region, each with its own + * address range. + */ + public abstract Builder setConfiguration(NetworkConfiguration configuration); + /** * Creates a {@code NetworkInfo} object. */ @@ -133,31 +154,49 @@ static final class BuilderImpl extends Builder { } @Override - BuilderImpl generatedId(String generatedId) { + BuilderImpl setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } @Override - BuilderImpl creationTimestamp(Long creationTimestamp) { + BuilderImpl setCreationTimestamp(Long creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } @Override + @Deprecated public BuilderImpl networkId(NetworkId networkId) { + return setNetworkId(networkId); + } + + @Override + public BuilderImpl setNetworkId(NetworkId networkId) { this.networkId = checkNotNull(networkId); return this; } @Override + @Deprecated public BuilderImpl description(String description) { + return setDescription(description); + } + + @Override + public BuilderImpl setDescription(String description) { this.description = description; return this; } @Override + @Deprecated public BuilderImpl configuration(NetworkConfiguration configuration) { + return setConfiguration(configuration); + } + + @Override + public BuilderImpl setConfiguration(NetworkConfiguration configuration) { this.configuration = checkNotNull(configuration); return this; } @@ -179,28 +218,60 @@ public NetworkInfo build() { /** * Returns the service-generated unique identifier for the network. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated unique identifier for the network. + */ + public String getGeneratedId() { return generatedId; } /** * Returns the creation timestamp in milliseconds since epoch. */ + @Deprecated public Long creationTimestamp() { + return getCreationTimestamp(); + } + + /** + * Returns the creation timestamp in milliseconds since epoch. + */ + public Long getCreationTimestamp() { return creationTimestamp; } /** * Returns the network identity. */ + @Deprecated public NetworkId networkId() { + return getNetworkId(); + } + + /** + * Returns the network identity. + */ + public NetworkId getNetworkId() { return networkId; } /** * Returns a textual description of the network. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns a textual description of the network. + */ + public String getDescription() { return description; } @@ -210,7 +281,18 @@ public String description() { * that could be divided into subnetworks, up to one per region, each with its own address range. */ @SuppressWarnings("unchecked") + @Deprecated public T configuration() { + return getConfiguration(); + } + + /** + * Returns the network configuration. Returns a {@link StandardNetworkConfiguration} for standard + * networks with associated IPv4 range. Returns {@link SubnetNetworkConfiguration} for networks + * that could be divided into subnetworks, up to one per region, each with its own address range. + */ + @SuppressWarnings("unchecked") + public T getConfiguration() { return (T) configuration; } @@ -247,7 +329,7 @@ public boolean equals(Object obj) { NetworkInfo setProjectId(String projectId) { return toBuilder() - .networkId(networkId.setProjectId(projectId)) + .setNetworkId(networkId.setProjectId(projectId)) .build(); } @@ -259,9 +341,9 @@ Network toPb() { if (creationTimestamp != null) { networkPb.setCreationTimestamp(TIMESTAMP_FORMATTER.print(creationTimestamp)); } - networkPb.setName(networkId.network()); + networkPb.setName(networkId.getNetwork()); networkPb.setDescription(description); - networkPb.setSelfLink(networkId.selfLink()); + networkPb.setSelfLink(networkId.getSelfLink()); return networkPb; } @@ -271,7 +353,18 @@ Network toPb() { * associated address range. Use {@link SubnetNetworkConfiguration} to create a network that * supports subnetworks, up to one per region, each with its own address range. */ + @Deprecated public static Builder builder(NetworkId networkId, NetworkConfiguration configuration) { + return newBuilder(networkId, configuration); + } + + /** + * Returns a builder for a {@code NetworkInfo} object given the network identity and its + * configuration. Use {@link StandardNetworkConfiguration} to create a standard network with + * associated address range. Use {@link SubnetNetworkConfiguration} to create a network that + * supports subnetworks, up to one per region, each with its own address range. + */ + public static Builder newBuilder(NetworkId networkId, NetworkConfiguration configuration) { return new BuilderImpl(networkId, configuration); } @@ -282,7 +375,7 @@ public static Builder builder(NetworkId networkId, NetworkConfiguration configur * to one per region, each with its own address range. */ public static NetworkInfo of(NetworkId networkId, NetworkConfiguration configuration) { - return builder(networkId, configuration).build(); + return newBuilder(networkId, configuration).build(); } static NetworkInfo fromPb(Network networkPb) { diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkInterface.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkInterface.java index 06964f6641af..13d8652ace36 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkInterface.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/NetworkInterface.java @@ -127,7 +127,15 @@ private Builder(AccessConfig accessConfig) { /** * Sets the name of the access configuration. */ + @Deprecated public Builder name(String name) { + return setName(name); + } + + /** + * Sets the name of the access configuration. + */ + public Builder setName(String name) { this.name = name; return this; } @@ -144,7 +152,24 @@ public Builder name(String name) { * href="https://cloud.google.com/compute/docs/instances-and-network#ephemeraladdress"> * Ephemeral external IP addresses */ + @Deprecated public Builder natIp(String natIp) { + return setNatIp(natIp); + } + + /** + * Sets an external IP address associated with this instance. Specify an unused static + * external IP address available to the project or leave this field undefined to use an IP + * from a shared ephemeral IP address pool. If you specify a static external IP address, it + * must live in the same region as the zone of the instance. + * + * @see + * Ephemeral external IP addresses + * @see + * Ephemeral external IP addresses + */ + public Builder setNatIp(String natIp) { this.natIp = natIp; return this; } @@ -153,7 +178,16 @@ public Builder natIp(String natIp) { * Sets the type of the access configuration. The only supported value is * {@link Type#ONE_TO_ONE_NAT}. */ + @Deprecated public Builder type(Type type) { + return setType(type); + } + + /** + * Sets the type of the access configuration. The only supported value is + * {@link Type#ONE_TO_ONE_NAT}. + */ + public Builder setType(Type type) { this.type = type; return this; } @@ -175,14 +209,30 @@ public AccessConfig build() { /** * Returns the name of the access configuration. */ + @Deprecated public String name() { + return getName(); + } + + /** + * Returns the name of the access configuration. + */ + public String getName() { return name; } /** * Returns an external IP address associated with this instance. */ + @Deprecated public String natIp() { + return getNatIp(); + } + + /** + * Returns an external IP address associated with this instance. + */ + public String getNatIp() { return natIp; } @@ -190,7 +240,16 @@ public String natIp() { * Returns the type of network access configuration. The only supported value is * {@link Type#ONE_TO_ONE_NAT}. */ + @Deprecated public Type type() { + return getType(); + } + + /** + * Returns the type of network access configuration. The only supported value is + * {@link Type#ONE_TO_ONE_NAT}. + */ + public Type getType() { return type; } @@ -236,7 +295,15 @@ com.google.api.services.compute.model.AccessConfig toPb() { /** * Returns a builder for an {@code AccessConfig} object. */ + @Deprecated public static Builder builder() { + return newBuilder(); + } + + /** + * Returns a builder for an {@code AccessConfig} object. + */ + public static Builder newBuilder() { return new Builder(); } @@ -247,7 +314,7 @@ public static Builder builder() { * Static external IP addresses */ public static AccessConfig of(String natIp) { - return builder().natIp(natIp).build(); + return newBuilder().setNatIp(natIp).build(); } /** @@ -258,17 +325,17 @@ public static AccessConfig of(String natIp) { * Ephemeral external IP addresses */ public static AccessConfig of() { - return builder().build(); + return newBuilder().build(); } static AccessConfig fromPb(com.google.api.services.compute.model.AccessConfig configPb) { - Builder builder = builder(); - builder.name(configPb.getName()); + Builder builder = newBuilder(); + builder.setName(configPb.getName()); if (configPb.getNatIP() != null) { - builder.natIp(configPb.getNatIP()); + builder.setNatIp(configPb.getNatIP()); } if (configPb.getType() != null) { - builder.type(Type.valueOf(configPb.getType())); + builder.setType(Type.valueOf(configPb.getType())); } return builder.build(); } @@ -294,7 +361,7 @@ private Builder(NetworkInterface networkInterface) { this.accessConfigurations = networkInterface.accessConfigurations; } - Builder name(String name) { + Builder setName(String name) { this.name = name; return this; } @@ -302,12 +369,20 @@ Builder name(String name) { /** * Sets the identity of the network this interface applies to. */ + @Deprecated public Builder network(NetworkId network) { + return setNetwork(network); + } + + /** + * Sets the identity of the network this interface applies to. + */ + public Builder setNetwork(NetworkId network) { this.network = checkNotNull(network); return this; } - Builder networkIp(String networkIp) { + Builder setNetworkIp(String networkIp) { this.networkIp = networkIp; return this; } @@ -316,7 +391,16 @@ Builder networkIp(String networkIp) { * Sets the identity of the subnetwork this interface applies to. Setting the subnetwork is * not necessary when the network is in "automatic subnet mode". */ + @Deprecated public Builder subnetwork(SubnetworkId subnetwork) { + return setSubnetwork(subnetwork); + } + + /** + * Sets the identity of the subnetwork this interface applies to. Setting the subnetwork is + * not necessary when the network is in "automatic subnet mode". + */ + public Builder setSubnetwork(SubnetworkId subnetwork) { this.subnetwork = subnetwork; return this; } @@ -331,7 +415,22 @@ public Builder subnetwork(SubnetworkId subnetwork) { * @see * Ephemeral external IP addresses */ + @Deprecated public Builder accessConfigurations(List accessConfigurations) { + return setAccessConfigurations(accessConfigurations); + } + + /** + * Sets a list of access configurations for the network interface. Access configurations can be + * used to assign either a static or an ephemeral external IP address to Google Compute Engine + * instances. At the moment, network interfaces only support one access configuration. + * + * @see + * Static external IP addresses + * @see + * Ephemeral external IP addresses + */ + public Builder setAccessConfigurations(List accessConfigurations) { this.accessConfigurations = ImmutableList.copyOf(accessConfigurations); return this; } @@ -346,8 +445,23 @@ public Builder accessConfigurations(List accessConfigurations) { * @see * Ephemeral external IP addresses */ + @Deprecated public Builder accessConfigurations(AccessConfig... accessConfigurations) { - accessConfigurations(Arrays.asList(accessConfigurations)); + return setAccessConfigurations(accessConfigurations); + } + + /** + * Sets a list of access configurations for the network interface. Access configurations can be + * used to assign either a static or an ephemeral external IP address to Google Compute Engine + * instances. At the moment, network interfaces only support one access configuration. + * + * @see + * Static external IP addresses + * @see + * Ephemeral external IP addresses + */ + public Builder setAccessConfigurations(AccessConfig... accessConfigurations) { + setAccessConfigurations(Arrays.asList(accessConfigurations)); return this; } @@ -372,14 +486,31 @@ private NetworkInterface(Builder builder) { * Returns the name of the network interface, generated by the service. For network devices, * these are {@code eth0}, {@code eth1}, etc. */ + @Deprecated public String name() { + return getName(); + } + + /** + * Returns the name of the network interface, generated by the service. For network devices, + * these are {@code eth0}, {@code eth1}, etc. + */ + public String getName() { return name; } /** * Returns the identity of the network this interface applies to. */ + @Deprecated public NetworkId network() { + return getNetwork(); + } + + /** + * Returns the identity of the network this interface applies to. + */ + public NetworkId getNetwork() { return network; } @@ -387,21 +518,46 @@ public NetworkId network() { * An optional IPv4 internal network address assigned by the service to the instance for this * network interface. */ + @Deprecated public String networkIp() { + return getNetworkIp(); + } + + /** + * An optional IPv4 internal network address assigned by the service to the instance for this + * network interface. + */ + public String getNetworkIp() { return networkIp; } /** * Returns the identity of the subnetwork this interface applies to. */ + @Deprecated public SubnetworkId subnetwork() { + return getSubnetwork(); + } + + /** + * Returns the identity of the subnetwork this interface applies to. + */ + public SubnetworkId getSubnetwork() { return subnetwork; } /** * Returns a list of access configurations for the network interface. */ + @Deprecated public List accessConfigurations() { + return getAccessConfigurations(); + } + + /** + * Returns a list of access configurations for the network interface. + */ + public List getAccessConfigurations() { return accessConfigurations; } @@ -440,9 +596,9 @@ com.google.api.services.compute.model.NetworkInterface toPb() { com.google.api.services.compute.model.NetworkInterface interfacePb = new com.google.api.services.compute.model.NetworkInterface(); interfacePb.setName(name); - interfacePb.setNetwork(network.selfLink()); + interfacePb.setNetwork(network.getSelfLink()); if (subnetwork != null) { - interfacePb.setSubnetwork(subnetwork.selfLink()); + interfacePb.setSubnetwork(subnetwork.getSelfLink()); } interfacePb.setNetworkIP(networkIp); if (accessConfigurations != null) { @@ -454,9 +610,9 @@ com.google.api.services.compute.model.NetworkInterface toPb() { NetworkInterface setProjectId(String projectId) { Builder builder = toBuilder(); - builder.network(network.setProjectId(projectId)); + builder.setNetwork(network.setProjectId(projectId)); if (subnetwork != null) { - builder.subnetwork(subnetwork.setProjectId(projectId)); + builder.setSubnetwork(subnetwork.setProjectId(projectId)); } return builder.build(); } @@ -464,40 +620,56 @@ NetworkInterface setProjectId(String projectId) { /** * Returns a builder for a {@code NetworkInterface} object given the network's identity. */ + @Deprecated public static Builder builder(NetworkId networkId) { + return newBuilder(networkId); + } + + /** + * Returns a builder for a {@code NetworkInterface} object given the network's identity. + */ + public static Builder newBuilder(NetworkId networkId) { return new Builder(networkId); } /** * Returns a builder for a {@code NetworkInterface} object given the network's name. */ + @Deprecated public static Builder builder(String network) { - return builder(NetworkId.of(network)); + return newBuilder(network); + } + + /** + * Returns a builder for a {@code NetworkInterface} object given the network's name. + */ + public static Builder newBuilder(String network) { + return newBuilder(NetworkId.of(network)); } /** * Returns a {@code NetworkInterface} object given the network's identity. */ public static NetworkInterface of(NetworkId networkId) { - return builder(networkId).build(); + return newBuilder(networkId).build(); } /** * Returns a {@code NetworkInterface} object given the network's name. */ public static NetworkInterface of(String network) { - return builder(network).build(); + return newBuilder(network).build(); } static NetworkInterface fromPb( com.google.api.services.compute.model.NetworkInterface interfacePb) { - Builder builder = builder(NetworkId.fromUrl(interfacePb.getNetwork())) - .name(interfacePb.getName()); + Builder builder = newBuilder(NetworkId.fromUrl(interfacePb.getNetwork())) + .setName(interfacePb.getName()); if (interfacePb.getSubnetwork() != null) { - builder.subnetwork(SubnetworkId.fromUrl(interfacePb.getSubnetwork())); + builder.setSubnetwork(SubnetworkId.fromUrl(interfacePb.getSubnetwork())); } - builder.networkIp(interfacePb.getNetworkIP()); - builder.accessConfigurations(interfacePb.getAccessConfigs() != null + builder.setNetworkIp(interfacePb.getNetworkIP()); + builder.setAccessConfigurations(interfacePb.getAccessConfigs() != null ? Lists.transform(interfacePb.getAccessConfigs(), AccessConfig.FROM_PB_FUNCTION) : ImmutableList.of()); return builder.build(); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Operation.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Operation.java index 78752e9cdaeb..c1034bc2de77 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Operation.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Operation.java @@ -124,21 +124,45 @@ public com.google.api.services.compute.model.Operation.Error.Errors apply( /** * Returns an error type identifier for this error. */ + @Deprecated public String code() { + return getCode(); + } + + /** + * Returns an error type identifier for this error. + */ + public String getCode() { return code; } /** * Returns the field in the request which caused the error. This value is optional. */ + @Deprecated public String location() { + return getLocation(); + } + + /** + * Returns the field in the request which caused the error. This value is optional. + */ + public String getLocation() { return location; } /** * Returns an optional, human-readable error message. */ + @Deprecated public String message() { + return getMessage(); + } + + /** + * Returns an optional, human-readable error message. + */ + public String getMessage() { return message; } @@ -221,14 +245,31 @@ public com.google.api.services.compute.model.Operation.Warnings apply( * Returns a warning identifier for this warning. For example, {@code NO_RESULTS_ON_PAGE} if * there are no results in the response. */ + @Deprecated public String code() { + return getCode(); + } + + /** + * Returns a warning identifier for this warning. For example, {@code NO_RESULTS_ON_PAGE} if + * there are no results in the response. + */ + public String getCode() { return code; } /** * Returns a human-readable error message. */ + @Deprecated public String message() { + return getMessage(); + } + + /** + * Returns a human-readable error message. + */ + public String getMessage() { return message; } @@ -240,7 +281,20 @@ public String message() { * or a warning about invalid network settings (for example, if an instance attempts to perform * IP forwarding but is not enabled for IP forwarding). */ + @Deprecated public Map metadata() { + return getMetadata(); + } + + /** + * Returns metadata about this warning. Each key provides more detail on the warning being + * returned. For example, for warnings where there are no results in a list request for a + * particular zone, this key might be {@code scope} and the key's value might be the zone name. + * Other examples might be a key indicating a deprecated resource, and a suggested replacement, + * or a warning about invalid network settings (for example, if an instance attempts to perform + * IP forwarding but is not enabled for IP forwarding). + */ + public Map getMetadata() { return metadata; } @@ -368,92 +422,92 @@ static final class Builder { description = operationPb.getDescription(); } - Builder generatedId(String generatedId) { + Builder getGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } - Builder operationId(OperationId operationId) { + Builder setOperationId(OperationId operationId) { this.operationId = checkNotNull(operationId); return this; } - Builder clientOperationId(String clientOperationId) { + Builder setClientOperationId(String clientOperationId) { this.clientOperationId = clientOperationId; return this; } - Builder operationType(String operationType) { + Builder setOperationType(String operationType) { this.operationType = operationType; return this; } - Builder targetLink(String targetLink) { + Builder setTargetLink(String targetLink) { this.targetLink = targetLink; return this; } - Builder targetId(String targetId) { + Builder setTargetId(String targetId) { this.targetId = targetId; return this; } - Builder status(Status status) { + Builder setStatus(Status status) { this.status = status; return this; } - Builder statusMessage(String statusMessage) { + Builder setStatusMessage(String statusMessage) { this.statusMessage = statusMessage; return this; } - Builder user(String user) { + Builder setUser(String user) { this.user = user; return this; } - Builder progress(Integer progress) { + Builder setProgress(Integer progress) { this.progress = progress; return this; } - Builder insertTime(Long insertTime) { + Builder setInsertTime(Long insertTime) { this.insertTime = insertTime; return this; } - Builder startTime(Long startTime) { + Builder setStartTime(Long startTime) { this.startTime = startTime; return this; } - Builder endTime(Long endTime) { + Builder setEndTime(Long endTime) { this.endTime = endTime; return this; } - Builder errors(List errors) { + Builder setErrors(List errors) { this.errors = ImmutableList.copyOf(checkNotNull(errors)); return this; } - Builder warnings(List warnings) { + Builder setWarnings(List warnings) { this.warnings = ImmutableList.copyOf(checkNotNull(warnings)); return this; } - Builder httpErrorStatusCode(Integer httpErrorStatusCode) { + Builder setHttpErrorStatusCode(Integer httpErrorStatusCode) { this.httpErrorStatusCode = httpErrorStatusCode; return this; } - Builder httpErrorMessage(String httpErrorMessage) { + Builder setHttpErrorMessage(String httpErrorMessage) { this.httpErrorMessage = httpErrorMessage; return this; } - Builder description(String description) { + Builder setDescription(String description) { this.description = description; return this; } @@ -489,14 +543,30 @@ private Operation(Builder builder) { /** * Returns the operation's {@code Compute} object used to issue requests. */ + @Deprecated public Compute compute() { + return getCompute(); + } + + /** + * Returns the operation's {@code Compute} object used to issue requests. + */ + public Compute getCompute() { return compute; } /** * Returns the service-generated unique identifier for the operation. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated unique identifier for the operation. + */ + public String getGeneratedId() { return generatedId; } @@ -508,28 +578,57 @@ public String generatedId() { * @see RFC1035 */ @SuppressWarnings("unchecked") + @Deprecated public T operationId() { + return getOperationId(); + } + + /** + * Returns the operation's identity. This method returns an {@link GlobalOperationId} for global + * operations, a {@link RegionOperationId} for region operations and a {@link ZoneOperationId} for + * zone operations. + * + * @see RFC1035 + */ + @SuppressWarnings("unchecked") + public T getOperationId() { return (T) operationId; } /** * Reserved for future use. */ - String clientOperationId() { + String getClientOperationId() { return clientOperationId; } /** * Returns the type of operation. */ + @Deprecated public String operationType() { + return getOperationType(); + } + + /** + * Returns the type of operation. + */ + public String getOperationType() { return operationType; } /** * Returns the URL of the resource that the operation is modifying. */ + @Deprecated public String targetLink() { + return getTargetLink(); + } + + /** + * Returns the URL of the resource that the operation is modifying. + */ + public String getTargetLink() { return targetLink; } @@ -537,28 +636,61 @@ public String targetLink() { * Returns the unique service-defined target ID, which identifies the resource that the operation * is modifying. */ + @Deprecated public String targetId() { + return getTargetId(); + } + + /** + * Returns the unique service-defined target ID, which identifies the resource that the operation + * is modifying. + */ + public String getTargetId() { return targetId; } /** * Returns the status of the operation. */ + @Deprecated public Status status() { + return getStatus(); + } + + /** + * Returns the status of the operation. + */ + public Status getStatus() { return status; } /** * Returns an optional textual description of the current status of the operation. */ + @Deprecated public String statusMessage() { + return getStatusMessage(); + } + + /** + * Returns an optional textual description of the current status of the operation. + */ + public String getStatusMessage() { return statusMessage; } /** * Returns the user who requested the operation, for example: {@code user@example.com}. */ + @Deprecated public String user() { + return getUser(); + } + + /** + * Returns the user who requested the operation, for example: {@code user@example.com}. + */ + public String getUser() { return user; } @@ -568,14 +700,33 @@ public String user() { * the operation will be complete. This number should monotonically increase as the operation * progresses. */ + @Deprecated public Integer progress() { + return getProgress(); + } + + /** + * Returns an optional progress indicator that ranges from 0 to 100. There is no requirement that + * this be linear or support any granularity of operations. This should not be used to guess when + * the operation will be complete. This number should monotonically increase as the operation + * progresses. + */ + public Integer getProgress() { return progress; } /** * Returns the time that this operation was requested. In milliseconds since epoch. */ + @Deprecated public Long insertTime() { + return getInsertTime(); + } + + /** + * Returns the time that this operation was requested. In milliseconds since epoch. + */ + public Long getInsertTime() { return insertTime; } @@ -583,7 +734,16 @@ public Long insertTime() { * Returns the time that this operation was started by the service. In milliseconds since epoch. * This value will be {@code null} if the operation has not started yet. */ + @Deprecated public Long startTime() { + return getStartTime(); + } + + /** + * Returns the time that this operation was started by the service. In milliseconds since epoch. + * This value will be {@code null} if the operation has not started yet. + */ + public Long getStartTime() { return startTime; } @@ -591,7 +751,16 @@ public Long startTime() { * Returns the time that this operation was completed. In milliseconds since epoch. This value * will be {@code null} if the operation has not finished yet. */ + @Deprecated public Long endTime() { + return getEndTime(); + } + + /** + * Returns the time that this operation was completed. In milliseconds since epoch. This value + * will be {@code null} if the operation has not finished yet. + */ + public Long getEndTime() { return endTime; } @@ -599,7 +768,16 @@ public Long endTime() { * Returns the errors encountered while processing this operation, if any. Returns {@code null} if * no error occurred. */ + @Deprecated public List errors() { + return getErrors(); + } + + /** + * Returns the errors encountered while processing this operation, if any. Returns {@code null} if + * no error occurred. + */ + public List getErrors() { return errors; } @@ -607,7 +785,16 @@ public List errors() { * Returns the warnings encountered while processing this operation, if any. Returns {@code null} * if no warning occurred. */ + @Deprecated public List warnings() { + return getWarnings(); + } + + /** + * Returns the warnings encountered while processing this operation, if any. Returns {@code null} + * if no warning occurred. + */ + public List getWarnings() { return warnings; } @@ -615,7 +802,16 @@ public List warnings() { * Returns the HTTP error status code that was returned, if the operation failed. For example, a * {@code 404} means the resource was not found. */ + @Deprecated public Integer httpErrorStatusCode() { + return getHttpErrorStatusCode(); + } + + /** + * Returns the HTTP error status code that was returned, if the operation failed. For example, a + * {@code 404} means the resource was not found. + */ + public Integer getHttpErrorStatusCode() { return httpErrorStatusCode; } @@ -623,14 +819,31 @@ public Integer httpErrorStatusCode() { * Returns the the HTTP error message that was returned, if the operation failed. For example, a * {@code NOT FOUND} message is returned if the resource was not found. */ + @Deprecated public String httpErrorMessage() { + return getHttpErrorMessage(); + } + + /** + * Returns the the HTTP error message that was returned, if the operation failed. For example, a + * {@code NOT FOUND} message is returned if the resource was not found. + */ + public String getHttpErrorMessage() { return httpErrorMessage; } /** * Returns an optional textual description of the operation. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns an optional textual description of the operation. + */ + public String getDescription() { return description; } @@ -660,7 +873,7 @@ public boolean exists() { public boolean isDone() { Operation operation = compute.getOperation(operationId, OperationOption.fields(Compute.OperationField.STATUS)); - return operation == null || operation.status() == Status.DONE; + return operation == null || operation.getStatus() == Status.DONE; } /** @@ -788,14 +1001,14 @@ com.google.api.services.compute.model.Operation toPb() { if (generatedId != null) { operationPb.setId(new BigInteger(generatedId)); } - operationPb.setName(operationId.operation()); + operationPb.setName(operationId.getOperation()); operationPb.setClientOperationId(clientOperationId); - switch (operationId.type()) { + switch (operationId.getType()) { case REGION: - operationPb.setRegion(this.operationId().regionId().selfLink()); + operationPb.setRegion(this.getOperationId().getRegionId().getSelfLink()); break; case ZONE: - operationPb.setZone(this.operationId().zoneId().selfLink()); + operationPb.setZone(this.getOperationId().getZoneId().getSelfLink()); break; } if (operationType != null) { @@ -829,7 +1042,7 @@ com.google.api.services.compute.model.Operation toPb() { } operationPb.setHttpErrorStatusCode(httpErrorStatusCode); operationPb.setHttpErrorMessage(httpErrorMessage); - operationPb.setSelfLink(operationId.selfLink()); + operationPb.setSelfLink(operationId.getSelfLink()); operationPb.setDescription(description); return operationPb; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/OperationId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/OperationId.java index 2a3dc2a28d76..d6f7ddd5dfaf 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/OperationId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/OperationId.java @@ -62,12 +62,26 @@ enum Type { /** * Returns the type of this operation identity. */ + @Deprecated public abstract Type type(); + /** + * Returns the type of this operation identity. + */ + public abstract Type getType(); + /** * Returns the name of the operation resource. */ + @Deprecated public String operation() { + return getOperation(); + } + + /** + * Returns the name of the operation resource. + */ + public String getOperation() { return operation; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Option.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Option.java index de8676b2ac79..1e96726ca83d 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Option.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Option.java @@ -39,11 +39,11 @@ class Option implements Serializable { this.value = value; } - ComputeRpc.Option rpcOption() { + ComputeRpc.Option getRpcOption() { return rpcOption; } - Object value() { + Object getValue() { return value; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Region.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Region.java index 85845283010c..70c1c5b880c2 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Region.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Region.java @@ -108,21 +108,45 @@ public com.google.api.services.compute.model.Quota apply(Quota quota) { /** * Returns the name of the quota metric. */ + @Deprecated public String metric() { + return getMetric(); + } + + /** + * Returns the name of the quota metric. + */ + public String getMetric() { return metric; } /** * Returns the quota limit for this metric. */ + @Deprecated public double limit() { + return getLimit(); + } + + /** + * Returns the quota limit for this metric. + */ + public double getLimit() { return limit; } /** * Returns the current usage for this quota. */ + @Deprecated public double usage() { + return getUsage(); + } + + /** + * Returns the current usage for this quota. + */ + public double getUsage() { return usage; } @@ -177,42 +201,42 @@ static final class Builder { private Builder() {} - Builder regionId(RegionId regionId) { + Builder setRegionId(RegionId regionId) { this.regionId = regionId; return this; } - Builder generatedId(String generatedId) { + Builder setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } - Builder creationTimestamp(Long creationTimestamp) { + Builder setCreationTimestamp(Long creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } - Builder description(String description) { + Builder setDescription(String description) { this.description = description; return this; } - Builder status(Status status) { + Builder setStatus(Status status) { this.status = status; return this; } - Builder zones(List zones) { + Builder setZones(List zones) { this.zones = ImmutableList.copyOf(zones); return this; } - Builder quotas(List quotas) { + Builder setQuotas(List quotas) { this.quotas = ImmutableList.copyOf(quotas); return this; } - Builder deprecationStatus(DeprecationStatus deprecationStatus) { + Builder setDeprecationStatus(DeprecationStatus deprecationStatus) { this.deprecationStatus = deprecationStatus; return this; } @@ -236,49 +260,105 @@ private Region(Builder builder) { /** * Returns the region's identity. */ + @Deprecated public RegionId regionId() { + return getRegionId(); + } + + /** + * Returns the region's identity. + */ + public RegionId getRegionId() { return regionId; } /** * Returns the service-generated unique identifier for the region. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated unique identifier for the region. + */ + public String getGeneratedId() { return generatedId; } /** * Returns the creation timestamp in milliseconds since epoch. */ + @Deprecated public Long creationTimestamp() { + return getCreationTimestamp(); + } + + /** + * Returns the creation timestamp in milliseconds since epoch. + */ + public Long getCreationTimestamp() { return creationTimestamp; } /** * Returns an optional textual description of the region. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns an optional textual description of the region. + */ + public String getDescription() { return description; } /** * Returns the status of the status. */ + @Deprecated public Status status() { + return getStatus(); + } + + /** + * Returns the status of the status. + */ + public Status getStatus() { return status; } /** * Returns a list of identities of zones available in this region. */ + @Deprecated public List zones() { + return getZones(); + } + + /** + * Returns a list of identities of zones available in this region. + */ + public List getZones() { return zones; } /** * Returns quotas assigned to this region. */ + @Deprecated public List quotas() { + return getQuotas(); + } + + /** + * Returns quotas assigned to this region. + */ + public List getQuotas() { return quotas; } @@ -287,7 +367,17 @@ public List quotas() { * {@link DeprecationStatus.Status#DELETED} or {@link DeprecationStatus.Status#OBSOLETE} the * region should not be used. Returns {@code null} if the region is not deprecated. */ + @Deprecated public DeprecationStatus deprecationStatus() { + return getDeprecationStatus(); + } + + /** + * Returns the deprecation status of the region. If {@link DeprecationStatus#status()} is either + * {@link DeprecationStatus.Status#DELETED} or {@link DeprecationStatus.Status#OBSOLETE} the + * region should not be used. Returns {@code null} if the region is not deprecated. + */ + public DeprecationStatus getDeprecationStatus() { return deprecationStatus; } @@ -327,9 +417,9 @@ com.google.api.services.compute.model.Region toPb() { if (creationTimestamp != null) { regionPb.setCreationTimestamp(TIMESTAMP_FORMATTER.print(creationTimestamp)); } - regionPb.setName(regionId.region()); + regionPb.setName(regionId.getRegion()); regionPb.setDescription(description); - regionPb.setSelfLink(regionId.selfLink()); + regionPb.setSelfLink(regionId.getSelfLink()); if (status != null) { regionPb.setStatus(status.name()); } @@ -351,25 +441,26 @@ static Builder builder() { static Region fromPb(com.google.api.services.compute.model.Region regionPb) { Builder builder = builder(); - builder.regionId(RegionId.fromUrl(regionPb.getSelfLink())); + builder.setRegionId(RegionId.fromUrl(regionPb.getSelfLink())); if (regionPb.getId() != null) { - builder.generatedId(regionPb.getId().toString()); + builder.setGeneratedId(regionPb.getId().toString()); } if (regionPb.getCreationTimestamp() != null) { - builder.creationTimestamp(TIMESTAMP_FORMATTER.parseMillis(regionPb.getCreationTimestamp())); + builder.setCreationTimestamp( + TIMESTAMP_FORMATTER.parseMillis(regionPb.getCreationTimestamp())); } - builder.description(regionPb.getDescription()); + builder.setDescription(regionPb.getDescription()); if (regionPb.getStatus() != null) { - builder.status(Status.valueOf(regionPb.getStatus())); + builder.setStatus(Status.valueOf(regionPb.getStatus())); } if (regionPb.getZones() != null) { - builder.zones(Lists.transform(regionPb.getZones(), ZoneId.FROM_URL_FUNCTION)); + builder.setZones(Lists.transform(regionPb.getZones(), ZoneId.FROM_URL_FUNCTION)); } if (regionPb.getQuotas() != null) { - builder.quotas(Lists.transform(regionPb.getQuotas(), Quota.FROM_PB_FUNCTION)); + builder.setQuotas(Lists.transform(regionPb.getQuotas(), Quota.FROM_PB_FUNCTION)); } if (regionPb.getDeprecated() != null) { - builder.deprecationStatus( + builder.setDeprecationStatus( DeprecationStatus.fromPb(regionPb.getDeprecated(), RegionId.FROM_URL_FUNCTION)); } return builder.build(); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionAddressId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionAddressId.java index 9e81b3ca909a..bcc5870a1e26 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionAddressId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionAddressId.java @@ -41,27 +41,55 @@ private RegionAddressId(String project, String region, String address) { } @Override + @Deprecated public Type type() { + return getType(); + } + + @Override + public Type getType() { return Type.REGION; } /** * Returns the name of the region this address belongs to. */ + @Deprecated public String region() { return region; } + /** + * Returns the name of the region this address belongs to. + */ + public String getRegion() { + return region; + } + /** * Returns the identity of the region this address belongs to. */ + @Deprecated public RegionId regionId() { - return RegionId.of(project(), region); + return RegionId.of(getProject(), region); + } + + /** + * Returns the identity of the region this address belongs to. + */ + public RegionId getRegionId() { + return RegionId.of(getProject(), region); } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/regions/" + region + "/addresses/" + address(); + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/regions/" + region + "/addresses/" + getAddress(); } @Override @@ -88,10 +116,10 @@ public boolean equals(Object obj) { @Override RegionAddressId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } - return RegionAddressId.of(projectId, region, address()); + return RegionAddressId.of(projectId, region, getAddress()); } /** @@ -104,7 +132,7 @@ RegionAddressId setProjectId(String projectId) { * @see RFC1035 */ public static RegionAddressId of(RegionId regionId, String address) { - return new RegionAddressId(regionId.project(), regionId.region(), address); + return new RegionAddressId(regionId.getProject(), regionId.getRegion(), address); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionForwardingRuleId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionForwardingRuleId.java index f1f2460ef811..a15e03222d9a 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionForwardingRuleId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionForwardingRuleId.java @@ -41,7 +41,7 @@ public RegionForwardingRuleId apply(String pb) { new Function() { @Override public String apply(RegionForwardingRuleId forwardingRuleId) { - return forwardingRuleId.selfLink(); + return forwardingRuleId.getSelfLink(); } }; @@ -57,27 +57,55 @@ private RegionForwardingRuleId(String project, String region, String rule) { } @Override + @Deprecated public Type type() { + return getType(); + } + + @Override + public Type getType() { return Type.REGION; } /** * Returns the name of the region this forwarding rule belongs to. */ + @Deprecated public String region() { return region; } + /** + * Returns the name of the region this forwarding rule belongs to. + */ + public String getRegion() { + return region; + } + /** * Returns the identity of the region this forwarding rule belongs to. */ + @Deprecated public RegionId regionId() { - return RegionId.of(project(), region); + return RegionId.of(getProject(), region); + } + + /** + * Returns the identity of the region this forwarding rule belongs to. + */ + public RegionId getRegionId() { + return RegionId.of(getProject(), region); } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/regions/" + region + "/forwardingRules/" + rule(); + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/regions/" + region + "/forwardingRules/" + getRule(); } @Override @@ -104,10 +132,10 @@ public boolean equals(Object obj) { @Override RegionForwardingRuleId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } - return RegionForwardingRuleId.of(projectId, region, rule()); + return RegionForwardingRuleId.of(projectId, region, getRule()); } /** @@ -120,7 +148,7 @@ RegionForwardingRuleId setProjectId(String projectId) { * @see RFC1035 */ public static RegionForwardingRuleId of(RegionId regionId, String rule) { - return new RegionForwardingRuleId(regionId.project(), regionId.region(), rule); + return new RegionForwardingRuleId(regionId.getProject(), regionId.getRegion(), rule); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionId.java index 1f3c74084692..dce62d7bd267 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionId.java @@ -39,7 +39,7 @@ public RegionId apply(String pb) { static final Function TO_URL_FUNCTION = new Function() { @Override public String apply(RegionId regionId) { - return regionId.selfLink(); + return regionId.getSelfLink(); } }; @@ -55,20 +55,34 @@ private RegionId(String project, String region) { } private RegionId(RegionId regionId) { - super(regionId.project()); - this.region = checkNotNull(regionId.region()); + super(regionId.getProject()); + this.region = checkNotNull(regionId.getRegion()); } /** * Returns the name of the region. */ + @Deprecated public final String region() { + return getRegion(); + } + + /** + * Returns the name of the region. + */ + public String getRegion() { return region; } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/regions/" + region; + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/regions/" + region; } @Override @@ -95,7 +109,7 @@ public boolean equals(Object obj) { @Override RegionId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } return RegionId.of(projectId, region); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionOperationId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionOperationId.java index f66f3cc615bc..1bb834118b0a 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionOperationId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/RegionOperationId.java @@ -41,27 +41,55 @@ private RegionOperationId(String project, String region, String operation) { } @Override + @Deprecated public Type type() { + return getType(); + } + + @Override + public Type getType() { return Type.REGION; } /** * Returns the name of the region this operation belongs to. */ + @Deprecated public String region() { return region; } + /** + * Returns the name of the region this operation belongs to. + */ + public String getRegion() { + return region; + } + /** * Returns the identity of the region this operation belongs to. */ + @Deprecated public RegionId regionId() { - return RegionId.of(project(), region); + return RegionId.of(getProject(), region); + } + + /** + * Returns the identity of the region this operation belongs to. + */ + public RegionId getRegionId() { + return RegionId.of(getProject(), region); } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/regions/" + region + "/operations/" + operation(); + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/regions/" + region + "/operations/" + getOperation(); } @Override @@ -88,17 +116,17 @@ public boolean equals(Object obj) { @Override RegionOperationId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } - return RegionOperationId.of(projectId, region, operation()); + return RegionOperationId.of(projectId, region, getOperation()); } /** * Returns a region operation identity given the region identity and the operation name. */ public static RegionOperationId of(RegionId regionId, String operation) { - return new RegionOperationId(regionId.project(), regionId.region(), operation); + return new RegionOperationId(regionId.getProject(), regionId.getRegion(), operation); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ResourceId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ResourceId.java index fed67c8fd72a..f3d773e247cf 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ResourceId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ResourceId.java @@ -39,14 +39,30 @@ public abstract class ResourceId implements Serializable { /** * Returns a fully qualified URL to the entity. */ + @Deprecated public String selfLink() { + return getSelfLink(); + } + + /** + * Returns a fully qualified URL to the entity. + */ + public String getSelfLink() { return BASE_URL + project; } /** * Returns the name of the project. */ + @Deprecated public final String project() { + return getProject(); + } + + /** + * Returns the name of the project. + */ + public final String getProject() { return project; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/SchedulingOptions.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/SchedulingOptions.java index 8abac14f8fcb..0752b5b308e4 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/SchedulingOptions.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/SchedulingOptions.java @@ -72,10 +72,18 @@ public Boolean automaticRestart() { /** * Returns the maintenance behavior for the instance. */ + @Deprecated public Maintenance maintenance() { return maintenance; } + /** + * Returns the maintenance behavior for the instance. + */ + public Maintenance getMaintenance() { + return maintenance; + } + /** * Returns {@code true} if the instance is preemptible, {@code false} otherwhise. * diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ServiceAccount.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ServiceAccount.java index 65508a0a4c3f..19d0be7cb68b 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ServiceAccount.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ServiceAccount.java @@ -64,17 +64,33 @@ private ServiceAccount(String email, List scopes) { /** * Returns the email address of the service account. */ + @Deprecated public String email() { return email; } + /** + * Returns the email address of the service account. + */ + public String getEmail() { + return email; + } + /** * Returns the list of scopes to be made available for this service account. */ + @Deprecated public List scopes() { return scopes; } + /** + * Returns the list of scopes to be made available for this service account. + */ + public List getScopes() { + return scopes; + } + @Override public String toString() { return MoreObjects.toStringHelper(this) diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Snapshot.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Snapshot.java index fee0e2fcfac5..3947addb969a 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Snapshot.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Snapshot.java @@ -55,8 +55,8 @@ public static class Builder extends SnapshotInfo.Builder { Builder(Compute compute, SnapshotId snapshotId, DiskId sourceDisk) { this.compute = compute; this.infoBuilder = new SnapshotInfo.BuilderImpl(); - this.infoBuilder.snapshotId(snapshotId); - this.infoBuilder.sourceDisk(sourceDisk); + this.infoBuilder.setSnapshotId(snapshotId); + this.infoBuilder.setSourceDisk(sourceDisk); } Builder(Snapshot snapshot) { @@ -65,68 +65,86 @@ public static class Builder extends SnapshotInfo.Builder { } @Override - Builder generatedId(String generatedId) { - infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + infoBuilder.setGeneratedId(generatedId); return this; } @Override - Builder creationTimestamp(Long creationTimestamp) { - infoBuilder.creationTimestamp(creationTimestamp); + Builder setCreationTimestamp(Long creationTimestamp) { + infoBuilder.setCreationTimestamp(creationTimestamp); return this; } @Override + @Deprecated public Builder snapshotId(SnapshotId snapshotId) { - infoBuilder.snapshotId(snapshotId); + return setSnapshotId(snapshotId); + } + + @Override + public Builder setSnapshotId(SnapshotId snapshotId) { + infoBuilder.setSnapshotId(snapshotId); return this; } @Override + @Deprecated public Builder description(String description) { - infoBuilder.description(description); + return setDescription(description); + } + + @Override + public Builder setDescription(String description) { + infoBuilder.setDescription(description); return this; } @Override - Builder status(Status status) { - infoBuilder.status(status); + Builder setStatus(Status status) { + infoBuilder.setStatus(status); return this; } @Override - Builder diskSizeGb(Long diskSizeGb) { - infoBuilder.diskSizeGb(diskSizeGb); + Builder setDiskSizeGb(Long diskSizeGb) { + infoBuilder.setDiskSizeGb(diskSizeGb); return this; } @Override - Builder licenses(List licenses) { - infoBuilder.licenses(licenses); + Builder setLicenses(List licenses) { + infoBuilder.setLicenses(licenses); return this; } @Override + @Deprecated public Builder sourceDisk(DiskId sourceDisk) { - infoBuilder.sourceDisk(sourceDisk); + return setSourceDisk(sourceDisk); + } + + @Override + public Builder setSourceDisk(DiskId sourceDisk) { + infoBuilder.setSourceDisk(sourceDisk); return this; } @Override - Builder sourceDiskId(String sourceDiskId) { - infoBuilder.sourceDiskId(sourceDiskId); + Builder setSourceDiskId(String sourceDiskId) { + infoBuilder.setSourceDiskId(sourceDiskId); return this; } @Override - Builder storageBytes(Long storageBytes) { - infoBuilder.storageBytes(storageBytes); + Builder setStorageBytes(Long storageBytes) { + infoBuilder.setStorageBytes(storageBytes); return this; } @Override - Builder storageBytesStatus(StorageBytesStatus storageBytesStatus) { - infoBuilder.storageBytesStatus(storageBytesStatus); + Builder setStorageBytesStatus(StorageBytesStatus storageBytesStatus) { + infoBuilder.setStorageBytesStatus(storageBytesStatus); return this; } @@ -161,7 +179,7 @@ public boolean exists() { * @throws ComputeException upon failure */ public Snapshot reload(SnapshotOption... options) { - return compute.getSnapshot(snapshotId().snapshot(), options); + return compute.getSnapshot(getSnapshotId().getSnapshot(), options); } /** @@ -172,13 +190,21 @@ public Snapshot reload(SnapshotOption... options) { * @throws ComputeException upon failure */ public Operation delete(OperationOption... options) { - return compute.deleteSnapshot(snapshotId(), options); + return compute.deleteSnapshot(getSnapshotId(), options); } /** * Returns the snapshot's {@code Compute} object used to issue requests. */ + @Deprecated public Compute compute() { + return getCompute(); + } + + /** + * Returns the snapshot's {@code Compute} object used to issue requests. + */ + public Compute getCompute() { return compute; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/SnapshotDiskConfiguration.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/SnapshotDiskConfiguration.java index 15909b6092d1..ee64b768c8f2 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/SnapshotDiskConfiguration.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/SnapshotDiskConfiguration.java @@ -72,20 +72,43 @@ private Builder(Disk diskPb) { * Restoring a snapshot to a larger size */ @Override + @Deprecated public Builder sizeGb(Long sizeGb) { - super.sizeGb(sizeGb); + return setSizeGb(sizeGb); + } + + /** + * Sets the size of the persistent disk, in GB. If not set the disk will have the size of the + * snapshot. This value can be larger than the snapshot's size. If the provided size is smaller + * than the snapshot's size then disk creation will fail. + * + * @see + * Restoring a snapshot to a larger size + */ + @Override + public Builder setSizeGb(Long sizeGb) { + super.setSizeGb(sizeGb); return this; } /** * Sets the identity of the source snapshot used to create the disk. */ + @Deprecated public Builder sourceSnapshot(SnapshotId sourceSnapshot) { + return setSourceSnapshot(sourceSnapshot); + } + + /** + * Sets the identity of the source snapshot used to create the disk. + */ + public Builder setSourceSnapshot(SnapshotId sourceSnapshot) { this.sourceSnapshot = checkNotNull(sourceSnapshot); return this; } - Builder sourceSnapshotId(String sourceSnapshotId) { + Builder setSourceSnapshotId(String sourceSnapshotId) { this.sourceSnapshotId = sourceSnapshotId; return this; } @@ -108,20 +131,39 @@ private SnapshotDiskConfiguration(Builder builder) { /** * Returns the identity of the source snapshot used to create the disk. */ + @Deprecated public SnapshotId sourceSnapshot() { return sourceSnapshot; } + /** + * Returns the identity of the source snapshot used to create the disk. + */ + public SnapshotId getSourceSnapshot() { + return sourceSnapshot; + } + /** * Returns the service-generated unique id of the snapshot used to create this disk. This value * identifies the exact snapshot that was used to create the persistent disk. For example, if you * created the persistent disk from a snapshot that was later deleted and recreated under the same * name, the source snapshot ID would identify the exact version of the snapshot that was used. */ + @Deprecated public String sourceSnapshotId() { return sourceSnapshotId; } + /** + * Returns the service-generated unique id of the snapshot used to create this disk. This value + * identifies the exact snapshot that was used to create the persistent disk. For example, if you + * created the persistent disk from a snapshot that was later deleted and recreated under the same + * name, the source snapshot ID would identify the exact version of the snapshot that was used. + */ + public String getSourceSnapshotId() { + return sourceSnapshotId; + } + @Override public Builder toBuilder() { return new Builder(this); @@ -149,9 +191,9 @@ public final boolean equals(Object obj) { @Override SnapshotDiskConfiguration setProjectId(String projectId) { - Builder builder = toBuilder().sourceSnapshot(sourceSnapshot.setProjectId(projectId)); - if (diskType() != null) { - builder.diskType(diskType().setProjectId(projectId)); + Builder builder = toBuilder().setSourceSnapshot(sourceSnapshot.setProjectId(projectId)); + if (getDiskType() != null) { + builder.setDiskType(getDiskType().setProjectId(projectId)); } return builder.build(); } @@ -159,14 +201,22 @@ SnapshotDiskConfiguration setProjectId(String projectId) { @Override Disk toPb() { return super.toPb() - .setSourceSnapshot(sourceSnapshot.selfLink()) + .setSourceSnapshot(sourceSnapshot.getSelfLink()) .setSourceSnapshotId(sourceSnapshotId); } /** * Returns a builder for a {@code SnapshotDiskConfiguration} object given the snapshot identity. */ + @Deprecated public static Builder builder(SnapshotId sourceSnapshot) { + return newBuilder(sourceSnapshot); + } + + /** + * Returns a builder for a {@code SnapshotDiskConfiguration} object given the snapshot identity. + */ + public static Builder newBuilder(SnapshotId sourceSnapshot) { return new Builder(sourceSnapshot); } @@ -174,7 +224,7 @@ public static Builder builder(SnapshotId sourceSnapshot) { * Returns a {@code SnapshotDiskConfiguration} object given the snapshot identity. */ public static SnapshotDiskConfiguration of(SnapshotId sourceSnapshot) { - return builder(sourceSnapshot).build(); + return newBuilder(sourceSnapshot).build(); } @SuppressWarnings("unchecked") diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/SnapshotId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/SnapshotId.java index a30d531b65be..349b22354dda 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/SnapshotId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/SnapshotId.java @@ -49,13 +49,33 @@ private SnapshotId(String project, String snapshot) { * * @see RFC1035 */ + @Deprecated public String snapshot() { + return getSnapshot(); + } + + /** + * Returns the name of the snapshot. The name must be 1-63 characters long and comply with + * RFC1035. Specifically, the name must match the regular expression + * {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a lowercase letter, + * and all following characters must be a dash, lowercase letter, or digit, except the last + * character, which cannot be a dash. + * + * @see RFC1035 + */ + public String getSnapshot() { return snapshot; } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/global/snapshots/" + snapshot; + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/global/snapshots/" + snapshot; } @Override @@ -82,7 +102,7 @@ public boolean equals(Object obj) { @Override SnapshotId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } return SnapshotId.of(projectId, snapshot); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/SnapshotInfo.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/SnapshotInfo.java index ce9ebbc7825c..618933dc4017 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/SnapshotInfo.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/SnapshotInfo.java @@ -125,36 +125,54 @@ public enum StorageBytesStatus { */ public abstract static class Builder { - abstract Builder generatedId(String generatedId); + abstract Builder setGeneratedId(String generatedId); - abstract Builder creationTimestamp(Long creationTimestamp); + abstract Builder setCreationTimestamp(Long creationTimestamp); /** * Sets the snapshot identity. */ + @Deprecated public abstract Builder snapshotId(SnapshotId snapshotId); + /** + * Sets the snapshot identity. + */ + public abstract Builder setSnapshotId(SnapshotId snapshotId); + /** * Sets an optional textual description of the snapshot. */ + @Deprecated public abstract Builder description(String description); - abstract Builder status(Status status); + /** + * Sets an optional textual description of the snapshot. + */ + public abstract Builder setDescription(String description); + + abstract Builder setStatus(Status status); - abstract Builder diskSizeGb(Long diskSizeGb); + abstract Builder setDiskSizeGb(Long diskSizeGb); - abstract Builder licenses(List licenses); + abstract Builder setLicenses(List licenses); /** * Sets the identity of the source disk used to create the snapshot. */ + @Deprecated public abstract Builder sourceDisk(DiskId sourceDisk); - abstract Builder sourceDiskId(String sourceDiskId); + /** + * Sets the identity of the source disk used to create the snapshot. + */ + public abstract Builder setSourceDisk(DiskId sourceDisk); + + abstract Builder setSourceDiskId(String sourceDiskId); - abstract Builder storageBytes(Long storageBytes); + abstract Builder setStorageBytes(Long storageBytes); - abstract Builder storageBytesStatus(StorageBytesStatus storageBytesStatus); + abstract Builder setStorageBytesStatus(StorageBytesStatus storageBytesStatus); /** * Creates a {@code SnapshotInfo} object. @@ -219,67 +237,85 @@ static final class BuilderImpl extends Builder { } @Override - BuilderImpl generatedId(String generatedId) { + BuilderImpl setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } @Override - BuilderImpl creationTimestamp(Long creationTimestamp) { + BuilderImpl setCreationTimestamp(Long creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } @Override + @Deprecated public BuilderImpl snapshotId(SnapshotId snapshotId) { + return setSnapshotId(snapshotId); + } + + @Override + public BuilderImpl setSnapshotId(SnapshotId snapshotId) { this.snapshotId = checkNotNull(snapshotId); return this; } @Override + @Deprecated public BuilderImpl description(String description) { + return setDescription(description); + } + + @Override + public BuilderImpl setDescription(String description) { this.description = description; return this; } @Override - BuilderImpl status(Status status) { + BuilderImpl setStatus(Status status) { this.status = status; return this; } @Override - BuilderImpl diskSizeGb(Long diskSizeGb) { + BuilderImpl setDiskSizeGb(Long diskSizeGb) { this.diskSizeGb = diskSizeGb; return this; } @Override - BuilderImpl licenses(List licenses) { + BuilderImpl setLicenses(List licenses) { this.licenses = licenses != null ? ImmutableList.copyOf(licenses) : null; return this; } @Override + @Deprecated public BuilderImpl sourceDisk(DiskId sourceDisk) { + return setSourceDisk(sourceDisk); + } + + @Override + public BuilderImpl setSourceDisk(DiskId sourceDisk) { this.sourceDisk = checkNotNull(sourceDisk); return this; } @Override - BuilderImpl sourceDiskId(String sourceDiskId) { + BuilderImpl setSourceDiskId(String sourceDiskId) { this.sourceDiskId = sourceDiskId; return this; } @Override - BuilderImpl storageBytes(Long storageBytes) { + BuilderImpl setStorageBytes(Long storageBytes) { this.storageBytes = storageBytes; return this; } @Override - BuilderImpl storageBytesStatus(StorageBytesStatus storageBytesStatus) { + BuilderImpl setStorageBytesStatus(StorageBytesStatus storageBytesStatus) { this.storageBytesStatus = storageBytesStatus; return this; } @@ -307,35 +343,75 @@ public SnapshotInfo build() { /** * Returns the service-generated unique identifier for the snapshot. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated unique identifier for the snapshot. + */ + public String getGeneratedId() { return generatedId; } /** * Returns the creation timestamp in milliseconds since epoch. */ + @Deprecated public Long creationTimestamp() { + return getCreationTimestamp(); + } + + /** + * Returns the creation timestamp in milliseconds since epoch. + */ + public Long getCreationTimestamp() { return creationTimestamp; } /** * Returns the snapshot identity. */ + @Deprecated public SnapshotId snapshotId() { + return getSnapshotId(); + } + + /** + * Returns the snapshot identity. + */ + public SnapshotId getSnapshotId() { return snapshotId; } /** * Returns a textual description of the snapshot. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns a textual description of the snapshot. + */ + public String getDescription() { return description; } /** * Returns all applicable publicly visible licenses. */ + @Deprecated public List licenses() { + return getLicenses(); + } + + /** + * Returns all applicable publicly visible licenses. + */ + public List getLicenses() { return licenses; } @@ -344,21 +420,47 @@ public List licenses() { * disks, only after the snapshot has been successfully created and the status is set to * {@code READY}. */ + @Deprecated public Status status() { + return getStatus(); + } + + /** + * Returns the status of the snapshot. A snapshot can be used to create other resources, such as + * disks, only after the snapshot has been successfully created and the status is set to + * {@code READY}. + */ + public Status getStatus() { return status; } /** * Returns the size of the snapshot (in GB). */ + @Deprecated public Long diskSizeGb() { + return getDiskSizeGb(); + } + + /** + * Returns the size of the snapshot (in GB). + */ + public Long getDiskSizeGb() { return diskSizeGb; } /** * Returns the identity of the source disk used to create this snapshot. */ + @Deprecated public DiskId sourceDisk() { + return getSourceDisk(); + } + + /** + * Returns the identity of the source disk used to create this snapshot. + */ + public DiskId getSourceDisk() { return sourceDisk; } @@ -367,7 +469,17 @@ public DiskId sourceDisk() { * may be used to determine whether the snapshot was taken from the current or a previous instance * of a given disk name. */ + @Deprecated public String sourceDiskId() { + return getSourceDiskId(); + } + + /** + * Returns the service-generated unique id of the disk used to create this snapshot. This value + * may be used to determine whether the snapshot was taken from the current or a previous instance + * of a given disk name. + */ + public String getSourceDiskId() { return sourceDiskId; } @@ -375,7 +487,16 @@ public String sourceDiskId() { * Returns the size of the the storage used by the snapshot. As snapshots share storage, this * number is expected to change with snapshot creation/deletion. */ + @Deprecated public Long storageBytes() { + return getStorageBytes(); + } + + /** + * Returns the size of the the storage used by the snapshot. As snapshots share storage, this + * number is expected to change with snapshot creation/deletion. + */ + public Long getStorageBytes() { return storageBytes; } @@ -385,7 +506,18 @@ public Long storageBytes() { * indicates that the size of the snapshot is being updated. {@link StorageBytesStatus#UP_TO_DATE} * indicates that the size of the snapshot is up-to-date. */ + @Deprecated public StorageBytesStatus storageBytesStatus() { + return getStorageBytesStatus(); + } + + /** + * Indicates whether {@link SnapshotInfo#storageBytes()} is in a stable state or it is being + * adjusted as a result of shared storage reallocation. {@link StorageBytesStatus#UPDATING} + * indicates that the size of the snapshot is being updated. {@link StorageBytesStatus#UP_TO_DATE} + * indicates that the size of the snapshot is up-to-date. + */ + public StorageBytesStatus getStorageBytesStatus() { return storageBytesStatus; } @@ -429,8 +561,8 @@ public boolean equals(Object obj) { SnapshotInfo setProjectId(String projectId) { return toBuilder() - .snapshotId(snapshotId.setProjectId(projectId)) - .sourceDisk(sourceDisk.setProjectId(projectId)) + .setSnapshotId(snapshotId.setProjectId(projectId)) + .setSourceDisk(sourceDisk.setProjectId(projectId)) .build(); } @@ -442,9 +574,9 @@ Snapshot toPb() { if (creationTimestamp != null) { snapshotPb.setCreationTimestamp(TIMESTAMP_FORMATTER.print(creationTimestamp)); } - snapshotPb.setName(snapshotId.snapshot()); + snapshotPb.setName(snapshotId.getSnapshot()); snapshotPb.setDescription(description); - snapshotPb.setSelfLink(snapshotId.selfLink()); + snapshotPb.setSelfLink(snapshotId.getSelfLink()); if (status != null) { snapshotPb.setStatus(status.name()); } @@ -453,7 +585,7 @@ Snapshot toPb() { snapshotPb.setLicenses(Lists.transform(licenses, LicenseId.TO_URL_FUNCTION)); } if (sourceDisk != null) { - snapshotPb.setSourceDisk(sourceDisk.selfLink()); + snapshotPb.setSourceDisk(sourceDisk.getSelfLink()); } snapshotPb.setSourceDiskId(sourceDiskId); snapshotPb.setStorageBytes(storageBytes); @@ -467,15 +599,24 @@ Snapshot toPb() { * Returns a builder for a {@code SnapshotInfo} object given the snapshot identity and a source * disk identity. */ + @Deprecated public static Builder builder(SnapshotId snapshotId, DiskId source) { - return new BuilderImpl().snapshotId(snapshotId).sourceDisk(source); + return newBuilder(snapshotId, source); + } + + /** + * Returns a builder for a {@code SnapshotInfo} object given the snapshot identity and a source + * disk identity. + */ + public static Builder newBuilder(SnapshotId snapshotId, DiskId source) { + return new BuilderImpl().setSnapshotId(snapshotId).setSourceDisk(source); } /** * Returns a {@code SnapshotInfo} object given the snapshot identity and a source disk identity. */ public static SnapshotInfo of(SnapshotId snapshotId, DiskId source) { - return builder(snapshotId, source).build(); + return newBuilder(snapshotId, source).build(); } static SnapshotInfo fromPb(Snapshot snapshotPb) { diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/StandardDiskConfiguration.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/StandardDiskConfiguration.java index 90cf9fb7c40b..5138c7d7b8ea 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/StandardDiskConfiguration.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/StandardDiskConfiguration.java @@ -52,8 +52,17 @@ private Builder(Disk diskPb) { * Sets the size of the persistent disk, in GB. If not set, 500GB is used. */ @Override + @Deprecated public Builder sizeGb(Long sizeGb) { - super.sizeGb(sizeGb); + return setSizeGb(sizeGb); + } + + /** + * Sets the size of the persistent disk, in GB. If not set, 500GB is used. + */ + @Override + public Builder setSizeGb(Long sizeGb) { + super.setSizeGb(sizeGb); return this; } @@ -90,16 +99,24 @@ public final boolean equals(Object obj) { @Override StandardDiskConfiguration setProjectId(String projectId) { - if (diskType() == null || diskType().project() != null) { + if (getDiskType() == null || getDiskType().getProject() != null) { return this; } - return toBuilder().diskType(diskType().setProjectId(projectId)).build(); + return toBuilder().setDiskType(getDiskType().setProjectId(projectId)).build(); } /** * Returns a builder for a {@code StandardDiskConfiguration} object. */ + @Deprecated public static Builder builder() { + return newBuilder(); + } + + /** + * Returns a builder for a {@code StandardDiskConfiguration} object. + */ + public static Builder newBuilder() { return new Builder(); } @@ -107,21 +124,21 @@ public static Builder builder() { * Returns a {@code StandardDiskConfiguration} object given the disk type. */ public static StandardDiskConfiguration of(DiskTypeId diskType) { - return builder().diskType(diskType).build(); + return newBuilder().setDiskType(diskType).build(); } /** * Returns a {@code StandardDiskConfiguration} object given the disk size in GB. */ public static StandardDiskConfiguration of(long sizeGb) { - return builder().sizeGb(sizeGb).build(); + return newBuilder().setSizeGb(sizeGb).build(); } /** * Returns a {@code StandardDiskConfiguration} object given the disk type and size in GB. */ public static StandardDiskConfiguration of(DiskTypeId diskType, long sizeGb) { - return builder().diskType(diskType).sizeGb(sizeGb).build(); + return newBuilder().setDiskType(diskType).setSizeGb(sizeGb).build(); } @SuppressWarnings("unchecked") diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/StandardNetworkConfiguration.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/StandardNetworkConfiguration.java index 16aa8a128d0a..1a29e8fb3d06 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/StandardNetworkConfiguration.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/StandardNetworkConfiguration.java @@ -49,7 +49,18 @@ public class StandardNetworkConfiguration extends NetworkConfiguration { * * @see CIDR */ + @Deprecated public String ipRange() { + return getIpRange(); + } + + /** + * Returns the range of internal IPv4 addresses that are legal on this network. This range is a + * CIDR specification, for example: {@code 192.168.0.0/16}. + * + * @see CIDR + */ + public String getIpRange() { return ipRange; } @@ -57,7 +68,16 @@ public String ipRange() { * Returns the gateway IPv4 address for this networks. This value is read only and is selected by * Google Compute Engine, typically as the first usable address in {@code ipRange}. */ + @Deprecated public String gatewayAddress() { + return getGatewayAddress(); + } + + /** + * Returns the gateway IPv4 address for this networks. This value is read only and is selected by + * Google Compute Engine, typically as the first usable address in {@code ipRange}. + */ + public String getGatewayAddress() { return gatewayAddress; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/StorageImageConfiguration.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/StorageImageConfiguration.java index f90e9fa4e13a..3796cf6a688c 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/StorageImageConfiguration.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/StorageImageConfiguration.java @@ -77,7 +77,16 @@ private Builder(Image imagePb) { * Sets the format used to encode and transmit the block device. The only supported value is * {@code TAR}. This is just a container and transmission format, not a runtime format. */ + @Deprecated public Builder containerType(ContainerType containerType) { + return setContainerType(containerType); + } + + /** + * Sets the format used to encode and transmit the block device. The only supported value is + * {@code TAR}. This is just a container and transmission format, not a runtime format. + */ + public Builder setContainerType(ContainerType containerType) { this.containerType = containerType; return this; } @@ -85,7 +94,15 @@ public Builder containerType(ContainerType containerType) { /** * Sets the SHA1 checksum of the disk image before unpackaging. */ + @Deprecated public Builder sha1(String sha1) { + return setSha1(sha1); + } + + /** + * Sets the SHA1 checksum of the disk image before unpackaging. + */ + public Builder setSha1(String sha1) { this.sha1 = sha1; return this; } @@ -94,7 +111,16 @@ public Builder sha1(String sha1) { * Sets the full Google Cloud Storage URL where the disk image is stored (e.g. * {@code gs://bucket/file}). */ + @Deprecated public Builder source(String source) { + return setSource(source); + } + + /** + * Sets the full Google Cloud Storage URL where the disk image is stored (e.g. + * {@code gs://bucket/file}). + */ + public Builder setSource(String source) { this.source = checkNotNull(source); return this; } @@ -119,14 +145,31 @@ private StorageImageConfiguration(Builder builder) { * Returns the format used to encode and transmit the block device. This is just a container and * transmission format, not a runtime format. */ + @Deprecated public ContainerType containerType() { + return getContainerType(); + } + + /** + * Returns the format used to encode and transmit the block device. This is just a container and + * transmission format, not a runtime format. + */ + public ContainerType getContainerType() { return containerType; } /** * Returns the SHA1 checksum of the disk image before unpackaging. */ + @Deprecated public String sha1() { + return getSha1(); + } + + /** + * Returns the SHA1 checksum of the disk image before unpackaging. + */ + public String getSha1() { return sha1; } @@ -134,7 +177,16 @@ public String sha1() { * Returns the full Google Cloud Storage URL where the disk image is stored (e.g. * {@code gs://bucket/file}). */ + @Deprecated public String source() { + return getSource(); + } + + /** + * Returns the full Google Cloud Storage URL where the disk image is stored (e.g. + * {@code gs://bucket/file}). + */ + public String getSource() { return source; } @@ -185,8 +237,17 @@ Image toPb() { * Creates a {@code StorageImageConfiguration} builder given the full Google Cloud Storage URL * where the disk image is stored. */ + @Deprecated public static Builder builder(String source) { - return new Builder().source(source); + return newBuilder(source); + } + + /** + * Creates a {@code StorageImageConfiguration} builder given the full Google Cloud Storage URL + * where the disk image is stored. + */ + public static Builder newBuilder(String source) { + return new Builder().setSource(source); } /** @@ -194,7 +255,7 @@ public static Builder builder(String source) { * where the disk image is stored. */ public static StorageImageConfiguration of(String source) { - return builder(source).build(); + return newBuilder(source).build(); } @SuppressWarnings("unchecked") diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/SubnetNetworkConfiguration.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/SubnetNetworkConfiguration.java index d060e91eab73..727ba1210b8b 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/SubnetNetworkConfiguration.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/SubnetNetworkConfiguration.java @@ -56,7 +56,15 @@ public Boolean autoCreateSubnetworks() { /** * Returns the identities of all networks in this network. */ + @Deprecated public List subnetworks() { + return getSubnetworks(); + } + + /** + * Returns the identities of all networks in this network. + */ + public List getSubnetworks() { return subnetworks; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Subnetwork.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Subnetwork.java index b3929dd937ea..c190d0201415 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Subnetwork.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Subnetwork.java @@ -52,9 +52,9 @@ public static class Builder extends SubnetworkInfo.Builder { Builder(Compute compute, SubnetworkId subnetworkId, NetworkId networkId, String ipRange) { this.compute = compute; this.infoBuilder = new SubnetworkInfo.BuilderImpl(subnetworkId, networkId, ipRange); - this.infoBuilder.subnetworkId(subnetworkId); - this.infoBuilder.network(networkId); - this.infoBuilder.ipRange(ipRange); + this.infoBuilder.setSubnetworkId(subnetworkId); + this.infoBuilder.setNetwork(networkId); + this.infoBuilder.setIpRange(ipRange); } Builder(Subnetwork subnetwork) { @@ -63,44 +63,64 @@ public static class Builder extends SubnetworkInfo.Builder { } @Override - Builder generatedId(String generatedId) { - infoBuilder.generatedId(generatedId); + Builder setGeneratedId(String generatedId) { + infoBuilder.setGeneratedId(generatedId); return this; } @Override - Builder creationTimestamp(Long creationTimestamp) { - infoBuilder.creationTimestamp(creationTimestamp); + Builder setCreationTimestamp(Long creationTimestamp) { + infoBuilder.setCreationTimestamp(creationTimestamp); return this; } + @Override + public Builder setSubnetworkId(SubnetworkId subnetworkId) { + return setSubnetworkId(subnetworkId); + } + @Override public Builder subnetworkId(SubnetworkId subnetworkId) { - infoBuilder.subnetworkId(subnetworkId); + infoBuilder.setSubnetworkId(subnetworkId); return this; } + @Override + public Builder setDescription(String description) { + return setDescription(description); + } + @Override public Builder description(String description) { - infoBuilder.description(description); + infoBuilder.setDescription(description); return this; } @Override - Builder gatewayAddress(String gatewayAddress) { - infoBuilder.gatewayAddress(gatewayAddress); + Builder setGatewayAddress(String gatewayAddress) { + infoBuilder.setGatewayAddress(gatewayAddress); return this; } + @Override + public Builder setNetwork(NetworkId network) { + return setNetwork(network); + } + @Override public Builder network(NetworkId network) { - infoBuilder.network(network); + infoBuilder.setNetwork(network); return this; } + @Override + public Builder setIpRange(String ipRange) { + return setIpRange(ipRange); + } + @Override public Builder ipRange(String ipRange) { - infoBuilder.ipRange(ipRange); + infoBuilder.setIpRange(ipRange); return this; } @@ -135,7 +155,7 @@ public boolean exists() { * @throws ComputeException upon failure */ public Subnetwork reload(SubnetworkOption... options) { - return compute.getSubnetwork(subnetworkId(), options); + return compute.getSubnetwork(getSubnetworkId(), options); } /** @@ -146,13 +166,21 @@ public Subnetwork reload(SubnetworkOption... options) { * @throws ComputeException upon failure */ public Operation delete(OperationOption... options) { - return compute.deleteSubnetwork(subnetworkId(), options); + return compute.deleteSubnetwork(getSubnetworkId(), options); } /** * Returns the subnetwork's {@code Compute} object used to issue requests. */ + @Deprecated public Compute compute() { + return getCompute(); + } + + /** + * Returns the subnetwork's {@code Compute} object used to issue requests. + */ + public Compute getCompute() { return compute; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/SubnetworkId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/SubnetworkId.java index b750847a3d10..cd1c48fe33f4 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/SubnetworkId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/SubnetworkId.java @@ -41,7 +41,7 @@ public SubnetworkId apply(String pb) { new Function() { @Override public String apply(SubnetworkId zoneId) { - return zoneId.selfLink(); + return zoneId.getSelfLink(); } }; @@ -61,15 +61,31 @@ private SubnetworkId(String project, String region, String subnetwork) { /** * Returns the name of the region this subnetwork belongs to. */ + @Deprecated public String region() { + return getRegion(); + } + + /** + * Returns the name of the region this subnetwork belongs to. + */ + public String getRegion() { return region; } /** * Returns the identity of the region this subnetwork belongs to. */ + @Deprecated public RegionId regionId() { - return RegionId.of(project(), region); + return getRegionId(); + } + + /** + * Returns the identity of the region this subnetwork belongs to. + */ + public RegionId getRegionId() { + return RegionId.of(getProject(), region); } /** @@ -81,13 +97,33 @@ public RegionId regionId() { * * @see RFC1035 */ + @Deprecated public String subnetwork() { + return getSubnetwork(); + } + + /** + * Returns the name of the subnetwork. The name must be 1-63 characters long and comply with + * RFC1035. Specifically, the name must match the regular expression + * {@code [a-z]([-a-z0-9]*[a-z0-9])?} which means the first character must be a lowercase letter, + * and all following characters must be a dash, lowercase letter, or digit, except the last + * character, which cannot be a dash. + * + * @see RFC1035 + */ + public String getSubnetwork() { return subnetwork; } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/regions/" + region + "/subnetworks/" + subnetwork; + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/regions/" + region + "/subnetworks/" + subnetwork; } @Override @@ -116,10 +152,10 @@ public boolean equals(Object obj) { @Override SubnetworkId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } - return SubnetworkId.of(projectId, region(), subnetwork); + return SubnetworkId.of(projectId, getRegion(), subnetwork); } /** @@ -132,7 +168,7 @@ SubnetworkId setProjectId(String projectId) { * @see RFC1035 */ public static SubnetworkId of(RegionId regionId, String subnetwork) { - return new SubnetworkId(regionId.project(), regionId.region(), subnetwork); + return new SubnetworkId(regionId.getProject(), regionId.getRegion(), subnetwork); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/SubnetworkInfo.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/SubnetworkInfo.java index a89a5d713f0f..9705030af27a 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/SubnetworkInfo.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/SubnetworkInfo.java @@ -69,28 +69,47 @@ public Subnetwork apply(SubnetworkInfo subnetwork) { */ public abstract static class Builder { - abstract Builder generatedId(String generatedId); + abstract Builder setGeneratedId(String generatedId); - abstract Builder creationTimestamp(Long creationTimestamp); + abstract Builder setCreationTimestamp(Long creationTimestamp); /** * Sets the identity of the subnework. */ + @Deprecated public abstract Builder subnetworkId(SubnetworkId subnetworkId); + /** + * Sets the identity of the subnework. + */ + public abstract Builder setSubnetworkId(SubnetworkId subnetworkId); + /** * Sets an optional textual description of the subnetwork. */ + @Deprecated public abstract Builder description(String description); - abstract Builder gatewayAddress(String gatewayAddress); + /** + * Sets an optional textual description of the subnetwork. + */ + public abstract Builder setDescription(String description); + + abstract Builder setGatewayAddress(String gatewayAddress); /** * Sets the identity of the network to which this subnetwork belongs. Only networks that are in * subnet mode can have subnetworks. */ + @Deprecated public abstract Builder network(NetworkId network); + /** + * Sets the identity of the network to which this subnetwork belongs. Only networks that are in + * subnet mode can have subnetworks. + */ + public abstract Builder setNetwork(NetworkId network); + /** * Sets the range of internal IPv4 addresses that are owned by this subnetwork. This range must * be a CIDR specification, for example: {@code 192.168.0.0/16}. Ranges must be unique and @@ -98,8 +117,18 @@ public abstract static class Builder { * * @see CIDR */ + @Deprecated public abstract Builder ipRange(String ipRange); + /** + * Sets the range of internal IPv4 addresses that are owned by this subnetwork. This range must + * be a CIDR specification, for example: {@code 192.168.0.0/16}. Ranges must be unique and + * non-overlapping within a network. + * + * @see CIDR + */ + public abstract Builder setIpRange(String ipRange); + /** * Creates a {@code SubnetworkInfo} object. */ @@ -150,43 +179,67 @@ static final class BuilderImpl extends Builder { } @Override - BuilderImpl generatedId(String generatedId) { + BuilderImpl setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } @Override - BuilderImpl creationTimestamp(Long creationTimestamp) { + BuilderImpl setCreationTimestamp(Long creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } @Override + @Deprecated public BuilderImpl subnetworkId(SubnetworkId subnetworkId) { + return setSubnetworkId(subnetworkId); + } + + @Override + public BuilderImpl setSubnetworkId(SubnetworkId subnetworkId) { this.subnetworkId = checkNotNull(subnetworkId); return this; } @Override + @Deprecated public BuilderImpl description(String description) { + return setDescription(description); + } + + @Override + public BuilderImpl setDescription(String description) { this.description = description; return this; } @Override - BuilderImpl gatewayAddress(String gatewayAddress) { + BuilderImpl setGatewayAddress(String gatewayAddress) { this.gatewayAddress = gatewayAddress; return this; } @Override + @Deprecated public BuilderImpl network(NetworkId network) { + return setNetwork(network); + } + + @Override + public BuilderImpl setNetwork(NetworkId network) { this.network = checkNotNull(network); return this; } @Override + @Deprecated public BuilderImpl ipRange(String ipRange) { + return setIpRange(ipRange); + } + + @Override + public BuilderImpl setIpRange(String ipRange) { this.ipRange = checkNotNull(ipRange); return this; } @@ -210,35 +263,75 @@ public SubnetworkInfo build() { /** * Returns the service-generated unique identifier for the subnetwork. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated unique identifier for the subnetwork. + */ + public String getGeneratedId() { return generatedId; } /** * Returns the creation timestamp in milliseconds since epoch. */ + @Deprecated public Long creationTimestamp() { + return getCreationTimestamp(); + } + + /** + * Returns the creation timestamp in milliseconds since epoch. + */ + public Long getCreationTimestamp() { return creationTimestamp; } /** * Returns the subnetwork identity. */ + @Deprecated public SubnetworkId subnetworkId() { + return getSubnetworkId(); + } + + /** + * Returns the subnetwork identity. + */ + public SubnetworkId getSubnetworkId() { return subnetworkId; } /** * Returns a textual description of the subnetwork. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns a textual description of the subnetwork. + */ + public String getDescription() { return description; } /** * Returns the gateway IPv4 address for this subnetwork, selected by the service. */ + @Deprecated public String gatewayAddress() { + return getGatewayAddress(); + } + + /** + * Returns the gateway IPv4 address for this subnetwork, selected by the service. + */ + public String getGatewayAddress() { return gatewayAddress; } @@ -246,7 +339,16 @@ public String gatewayAddress() { * Returns the identity of the network to which this subnetwork belongs. Only networks that are in * subnet mode can have subnetworks. */ + @Deprecated public NetworkId network() { + return getNetwork(); + } + + /** + * Returns the identity of the network to which this subnetwork belongs. Only networks that are in + * subnet mode can have subnetworks. + */ + public NetworkId getNetwork() { return network; } @@ -257,10 +359,22 @@ public NetworkId network() { * * @see CIDR */ + @Deprecated public String ipRange() { return ipRange; } + /** + * Returns the range of internal IPv4 addresses that are owned by this subnetwork. This range is a + * CIDR specification, for example: {@code 192.168.0.0/16}. Ranges must be unique and + * non-overlapping within a network. + * + * @see CIDR + */ + public String getIpRange() { + return ipRange; + } + /** * Returns a builder for the current subnetwork. */ @@ -297,8 +411,8 @@ public boolean equals(Object obj) { SubnetworkInfo setProjectId(String projectId) { return toBuilder() - .subnetworkId(subnetworkId.setProjectId(projectId)) - .network(network.setProjectId(projectId)) + .setSubnetworkId(subnetworkId.setProjectId(projectId)) + .setNetwork(network.setProjectId(projectId)) .build(); } @@ -310,11 +424,11 @@ Subnetwork toPb() { if (creationTimestamp != null) { subnetworkPb.setCreationTimestamp(TIMESTAMP_FORMATTER.print(creationTimestamp)); } - subnetworkPb.setName(subnetworkId.subnetwork()); + subnetworkPb.setName(subnetworkId.getSubnetwork()); subnetworkPb.setDescription(description); - subnetworkPb.setSelfLink(subnetworkId.selfLink()); + subnetworkPb.setSelfLink(subnetworkId.getSelfLink()); subnetworkPb.setGatewayAddress(gatewayAddress); - subnetworkPb.setNetwork(network.selfLink()); + subnetworkPb.setNetwork(network.getSelfLink()); subnetworkPb.setIpCidrRange(ipRange); return subnetworkPb; } @@ -327,7 +441,20 @@ Subnetwork toPb() { * * @see CIDR */ + @Deprecated public static Builder builder(SubnetworkId subnetworkId, NetworkId network, String ipRange) { + return newBuilder(subnetworkId, network, ipRange); + } + + /** + * Returns a builder for a {@code SubnetworkInfo} object given the identity of the subnetwork, the + * identity of the network this subnetwork belongs to and the range of IPv4 addresses owned by + * this subnetwork. {@code ipRange} must be a CIDR specification, for example: + * {@code 192.168.0.0/16}. + * + * @see CIDR + */ + public static Builder newBuilder(SubnetworkId subnetworkId, NetworkId network, String ipRange) { return new BuilderImpl(subnetworkId, network, ipRange); } @@ -339,7 +466,7 @@ public static Builder builder(SubnetworkId subnetworkId, NetworkId network, Stri * @see CIDR */ public static SubnetworkInfo of(SubnetworkId subnetworkId, NetworkId network, String ipRange) { - return builder(subnetworkId, network, ipRange).build(); + return newBuilder(subnetworkId, network, ipRange).build(); } static SubnetworkInfo fromPb(Subnetwork subnetworkPb) { diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Tags.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Tags.java index 7be604cd5a64..d8e0366f468a 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Tags.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Tags.java @@ -81,7 +81,18 @@ private Builder(Tags tags) { * * @see RFC1035 */ + @Deprecated public Builder values(Iterable values) { + return setValues(values); + } + + /** + * Sets a list of tags to apply to an instance. Tags are used to identify valid sources or + * targets for network firewalls. Each tag within the list must comply with RFC1035. + * + * @see RFC1035 + */ + public Builder setValues(Iterable values) { this.values = Lists.newArrayList(values); return this; } @@ -92,7 +103,18 @@ public Builder values(Iterable values) { * * @see RFC1035 */ + @Deprecated public Builder values(String... values) { + return setValues(values); + } + + /** + * Sets a list of tags to apply to an instance. Tags are used to identify valid sources or + * targets for network firewalls. Each tag within the list must comply with RFC1035. + * + * @see RFC1035 + */ + public Builder setValues(String... values) { this.values = Lists.newArrayList(Arrays.asList(checkNotNull(values))); return this; } @@ -111,7 +133,15 @@ public Builder add(String tag) { /** * Sets the fingerprint for the tags. This value is needed to update instance's tags. */ + @Deprecated public Builder fingerprint(String fingerprint) { + return setFingerprint(fingerprint); + } + + /** + * Sets the fingerprint for the tags. This value is needed to update instance's tags. + */ + public Builder setFingerprint(String fingerprint) { this.fingerprint = fingerprint; return this; } @@ -135,14 +165,33 @@ private Tags(Builder builder) { * * @see RFC1035 */ + @Deprecated public List values() { + return getValues(); + } + + /** + * Returns a list of tags to apply to an instance. Tags are used to identify valid sources or + * targets for network firewalls. Each tag within the list must comply with RFC1035. + * + * @see RFC1035 + */ + public List getValues() { return values; } /** * Returns the fingerprint for the tags. This value is needed to update instance's tags. */ + @Deprecated public String fingerprint() { + return getFingerprint(); + } + + /** + * Returns the fingerprint for the tags. This value is needed to update instance's tags. + */ + public String getFingerprint() { return fingerprint; } @@ -185,8 +234,9 @@ com.google.api.services.compute.model.Tags toPb() { * * @see RFC1035 */ + @Deprecated public static Builder builder(Iterable values) { - return new Builder().values(values); + return newBuilder(values); } /** @@ -195,8 +245,29 @@ public static Builder builder(Iterable values) { * * @see RFC1035 */ + public static Builder newBuilder(Iterable values) { + return new Builder().setValues(values); + } + + /** + * Returns a builder for a {@code Tags} object given the tags to apply to the instance. Each tag + * within the list must comply with RFC1035. + * + * @see RFC1035 + */ + @Deprecated public static Builder builder(String... values) { - return new Builder().values(values); + return newBuilder(values); + } + + /** + * Returns a builder for a {@code Tags} object given the tags to apply to the instance. Each tag + * within the list must comply with RFC1035. + * + * @see RFC1035 + */ + public static Builder newBuilder(String... values) { + return new Builder().setValues(values); } /** @@ -206,7 +277,7 @@ public static Builder builder(String... values) { * @see RFC1035 */ public static Tags of(Iterable values) { - return builder(values).build(); + return newBuilder(values).build(); } /** @@ -216,12 +287,12 @@ public static Tags of(Iterable values) { * @see RFC1035 */ public static Tags of(String... values) { - return builder(values).build(); + return newBuilder(values).build(); } static Tags fromPb(com.google.api.services.compute.model.Tags tagsPb) { Builder builder = - builder(tagsPb.getItems() != null ? tagsPb.getItems() : ImmutableList.of()); - return builder.fingerprint(tagsPb.getFingerprint()).build(); + newBuilder(tagsPb.getItems() != null ? tagsPb.getItems() : ImmutableList.of()); + return builder.setFingerprint(tagsPb.getFingerprint()).build(); } } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Zone.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Zone.java index 1534506c55a3..bd90ca6ee050 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Zone.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Zone.java @@ -80,37 +80,37 @@ static final class Builder { private Builder() {} - Builder zoneId(ZoneId zoneId) { + Builder setZoneId(ZoneId zoneId) { this.zoneId = zoneId; return this; } - Builder generatedId(String generatedId) { + Builder setGeneratedId(String generatedId) { this.generatedId = generatedId; return this; } - Builder creationTimestamp(Long creationTimestamp) { + Builder setCreationTimestamp(Long creationTimestamp) { this.creationTimestamp = creationTimestamp; return this; } - Builder description(String description) { + Builder setDescription(String description) { this.description = description; return this; } - Builder status(Status status) { + Builder setStatus(Status status) { this.status = status; return this; } - Builder region(RegionId region) { + Builder setRegion(RegionId region) { this.region = region; return this; } - Builder deprecationStatus(DeprecationStatus deprecationStatus) { + Builder setDeprecationStatus(DeprecationStatus deprecationStatus) { this.deprecationStatus = deprecationStatus; return this; } @@ -133,42 +133,90 @@ private Zone(Builder builder) { /** * Returns the zone's identity. */ + @Deprecated public ZoneId zoneId() { + return getZoneId(); + } + + /** + * Returns the zone's identity. + */ + public ZoneId getZoneId() { return zoneId; } /** * Returns the creation timestamp in milliseconds since epoch. */ + @Deprecated public Long creationTimestamp() { + return getCreationTimestamp(); + } + + /** + * Returns the creation timestamp in milliseconds since epoch. + */ + public Long getCreationTimestamp() { return creationTimestamp; } /** * Returns an optional textual description of the zone. */ + @Deprecated public String description() { + return getDescription(); + } + + /** + * Returns an optional textual description of the zone. + */ + public String getDescription() { return description; } /** * Returns the service-generated unique identifier for the zone. */ + @Deprecated public String generatedId() { + return getGeneratedId(); + } + + /** + * Returns the service-generated unique identifier for the zone. + */ + public String getGeneratedId() { return generatedId; } /** * Returns the status of the zone. */ + @Deprecated public Status status() { + return getStatus(); + } + + /** + * Returns the status of the zone. + */ + public Status getStatus() { return status; } /** * Returns the identity of the region that hosts the zone. */ + @Deprecated public RegionId region() { + return getRegion(); + } + + /** + * Returns the identity of the region that hosts the zone. + */ + public RegionId getRegion() { return region; } @@ -177,7 +225,17 @@ public RegionId region() { * {@link DeprecationStatus.Status#DELETED} or {@link DeprecationStatus.Status#OBSOLETE} the zone * should not be used. Returns {@code null} if the zone is not deprecated. */ + @Deprecated public DeprecationStatus deprecationStatus() { + return getDeprecationStatus(); + } + + /** + * Returns the deprecation status of the zone. If {@link DeprecationStatus#status()} is either + * {@link DeprecationStatus.Status#DELETED} or {@link DeprecationStatus.Status#OBSOLETE} the zone + * should not be used. Returns {@code null} if the zone is not deprecated. + */ + public DeprecationStatus getDeprecationStatus() { return deprecationStatus; } @@ -216,14 +274,14 @@ com.google.api.services.compute.model.Zone toPb() { if (creationTimestamp != null) { zonePb.setCreationTimestamp(TIMESTAMP_FORMATTER.print(creationTimestamp)); } - zonePb.setName(zoneId.zone()); + zonePb.setName(zoneId.getZone()); zonePb.setDescription(description); - zonePb.setSelfLink(zoneId.selfLink()); + zonePb.setSelfLink(zoneId.getSelfLink()); if (status != null) { zonePb.setStatus(status.name()); } if (region != null) { - zonePb.setRegion(region.selfLink()); + zonePb.setRegion(region.getSelfLink()); } if (deprecationStatus != null) { zonePb.setDeprecated(deprecationStatus.toPb()); @@ -237,22 +295,22 @@ static Builder builder() { static Zone fromPb(com.google.api.services.compute.model.Zone zonePb) { Builder builder = builder(); - builder.zoneId(ZoneId.fromUrl(zonePb.getSelfLink())); + builder.setZoneId(ZoneId.fromUrl(zonePb.getSelfLink())); if (zonePb.getId() != null) { - builder.generatedId(zonePb.getId().toString()); + builder.setGeneratedId(zonePb.getId().toString()); } if (zonePb.getCreationTimestamp() != null) { - builder.creationTimestamp(TIMESTAMP_FORMATTER.parseMillis(zonePb.getCreationTimestamp())); + builder.setCreationTimestamp(TIMESTAMP_FORMATTER.parseMillis(zonePb.getCreationTimestamp())); } - builder.description(zonePb.getDescription()); + builder.setDescription(zonePb.getDescription()); if (zonePb.getStatus() != null) { - builder.status(Status.valueOf(zonePb.getStatus())); + builder.setStatus(Status.valueOf(zonePb.getStatus())); } if (zonePb.getRegion() != null) { - builder.region(RegionId.fromUrl(zonePb.getRegion())); + builder.setRegion(RegionId.fromUrl(zonePb.getRegion())); } if (zonePb.getDeprecated() != null) { - builder.deprecationStatus( + builder.setDeprecationStatus( DeprecationStatus.fromPb(zonePb.getDeprecated(), ZoneId.FROM_URL_FUNCTION)); } return builder.build(); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ZoneId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ZoneId.java index 1a1e2bf207be..b95bcbce766d 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ZoneId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ZoneId.java @@ -39,7 +39,7 @@ public ZoneId apply(String pb) { static final Function TO_URL_FUNCTION = new Function() { @Override public String apply(ZoneId zoneId) { - return zoneId.selfLink(); + return zoneId.getSelfLink(); } }; @@ -57,13 +57,27 @@ private ZoneId(String project, String zone) { /** * Returns the name of the zone. */ + @Deprecated public final String zone() { + return getZone(); + } + + /** + * Returns the name of the zone. + */ + public String getZone() { return zone; } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/zones/" + zone; + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/zones/" + zone; } @Override @@ -90,7 +104,7 @@ public boolean equals(Object obj) { @Override ZoneId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } return ZoneId.of(projectId, zone); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ZoneOperationId.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ZoneOperationId.java index 1403773d2d99..34a5c6624be5 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ZoneOperationId.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ZoneOperationId.java @@ -41,27 +41,55 @@ private ZoneOperationId(String project, String zone, String operation) { } @Override + @Deprecated public Type type() { + return getType(); + } + + @Override + public Type getType() { return Type.ZONE; } /** * Returns the name of the zone this operation belongs to. */ + @Deprecated public String zone() { + return getZone(); + } + + /** + * Returns the name of the zone this operation belongs to. + */ + public String getZone() { return zone; } /** * Returns the identity of the zone this address belongs to. */ + @Deprecated public ZoneId zoneId() { - return ZoneId.of(project(), zone); + return getZoneId(); + } + + /** + * Returns the identity of the zone this address belongs to. + */ + public ZoneId getZoneId() { + return ZoneId.of(getProject(), zone); } @Override + @Deprecated public String selfLink() { - return super.selfLink() + "/zones/" + zone + "/operations/" + operation(); + return getSelfLink(); + } + + @Override + public String getSelfLink() { + return super.getSelfLink() + "/zones/" + zone + "/operations/" + getOperation(); } @Override @@ -88,17 +116,17 @@ public boolean equals(Object obj) { @Override ZoneOperationId setProjectId(String projectId) { - if (project() != null) { + if (getProject() != null) { return this; } - return ZoneOperationId.of(projectId, zone, operation()); + return ZoneOperationId.of(projectId, zone, getOperation()); } /** * Returns a zone operation identity given the zone identity and the operation name. */ public static ZoneOperationId of(ZoneId zoneId, String operation) { - return new ZoneOperationId(zoneId.project(), zoneId.zone(), operation); + return new ZoneOperationId(zoneId.getProject(), zoneId.getZone(), operation); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/package-info.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/package-info.java index f602b5d8831f..51c9babdaeb6 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/package-info.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/package-info.java @@ -29,7 +29,7 @@ * String snapshotName = "disk-name-snapshot"; * Operation operation = disk.createSnapshot(snapshotName); * operation = operation.waitFor(); - * if (operation.errors() == null) { + * if (operation.getErrors() == null) { * // use snapshot * Snapshot snapshot = compute.getSnapshot(snapshotName); * } @@ -49,7 +49,7 @@ * Operation operation = * compute.create(InstanceInfo.of(instanceId, machineTypeId, attachedDisk, networkInterface)); * operation = operation.waitFor(); - * if (operation.errors() == null) { + * if (operation.getErrors() == null) { * // use instance * Instance instance = compute.getInstance(instanceId); * }} diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/RemoteComputeHelper.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/RemoteComputeHelper.java index eb443a25af28..92937c824ba0 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/RemoteComputeHelper.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/RemoteComputeHelper.java @@ -48,7 +48,15 @@ private RemoteComputeHelper(ComputeOptions options) { /** * Returns a {@link ComputeOptions} object to be used for testing. */ + @Deprecated public ComputeOptions options() { + return getOptions(); + } + + /** + * Returns a {@link ComputeOptions} object to be used for testing. + */ + public ComputeOptions getOptions() { return options; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/package-info.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/package-info.java index d30df3b1fd11..897999dfcce5 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/package-info.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/package-info.java @@ -22,7 +22,7 @@ *

Before the test: *

 {@code
  * RemoteComputeHelper computeHelper = RemoteComputeHelper.create();
- * Compute compute = computeHelper.options().service();
+ * Compute compute = computeHelper.getOptions().service();
  * } 
* * @see diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressIdTest.java index 361012f3a30f..ae0ec0bf3900 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressIdTest.java @@ -41,6 +41,31 @@ public class AddressIdTest { @Test public void testOf() { + GlobalAddressId addressId = GlobalAddressId.of(PROJECT, NAME); + assertEquals(PROJECT, addressId.getProject()); + assertEquals(NAME, addressId.getAddress()); + assertEquals(GLOBAL_URL, addressId.getSelfLink()); + addressId = GlobalAddressId.of(NAME); + assertNull(addressId.getProject()); + assertEquals(NAME, addressId.getAddress()); + RegionAddressId regionAddressId = RegionAddressId.of(PROJECT, REGION, NAME); + assertEquals(PROJECT, regionAddressId.getProject()); + assertEquals(REGION, regionAddressId.getRegion()); + assertEquals(NAME, regionAddressId.getAddress()); + assertEquals(REGION_URL, regionAddressId.getSelfLink()); + regionAddressId = RegionAddressId.of(RegionId.of(PROJECT, REGION), NAME); + assertEquals(PROJECT, regionAddressId.getProject()); + assertEquals(REGION, regionAddressId.getRegion()); + assertEquals(NAME, regionAddressId.getAddress()); + assertEquals(REGION_URL, regionAddressId.getSelfLink()); + regionAddressId = RegionAddressId.of(REGION, NAME); + assertNull(regionAddressId.getProject()); + assertEquals(REGION, regionAddressId.getRegion()); + assertEquals(NAME, regionAddressId.getAddress()); + } + + @Test + public void testOfDeprecated() { GlobalAddressId addressId = GlobalAddressId.of(PROJECT, NAME); assertEquals(PROJECT, addressId.project()); assertEquals(NAME, addressId.address()); @@ -67,7 +92,7 @@ public void testOf() { @Test public void testToAndFromUrlGlobal() { GlobalAddressId addressId = GlobalAddressId.of(PROJECT, NAME); - compareAddressId(addressId, GlobalAddressId.fromUrl(addressId.selfLink())); + compareAddressId(addressId, GlobalAddressId.fromUrl(addressId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid global address URL"); GlobalAddressId.fromUrl("notMatchingUrl"); @@ -76,7 +101,7 @@ public void testToAndFromUrlGlobal() { @Test public void testToAndFromUrlRegion() { RegionAddressId regionAddressId = RegionAddressId.of(PROJECT, REGION, NAME); - compareRegionAddressId(regionAddressId, RegionAddressId.fromUrl(regionAddressId.selfLink())); + compareRegionAddressId(regionAddressId, RegionAddressId.fromUrl(regionAddressId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid region address URL"); RegionAddressId.fromUrl("notMatchingUrl"); @@ -94,26 +119,26 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(GlobalAddressId.matchesUrl(GlobalAddressId.of(PROJECT, NAME).selfLink())); + assertTrue(GlobalAddressId.matchesUrl(GlobalAddressId.of(PROJECT, NAME).getSelfLink())); assertFalse(GlobalAddressId.matchesUrl("notMatchingUrl")); - assertTrue(RegionAddressId.matchesUrl(RegionAddressId.of(PROJECT, REGION, NAME).selfLink())); + assertTrue(RegionAddressId.matchesUrl(RegionAddressId.of(PROJECT, REGION, NAME).getSelfLink())); assertFalse(RegionAddressId.matchesUrl("notMatchingUrl")); } private void compareAddressId(GlobalAddressId expected, GlobalAddressId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.address(), expected.address()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getAddress(), expected.getAddress()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } private void compareRegionAddressId(RegionAddressId expected, RegionAddressId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.region(), expected.region()); - assertEquals(expected.address(), expected.address()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getRegion(), expected.getRegion()); + assertEquals(expected.getAddress(), expected.getAddress()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressInfoTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressInfoTest.java index 1e69608c8d40..47ac9917b6c4 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressInfoTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressInfoTest.java @@ -19,9 +19,10 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import com.google.cloud.compute.AddressInfo.GlobalForwardingUsage; +import com.google.cloud.compute.AddressInfo.RegionForwardingUsage; import com.google.common.collect.ImmutableList; -import org.junit.Assert; import org.junit.Test; import java.util.List; @@ -44,72 +45,112 @@ public class AddressInfoTest { RegionForwardingRuleId.of("project", "region", "forwardingRule2")); private static final AddressInfo.InstanceUsage INSTANCE_USAGE = new AddressInfo.InstanceUsage(InstanceId.of("project", "zone", "instance1")); - private static final AddressInfo.GlobalForwardingUsage GLOBAL_FORWARDING_USAGE = - new AddressInfo.GlobalForwardingUsage(GLOBAL_FORWARDING_RULES); - private static final AddressInfo.RegionForwardingUsage REGION_FORWARDING_USAGE = - new AddressInfo.RegionForwardingUsage(REGION_FORWARDING_RULES); - private static final AddressInfo INSTANCE_ADDRESS_INFO = AddressInfo.builder(REGION_ADDRESS_ID) - .address(ADDRESS) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .generatedId(GENERATED_ID) - .status(STATUS) - .usage(INSTANCE_USAGE) + private static final GlobalForwardingUsage GLOBAL_FORWARDING_USAGE = + new GlobalForwardingUsage(GLOBAL_FORWARDING_RULES); + private static final RegionForwardingUsage REGION_FORWARDING_USAGE = + new RegionForwardingUsage(REGION_FORWARDING_RULES); + private static final AddressInfo INSTANCE_ADDRESS_INFO = AddressInfo.newBuilder(REGION_ADDRESS_ID) + .setAddress(ADDRESS) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setGeneratedId(GENERATED_ID) + .setStatus(STATUS) + .setUsage(INSTANCE_USAGE) .build(); private static final AddressInfo GLOBAL_FORWARDING_ADDRESS_INFO = - AddressInfo.builder(GLOBAL_ADDRESS_ID) - .address(ADDRESS) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .generatedId(GENERATED_ID) - .status(STATUS) - .usage(GLOBAL_FORWARDING_USAGE) + AddressInfo.newBuilder(GLOBAL_ADDRESS_ID) + .setAddress(ADDRESS) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setGeneratedId(GENERATED_ID) + .setStatus(STATUS) + .setUsage(GLOBAL_FORWARDING_USAGE) .build(); private static final AddressInfo REGION_FORWARDING_ADDRESS_INFO = - AddressInfo.builder(REGION_ADDRESS_ID) + AddressInfo.newBuilder(REGION_ADDRESS_ID) + .setAddress(ADDRESS) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setGeneratedId(GENERATED_ID) + .setStatus(STATUS) + .setUsage(REGION_FORWARDING_USAGE) + .build(); + private static final AddressInfo DEPRECATED_ADDRESS_INFO = + AddressInfo.newBuilder(REGION_ADDRESS_ID) .address(ADDRESS) - .creationTimestamp(CREATION_TIMESTAMP) + .setCreationTimestamp(CREATION_TIMESTAMP) .description(DESCRIPTION) - .generatedId(GENERATED_ID) - .status(STATUS) - .usage(REGION_FORWARDING_USAGE) + .setGeneratedId(GENERATED_ID) + .setStatus(STATUS) + .setUsage(INSTANCE_USAGE) .build(); @Test public void testToBuilder() { compareAddressInfo(INSTANCE_ADDRESS_INFO, INSTANCE_ADDRESS_INFO.toBuilder().build()); AddressInfo addressInfo = INSTANCE_ADDRESS_INFO.toBuilder() - .address("192.168.1.2") - .description("description2") + .setAddress("192.168.1.2") + .setDescription("description2") .build(); - assertEquals("description2", addressInfo.description()); - assertEquals("192.168.1.2", addressInfo.address()); + assertEquals("description2", addressInfo.getDescription()); + assertEquals("192.168.1.2", addressInfo.getAddress()); addressInfo = addressInfo.toBuilder() - .address("192.168.1.1") - .description("description") + .setAddress("192.168.1.1") + .setDescription("description") .build(); compareAddressInfo(INSTANCE_ADDRESS_INFO, addressInfo); } @Test public void testToBuilderIncomplete() { - AddressInfo addressInfo = AddressInfo.builder(GLOBAL_ADDRESS_ID).build(); + AddressInfo addressInfo = AddressInfo.newBuilder(GLOBAL_ADDRESS_ID).build(); assertEquals(addressInfo, addressInfo.toBuilder().build()); - addressInfo = AddressInfo.builder(REGION_ADDRESS_ID).build(); + addressInfo = AddressInfo.newBuilder(REGION_ADDRESS_ID).build(); assertEquals(addressInfo, addressInfo.toBuilder().build()); } @Test public void testBuilder() { - assertEquals(ADDRESS, INSTANCE_ADDRESS_INFO.address()); - assertEquals(CREATION_TIMESTAMP, INSTANCE_ADDRESS_INFO.creationTimestamp()); - assertEquals(DESCRIPTION, INSTANCE_ADDRESS_INFO.description()); - assertEquals(GENERATED_ID, INSTANCE_ADDRESS_INFO.generatedId()); - assertEquals(REGION_ADDRESS_ID, INSTANCE_ADDRESS_INFO.addressId()); - assertEquals(STATUS, INSTANCE_ADDRESS_INFO.status()); - assertEquals(INSTANCE_USAGE, INSTANCE_ADDRESS_INFO.usage()); - Assert.assertEquals(INSTANCE_USAGE.instance(), - INSTANCE_ADDRESS_INFO.usage().instance()); + assertEquals(ADDRESS, INSTANCE_ADDRESS_INFO.getAddress()); + assertEquals(CREATION_TIMESTAMP, INSTANCE_ADDRESS_INFO.getCreationTimestamp()); + assertEquals(DESCRIPTION, INSTANCE_ADDRESS_INFO.getDescription()); + assertEquals(GENERATED_ID, INSTANCE_ADDRESS_INFO.getGeneratedId()); + assertEquals(REGION_ADDRESS_ID, INSTANCE_ADDRESS_INFO.getAddressId()); + assertEquals(STATUS, INSTANCE_ADDRESS_INFO.getStatus()); + assertEquals(INSTANCE_USAGE, INSTANCE_ADDRESS_INFO.getUsage()); + assertEquals(INSTANCE_USAGE.getInstance(), + INSTANCE_ADDRESS_INFO.getUsage().getInstance()); + assertEquals(ADDRESS, REGION_FORWARDING_ADDRESS_INFO.getAddress()); + assertEquals(CREATION_TIMESTAMP, REGION_FORWARDING_ADDRESS_INFO.getCreationTimestamp()); + assertEquals(DESCRIPTION, REGION_FORWARDING_ADDRESS_INFO.getDescription()); + assertEquals(GENERATED_ID, REGION_FORWARDING_ADDRESS_INFO.getGeneratedId()); + assertEquals(REGION_ADDRESS_ID, REGION_FORWARDING_ADDRESS_INFO.getAddressId()); + assertEquals(STATUS, REGION_FORWARDING_ADDRESS_INFO.getStatus()); + assertEquals(REGION_FORWARDING_USAGE, REGION_FORWARDING_ADDRESS_INFO.getUsage()); + assertEquals(REGION_FORWARDING_RULES, + REGION_FORWARDING_ADDRESS_INFO.getUsage().getForwardingRules()); + assertEquals(ADDRESS, GLOBAL_FORWARDING_ADDRESS_INFO.getAddress()); + assertEquals(CREATION_TIMESTAMP, GLOBAL_FORWARDING_ADDRESS_INFO.getCreationTimestamp()); + assertEquals(DESCRIPTION, GLOBAL_FORWARDING_ADDRESS_INFO.getDescription()); + assertEquals(GENERATED_ID, GLOBAL_FORWARDING_ADDRESS_INFO.getGeneratedId()); + assertEquals(GLOBAL_ADDRESS_ID, GLOBAL_FORWARDING_ADDRESS_INFO.getAddressId()); + assertEquals(STATUS, GLOBAL_FORWARDING_ADDRESS_INFO.getStatus()); + assertEquals(GLOBAL_FORWARDING_USAGE, GLOBAL_FORWARDING_ADDRESS_INFO.getUsage()); + assertEquals(GLOBAL_FORWARDING_RULES, + GLOBAL_FORWARDING_ADDRESS_INFO.getUsage().getForwardingRules()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(ADDRESS, DEPRECATED_ADDRESS_INFO.address()); + assertEquals(CREATION_TIMESTAMP, DEPRECATED_ADDRESS_INFO.creationTimestamp()); + assertEquals(DESCRIPTION, DEPRECATED_ADDRESS_INFO.description()); + assertEquals(GENERATED_ID, DEPRECATED_ADDRESS_INFO.generatedId()); + assertEquals(REGION_ADDRESS_ID, DEPRECATED_ADDRESS_INFO.addressId()); + assertEquals(STATUS, DEPRECATED_ADDRESS_INFO.status()); + assertEquals(INSTANCE_USAGE, DEPRECATED_ADDRESS_INFO.usage()); + assertEquals(INSTANCE_USAGE.instance(), + DEPRECATED_ADDRESS_INFO.usage().instance()); assertEquals(ADDRESS, REGION_FORWARDING_ADDRESS_INFO.address()); assertEquals(CREATION_TIMESTAMP, REGION_FORWARDING_ADDRESS_INFO.creationTimestamp()); assertEquals(DESCRIPTION, REGION_FORWARDING_ADDRESS_INFO.description()); @@ -117,8 +158,8 @@ public void testBuilder() { assertEquals(REGION_ADDRESS_ID, REGION_FORWARDING_ADDRESS_INFO.addressId()); assertEquals(STATUS, REGION_FORWARDING_ADDRESS_INFO.status()); assertEquals(REGION_FORWARDING_USAGE, REGION_FORWARDING_ADDRESS_INFO.usage()); - Assert.assertEquals(REGION_FORWARDING_RULES, - REGION_FORWARDING_ADDRESS_INFO.usage().forwardingRules()); + assertEquals(REGION_FORWARDING_RULES, + REGION_FORWARDING_ADDRESS_INFO.usage().forwardingRules()); assertEquals(ADDRESS, GLOBAL_FORWARDING_ADDRESS_INFO.address()); assertEquals(CREATION_TIMESTAMP, GLOBAL_FORWARDING_ADDRESS_INFO.creationTimestamp()); assertEquals(DESCRIPTION, GLOBAL_FORWARDING_ADDRESS_INFO.description()); @@ -126,44 +167,44 @@ public void testBuilder() { assertEquals(GLOBAL_ADDRESS_ID, GLOBAL_FORWARDING_ADDRESS_INFO.addressId()); assertEquals(STATUS, GLOBAL_FORWARDING_ADDRESS_INFO.status()); assertEquals(GLOBAL_FORWARDING_USAGE, GLOBAL_FORWARDING_ADDRESS_INFO.usage()); - Assert.assertEquals(GLOBAL_FORWARDING_RULES, - GLOBAL_FORWARDING_ADDRESS_INFO.usage().forwardingRules()); + assertEquals(GLOBAL_FORWARDING_RULES, + GLOBAL_FORWARDING_ADDRESS_INFO.usage().forwardingRules()); } @Test public void testOf() { AddressInfo addressInfo = AddressInfo.of("address"); - assertEquals(GlobalAddressId.of("address"), addressInfo.addressId()); - assertNull(addressInfo.address()); - assertNull(addressInfo.creationTimestamp()); - assertNull(addressInfo.description()); - assertNull(addressInfo.generatedId()); - assertNull(addressInfo.status()); - assertNull(addressInfo.usage()); + assertEquals(GlobalAddressId.of("address"), addressInfo.getAddressId()); + assertNull(addressInfo.getAddress()); + assertNull(addressInfo.getCreationTimestamp()); + assertNull(addressInfo.getDescription()); + assertNull(addressInfo.getGeneratedId()); + assertNull(addressInfo.getStatus()); + assertNull(addressInfo.getUsage()); addressInfo = AddressInfo.of(GLOBAL_ADDRESS_ID); - assertEquals(GLOBAL_ADDRESS_ID, addressInfo.addressId()); - assertNull(addressInfo.address()); - assertNull(addressInfo.creationTimestamp()); - assertNull(addressInfo.description()); - assertNull(addressInfo.generatedId()); - assertNull(addressInfo.status()); - assertNull(addressInfo.usage()); + assertEquals(GLOBAL_ADDRESS_ID, addressInfo.getAddressId()); + assertNull(addressInfo.getAddress()); + assertNull(addressInfo.getCreationTimestamp()); + assertNull(addressInfo.getDescription()); + assertNull(addressInfo.getGeneratedId()); + assertNull(addressInfo.getStatus()); + assertNull(addressInfo.getUsage()); addressInfo = AddressInfo.of("region", "address"); - assertEquals(RegionAddressId.of("region", "address"), addressInfo.addressId()); - assertNull(addressInfo.address()); - assertNull(addressInfo.creationTimestamp()); - assertNull(addressInfo.description()); - assertNull(addressInfo.generatedId()); - assertNull(addressInfo.status()); - assertNull(addressInfo.usage()); + assertEquals(RegionAddressId.of("region", "address"), addressInfo.getAddressId()); + assertNull(addressInfo.getAddress()); + assertNull(addressInfo.getCreationTimestamp()); + assertNull(addressInfo.getDescription()); + assertNull(addressInfo.getGeneratedId()); + assertNull(addressInfo.getStatus()); + assertNull(addressInfo.getUsage()); addressInfo = AddressInfo.of(RegionId.of("region"), "address"); - assertEquals(RegionAddressId.of("region", "address"), addressInfo.addressId()); - assertNull(addressInfo.address()); - assertNull(addressInfo.creationTimestamp()); - assertNull(addressInfo.description()); - assertNull(addressInfo.generatedId()); - assertNull(addressInfo.status()); - assertNull(addressInfo.usage()); + assertEquals(RegionAddressId.of("region", "address"), addressInfo.getAddressId()); + assertNull(addressInfo.getAddress()); + assertNull(addressInfo.getCreationTimestamp()); + assertNull(addressInfo.getDescription()); + assertNull(addressInfo.getGeneratedId()); + assertNull(addressInfo.getStatus()); + assertNull(addressInfo.getUsage()); } @Test @@ -173,27 +214,27 @@ public void testToPbAndFromPb() { AddressInfo.fromPb(REGION_FORWARDING_ADDRESS_INFO.toPb())); compareAddressInfo(GLOBAL_FORWARDING_ADDRESS_INFO, AddressInfo.fromPb(GLOBAL_FORWARDING_ADDRESS_INFO.toPb())); - AddressInfo addressInfo = AddressInfo.builder(GLOBAL_ADDRESS_ID).build(); + AddressInfo addressInfo = AddressInfo.newBuilder(GLOBAL_ADDRESS_ID).build(); compareAddressInfo(addressInfo, AddressInfo.fromPb(addressInfo.toPb())); } @Test public void testSetProjectId() { AddressInfo addressInfo = GLOBAL_FORWARDING_ADDRESS_INFO.toBuilder() - .addressId(GlobalAddressId.of(GLOBAL_ADDRESS_ID.address())) + .setAddressId(GlobalAddressId.of(GLOBAL_ADDRESS_ID.getAddress())) .build(); compareAddressInfo(GLOBAL_FORWARDING_ADDRESS_INFO, addressInfo.setProjectId("project")); } private void compareAddressInfo(AddressInfo expected, AddressInfo value) { assertEquals(expected, value); - assertEquals(expected.address(), value.address()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.addressId(), value.addressId()); - assertEquals(expected.usage(), value.usage()); - assertEquals(expected.status(), value.status()); + assertEquals(expected.getAddress(), value.getAddress()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getAddressId(), value.getAddressId()); + assertEquals(expected.getUsage(), value.getUsage()); + assertEquals(expected.getStatus(), value.getStatus()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressTest.java index 914d7e510b3a..aca5721c6306 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressTest.java @@ -69,40 +69,40 @@ private void initializeExpectedAddress(int optionsCalls) { expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); instanceAddress = new Address.Builder(serviceMockReturnsOptions, REGION_ADDRESS_ID) - .address(ADDRESS) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .generatedId(GENERATED_ID) - .status(STATUS) - .usage(INSTANCE_USAGE) + .setAddress(ADDRESS) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setGeneratedId(GENERATED_ID) + .setStatus(STATUS) + .setUsage(INSTANCE_USAGE) .build(); globalForwardingAddress = new Address.Builder(serviceMockReturnsOptions, GLOBAL_ADDRESS_ID) - .address(ADDRESS) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .generatedId(GENERATED_ID) - .status(STATUS) - .usage(GLOBAL_FORWARDING_USAGE) + .setAddress(ADDRESS) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setGeneratedId(GENERATED_ID) + .setStatus(STATUS) + .setUsage(GLOBAL_FORWARDING_USAGE) .build(); regionForwardingAddress = new Address.Builder(serviceMockReturnsOptions, REGION_ADDRESS_ID) - .address(ADDRESS) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .generatedId(GENERATED_ID) - .status(STATUS) - .usage(REGION_FORWARDING_USAGE) + .setAddress(ADDRESS) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setGeneratedId(GENERATED_ID) + .setStatus(STATUS) + .setUsage(REGION_FORWARDING_USAGE) .build(); compute = createStrictMock(Compute.class); } private void initializeAddress() { address = new Address.Builder(compute, REGION_ADDRESS_ID) - .address(ADDRESS) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .generatedId(GENERATED_ID) - .status(STATUS) - .usage(REGION_FORWARDING_USAGE) + .setAddress(ADDRESS) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setGeneratedId(GENERATED_ID) + .setStatus(STATUS) + .setUsage(REGION_FORWARDING_USAGE) .build(); } @@ -113,6 +113,64 @@ public void tearDown() throws Exception { @Test public void testBuilder() { + initializeExpectedAddress(6); + assertEquals(ADDRESS, instanceAddress.getAddress()); + assertEquals(CREATION_TIMESTAMP, instanceAddress.getCreationTimestamp()); + assertEquals(DESCRIPTION, instanceAddress.getDescription()); + assertEquals(GENERATED_ID, instanceAddress.getGeneratedId()); + assertEquals(REGION_ADDRESS_ID, instanceAddress.getAddressId()); + assertEquals(STATUS, instanceAddress.getStatus()); + assertEquals(INSTANCE_USAGE, instanceAddress.getUsage()); + assertSame(serviceMockReturnsOptions, instanceAddress.getCompute()); + assertEquals(ADDRESS, regionForwardingAddress.getAddress()); + assertEquals(CREATION_TIMESTAMP, regionForwardingAddress.getCreationTimestamp()); + assertEquals(DESCRIPTION, regionForwardingAddress.getDescription()); + assertEquals(GENERATED_ID, regionForwardingAddress.getGeneratedId()); + assertEquals(REGION_ADDRESS_ID, regionForwardingAddress.getAddressId()); + assertEquals(STATUS, regionForwardingAddress.getStatus()); + assertEquals(REGION_FORWARDING_USAGE, regionForwardingAddress.getUsage()); + assertSame(serviceMockReturnsOptions, regionForwardingAddress.getCompute()); + assertEquals(ADDRESS, globalForwardingAddress.getAddress()); + assertEquals(CREATION_TIMESTAMP, globalForwardingAddress.getCreationTimestamp()); + assertEquals(DESCRIPTION, globalForwardingAddress.getDescription()); + assertEquals(GENERATED_ID, globalForwardingAddress.getGeneratedId()); + assertEquals(GLOBAL_ADDRESS_ID, globalForwardingAddress.getAddressId()); + assertEquals(STATUS, globalForwardingAddress.getStatus()); + assertEquals(GLOBAL_FORWARDING_USAGE, globalForwardingAddress.getUsage()); + assertSame(serviceMockReturnsOptions, globalForwardingAddress.getCompute()); + Address address = new Address.Builder(serviceMockReturnsOptions, GLOBAL_ADDRESS_ID).build(); + assertEquals(GLOBAL_ADDRESS_ID, address.getAddressId()); + assertSame(serviceMockReturnsOptions, address.getCompute()); + assertNull(address.getAddress()); + assertNull(address.getCreationTimestamp()); + assertNull(address.getDescription()); + assertNull(address.getGeneratedId()); + assertNull(address.getStatus()); + assertNull(address.getUsage()); + address = new Address.Builder(serviceMockReturnsOptions, REGION_ADDRESS_ID).build(); + assertEquals(REGION_ADDRESS_ID, address.getAddressId()); + assertSame(serviceMockReturnsOptions, address.getCompute()); + assertNull(address.getAddress()); + assertNull(address.getCreationTimestamp()); + assertNull(address.getDescription()); + assertNull(address.getGeneratedId()); + assertNull(address.getStatus()); + assertNull(address.getUsage()); + address = new Address.Builder(serviceMockReturnsOptions, REGION_ADDRESS_ID) + .setAddressId(GLOBAL_ADDRESS_ID) + .build(); + assertEquals(GLOBAL_ADDRESS_ID, address.getAddressId()); + assertSame(serviceMockReturnsOptions, address.getCompute()); + assertNull(address.getAddress()); + assertNull(address.getCreationTimestamp()); + assertNull(address.getDescription()); + assertNull(address.getGeneratedId()); + assertNull(address.getStatus()); + assertNull(address.getUsage()); + } + + @Test + public void testBuilderDeprecated() { initializeExpectedAddress(6); assertEquals(ADDRESS, instanceAddress.address()); assertEquals(CREATION_TIMESTAMP, instanceAddress.creationTimestamp()); @@ -175,9 +233,9 @@ public void testToBuilder() { compareAddress(instanceAddress, instanceAddress.toBuilder().build()); compareAddress(globalForwardingAddress, globalForwardingAddress.toBuilder().build()); compareAddress(regionForwardingAddress, regionForwardingAddress.toBuilder().build()); - Address newAddress = instanceAddress.toBuilder().description("newDescription").build(); - assertEquals("newDescription", newAddress.description()); - newAddress = newAddress.toBuilder().description("description").build(); + Address newAddress = instanceAddress.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", newAddress.getDescription()); + newAddress = newAddress.toBuilder().setDescription("description").build(); compareAddress(instanceAddress, newAddress); } @@ -201,7 +259,7 @@ public void testDeleteOperation() { initializeExpectedAddress(4); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(GlobalOperationId.of("project", "op")) + .setOperationId(GlobalOperationId.of("project", "op")) .build(); expect(compute.deleteAddress(REGION_ADDRESS_ID)).andReturn(operation); replay(compute); @@ -281,14 +339,14 @@ public void testReloadWithOptions() throws Exception { private void compareAddress(Address expected, Address value) { assertEquals(expected, value); - assertEquals(expected.compute().options(), value.compute().options()); - assertEquals(expected.address(), value.address()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.addressId(), value.addressId()); - assertEquals(expected.usage(), value.usage()); - assertEquals(expected.status(), value.status()); + assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getAddress(), value.getAddress()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getAddressId(), value.getAddressId()); + assertEquals(expected.getUsage(), value.getUsage()); + assertEquals(expected.getStatus(), value.getStatus()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/AttachedDiskTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/AttachedDiskTest.java index 6e68e18590c2..9d318d6fc178 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/AttachedDiskTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/AttachedDiskTest.java @@ -47,14 +47,50 @@ public class AttachedDiskTest { private static final PersistentDiskConfiguration.Mode MODE = PersistentDiskConfiguration.Mode.READ_ONLY; private static final PersistentDiskConfiguration PERSISTENT_DISK_CONFIGURATION = + PersistentDiskConfiguration.newBuilder(DISK_ID) + .setBoot(BOOT) + .setAutoDelete(AUTO_DELETE) + .setMode(MODE) + .build(); + private static final ScratchDiskConfiguration SCRATCH_DISK_CONFIGURATION = + ScratchDiskConfiguration.newBuilder(DISK_TYPE_ID).setInterfaceType(INTERFACE_TYPE).build(); + private static final CreateDiskConfiguration CREATE_DISK_CONFIGURATION = + CreateDiskConfiguration.newBuilder(IMAGE_ID) + .setAutoDelete(AUTO_DELETE) + .setDiskName(DISK_NAME) + .setDiskType(DISK_TYPE_ID) + .setDiskSizeGb(DISK_SIZE_GB) + .setSourceImage(IMAGE_ID) + .build(); + private static final List LICENSES = ImmutableList.of( + LicenseId.of("project", "license1"), LicenseId.of("project", "license2")); + private static final AttachedDisk PERSISTENT_DISK = + AttachedDisk.newBuilder(PERSISTENT_DISK_CONFIGURATION) + .setDeviceName(DEVICE_NAME) + .setIndex(INDEX) + .setLicenses(LICENSES) + .build(); + private static final AttachedDisk SCRATCH_DISK = + AttachedDisk.newBuilder(SCRATCH_DISK_CONFIGURATION) + .setDeviceName(DEVICE_NAME) + .setIndex(INDEX) + .setLicenses(LICENSES) + .build(); + private static final AttachedDisk CREATED_DISK = + AttachedDisk.newBuilder(CREATE_DISK_CONFIGURATION) + .setDeviceName(DEVICE_NAME) + .setIndex(INDEX) + .setLicenses(LICENSES) + .build(); + private static final PersistentDiskConfiguration DEPRECATED_PERSISTENT_DISK_CONFIGURATION = PersistentDiskConfiguration.builder(DISK_ID) .boot(BOOT) .autoDelete(AUTO_DELETE) .mode(MODE) .build(); - private static final ScratchDiskConfiguration SCRATCH_DISK_CONFIGURATION = + private static final ScratchDiskConfiguration DEPRECATED_SCRATCH_DISK_CONFIGURATION = ScratchDiskConfiguration.builder(DISK_TYPE_ID).interfaceType(INTERFACE_TYPE).build(); - private static final CreateDiskConfiguration CREATE_DISK_CONFIGURATION = + private static final CreateDiskConfiguration DEPRECATED_CREATE_DISK_CONFIGURATION = CreateDiskConfiguration.builder(IMAGE_ID) .autoDelete(AUTO_DELETE) .diskName(DISK_NAME) @@ -62,25 +98,23 @@ public class AttachedDiskTest { .diskSizeGb(DISK_SIZE_GB) .sourceImage(IMAGE_ID) .build(); - private static final List LICENSES = ImmutableList.of( - LicenseId.of("project", "license1"), LicenseId.of("project", "license2")); - private static final AttachedDisk PERSISTENT_DISK = + private static final AttachedDisk DEPRECATED_PERSISTENT_DISK = AttachedDisk.builder(PERSISTENT_DISK_CONFIGURATION) .deviceName(DEVICE_NAME) .index(INDEX) - .licenses(LICENSES) + .setLicenses(LICENSES) .build(); - private static final AttachedDisk SCRATCH_DISK = + private static final AttachedDisk DEPRECATED_SCRATCH_DISK = AttachedDisk.builder(SCRATCH_DISK_CONFIGURATION) .deviceName(DEVICE_NAME) .index(INDEX) - .licenses(LICENSES) + .setLicenses(LICENSES) .build(); - private static final AttachedDisk CREATED_DISK = + private static final AttachedDisk DEPRECATED_CREATED_DISK = AttachedDisk.builder(CREATE_DISK_CONFIGURATION) .deviceName(DEVICE_NAME) .index(INDEX) - .licenses(LICENSES) + .setLicenses(LICENSES) .build(); @Test @@ -92,21 +126,22 @@ public void testConfigurationToBuilder() { compareCreateDiskConfiguration(CREATE_DISK_CONFIGURATION, CREATE_DISK_CONFIGURATION.toBuilder().build()); PersistentDiskConfiguration persistentDiskConfiguration = - PERSISTENT_DISK_CONFIGURATION.toBuilder().autoDelete(false).build(); + PERSISTENT_DISK_CONFIGURATION.toBuilder().setAutoDelete(false).build(); assertFalse(persistentDiskConfiguration.autoDelete()); persistentDiskConfiguration = - persistentDiskConfiguration.toBuilder().autoDelete(AUTO_DELETE).build(); + persistentDiskConfiguration.toBuilder().setAutoDelete(AUTO_DELETE).build(); assertEquals(PERSISTENT_DISK_CONFIGURATION, persistentDiskConfiguration); ScratchDiskConfiguration scratchDiskConfiguration = - SCRATCH_DISK_CONFIGURATION.toBuilder().interfaceType(InterfaceType.SCSI).build(); - assertEquals(InterfaceType.SCSI, scratchDiskConfiguration.interfaceType()); + SCRATCH_DISK_CONFIGURATION.toBuilder().setInterfaceType(InterfaceType.SCSI).build(); + assertEquals(InterfaceType.SCSI, scratchDiskConfiguration.getInterfaceType()); scratchDiskConfiguration = - scratchDiskConfiguration.toBuilder().interfaceType(INTERFACE_TYPE).build(); + scratchDiskConfiguration.toBuilder().setInterfaceType(INTERFACE_TYPE).build(); assertEquals(SCRATCH_DISK_CONFIGURATION, scratchDiskConfiguration); CreateDiskConfiguration createDiskConfiguration = - CREATE_DISK_CONFIGURATION.toBuilder().autoDelete(false).build(); + CREATE_DISK_CONFIGURATION.toBuilder().setAutoDelete(false).build(); assertFalse(createDiskConfiguration.autoDelete()); - createDiskConfiguration = createDiskConfiguration.toBuilder().autoDelete(AUTO_DELETE).build(); + createDiskConfiguration = + createDiskConfiguration.toBuilder().setAutoDelete(AUTO_DELETE).build(); assertEquals(CREATE_DISK_CONFIGURATION, createDiskConfiguration); } @@ -131,9 +166,9 @@ public void testToBuilder() { compareAttachedDisk(PERSISTENT_DISK, PERSISTENT_DISK.toBuilder().build()); compareAttachedDisk(SCRATCH_DISK, SCRATCH_DISK.toBuilder().build()); compareAttachedDisk(CREATED_DISK, CREATED_DISK.toBuilder().build()); - AttachedDisk attachedDisk = PERSISTENT_DISK.toBuilder().deviceName("newDeviceName").build(); - assertEquals("newDeviceName", attachedDisk.deviceName()); - attachedDisk = attachedDisk.toBuilder().deviceName(DEVICE_NAME).build(); + AttachedDisk attachedDisk = PERSISTENT_DISK.toBuilder().setDeviceName("newDeviceName").build(); + assertEquals("newDeviceName", attachedDisk.getDeviceName()); + attachedDisk = attachedDisk.toBuilder().setDeviceName(DEVICE_NAME).build(); compareAttachedDisk(PERSISTENT_DISK, attachedDisk); } @@ -151,103 +186,145 @@ public void testToBuilderIncomplete() { public void testConfigurationBuilder() { assertTrue(CREATE_DISK_CONFIGURATION.boot()); assertEquals(AUTO_DELETE, CREATE_DISK_CONFIGURATION.autoDelete()); - assertNull(CREATE_DISK_CONFIGURATION.interfaceType()); - assertEquals(Type.PERSISTENT, CREATE_DISK_CONFIGURATION.type()); - assertEquals(IMAGE_ID, CREATE_DISK_CONFIGURATION.sourceImage()); - assertEquals(DISK_NAME, CREATE_DISK_CONFIGURATION.diskName()); - assertEquals(DISK_TYPE_ID, CREATE_DISK_CONFIGURATION.diskType()); - assertEquals(DISK_SIZE_GB, CREATE_DISK_CONFIGURATION.diskSizeGb()); - assertEquals(IMAGE_ID, CREATE_DISK_CONFIGURATION.sourceImage()); + assertNull(CREATE_DISK_CONFIGURATION.getInterfaceType()); + assertEquals(Type.PERSISTENT, CREATE_DISK_CONFIGURATION.getType()); + assertEquals(IMAGE_ID, CREATE_DISK_CONFIGURATION.getSourceImage()); + assertEquals(DISK_NAME, CREATE_DISK_CONFIGURATION.getDiskName()); + assertEquals(DISK_TYPE_ID, CREATE_DISK_CONFIGURATION.getDiskType()); + assertEquals(DISK_SIZE_GB, CREATE_DISK_CONFIGURATION.getDiskSizeGb()); + assertEquals(IMAGE_ID, CREATE_DISK_CONFIGURATION.getSourceImage()); assertEquals(BOOT, PERSISTENT_DISK_CONFIGURATION.boot()); assertEquals(AUTO_DELETE, PERSISTENT_DISK_CONFIGURATION.autoDelete()); - assertNull(PERSISTENT_DISK_CONFIGURATION.interfaceType()); - assertEquals(Type.PERSISTENT, PERSISTENT_DISK_CONFIGURATION.type()); - assertEquals(MODE, PERSISTENT_DISK_CONFIGURATION.mode()); - assertEquals(DISK_ID, PERSISTENT_DISK_CONFIGURATION.sourceDisk()); + assertNull(PERSISTENT_DISK_CONFIGURATION.getInterfaceType()); + assertEquals(Type.PERSISTENT, PERSISTENT_DISK_CONFIGURATION.getType()); + assertEquals(MODE, PERSISTENT_DISK_CONFIGURATION.getMode()); + assertEquals(DISK_ID, PERSISTENT_DISK_CONFIGURATION.getSourceDisk()); assertFalse(SCRATCH_DISK_CONFIGURATION.boot()); assertTrue(SCRATCH_DISK_CONFIGURATION.autoDelete()); - assertEquals(INTERFACE_TYPE, SCRATCH_DISK_CONFIGURATION.interfaceType()); - assertEquals(Type.SCRATCH, SCRATCH_DISK_CONFIGURATION.type()); - assertEquals(DISK_TYPE_ID, SCRATCH_DISK_CONFIGURATION.diskType()); + assertEquals(INTERFACE_TYPE, SCRATCH_DISK_CONFIGURATION.getInterfaceType()); + assertEquals(Type.SCRATCH, SCRATCH_DISK_CONFIGURATION.getType()); + assertEquals(DISK_TYPE_ID, SCRATCH_DISK_CONFIGURATION.getDiskType()); + } + + @Test + public void testConfigurationBuilderDeprecated() { + assertTrue(DEPRECATED_CREATE_DISK_CONFIGURATION.boot()); + assertEquals(AUTO_DELETE, DEPRECATED_CREATE_DISK_CONFIGURATION.autoDelete()); + assertNull(DEPRECATED_CREATE_DISK_CONFIGURATION.interfaceType()); + assertEquals(Type.PERSISTENT, DEPRECATED_CREATE_DISK_CONFIGURATION.type()); + assertEquals(IMAGE_ID, DEPRECATED_CREATE_DISK_CONFIGURATION.sourceImage()); + assertEquals(DISK_NAME, DEPRECATED_CREATE_DISK_CONFIGURATION.diskName()); + assertEquals(DISK_TYPE_ID, DEPRECATED_CREATE_DISK_CONFIGURATION.diskType()); + assertEquals(DISK_SIZE_GB, DEPRECATED_CREATE_DISK_CONFIGURATION.diskSizeGb()); + assertEquals(IMAGE_ID, DEPRECATED_CREATE_DISK_CONFIGURATION.sourceImage()); + + assertEquals(BOOT, DEPRECATED_PERSISTENT_DISK_CONFIGURATION.boot()); + assertEquals(AUTO_DELETE, DEPRECATED_PERSISTENT_DISK_CONFIGURATION.autoDelete()); + assertNull(DEPRECATED_PERSISTENT_DISK_CONFIGURATION.interfaceType()); + assertEquals(Type.PERSISTENT, DEPRECATED_PERSISTENT_DISK_CONFIGURATION.type()); + assertEquals(MODE, DEPRECATED_PERSISTENT_DISK_CONFIGURATION.mode()); + assertEquals(DISK_ID, DEPRECATED_PERSISTENT_DISK_CONFIGURATION.sourceDisk()); + + assertFalse(DEPRECATED_SCRATCH_DISK_CONFIGURATION.boot()); + assertTrue(DEPRECATED_SCRATCH_DISK_CONFIGURATION.autoDelete()); + assertEquals(INTERFACE_TYPE, DEPRECATED_SCRATCH_DISK_CONFIGURATION.interfaceType()); + assertEquals(Type.SCRATCH, DEPRECATED_SCRATCH_DISK_CONFIGURATION.type()); + assertEquals(DISK_TYPE_ID, DEPRECATED_SCRATCH_DISK_CONFIGURATION.diskType()); } @Test public void testBuilder() { - assertEquals(PERSISTENT_DISK_CONFIGURATION, PERSISTENT_DISK.configuration()); - assertEquals(DEVICE_NAME, PERSISTENT_DISK.deviceName()); - assertEquals(INDEX, PERSISTENT_DISK.index()); - assertEquals(LICENSES, PERSISTENT_DISK.licenses()); - assertEquals(SCRATCH_DISK_CONFIGURATION, SCRATCH_DISK.configuration()); - assertEquals(DEVICE_NAME, SCRATCH_DISK.deviceName()); - assertEquals(INDEX, SCRATCH_DISK.index()); - assertEquals(LICENSES, SCRATCH_DISK.licenses()); - assertEquals(CREATE_DISK_CONFIGURATION, CREATED_DISK.configuration()); - assertEquals(DEVICE_NAME, CREATED_DISK.deviceName()); - assertEquals(INDEX, CREATED_DISK.index()); - assertEquals(LICENSES, CREATED_DISK.licenses()); + assertEquals(PERSISTENT_DISK_CONFIGURATION, PERSISTENT_DISK.getConfiguration()); + assertEquals(DEVICE_NAME, PERSISTENT_DISK.getDeviceName()); + assertEquals(INDEX, PERSISTENT_DISK.getIndex()); + assertEquals(LICENSES, PERSISTENT_DISK.getLicenses()); + assertEquals(SCRATCH_DISK_CONFIGURATION, SCRATCH_DISK.getConfiguration()); + assertEquals(DEVICE_NAME, SCRATCH_DISK.getDeviceName()); + assertEquals(INDEX, SCRATCH_DISK.getIndex()); + assertEquals(LICENSES, SCRATCH_DISK.getLicenses()); + assertEquals(CREATE_DISK_CONFIGURATION, CREATED_DISK.getConfiguration()); + assertEquals(DEVICE_NAME, CREATED_DISK.getDeviceName()); + assertEquals(INDEX, CREATED_DISK.getIndex()); + assertEquals(LICENSES, CREATED_DISK.getLicenses()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(PERSISTENT_DISK_CONFIGURATION, DEPRECATED_PERSISTENT_DISK.configuration()); + assertEquals(DEVICE_NAME, DEPRECATED_PERSISTENT_DISK.deviceName()); + assertEquals(INDEX, DEPRECATED_PERSISTENT_DISK.index()); + assertEquals(LICENSES, DEPRECATED_PERSISTENT_DISK.licenses()); + assertEquals(SCRATCH_DISK_CONFIGURATION, DEPRECATED_SCRATCH_DISK.configuration()); + assertEquals(DEVICE_NAME, DEPRECATED_SCRATCH_DISK.deviceName()); + assertEquals(INDEX, DEPRECATED_SCRATCH_DISK.index()); + assertEquals(LICENSES, DEPRECATED_SCRATCH_DISK.licenses()); + assertEquals(CREATE_DISK_CONFIGURATION, DEPRECATED_CREATED_DISK.configuration()); + assertEquals(DEVICE_NAME, DEPRECATED_CREATED_DISK.deviceName()); + assertEquals(INDEX, DEPRECATED_CREATED_DISK.index()); + assertEquals(LICENSES, DEPRECATED_CREATED_DISK.licenses()); } @Test public void testConfigurationOf() { PersistentDiskConfiguration persistentConfiguration = PersistentDiskConfiguration.of(DISK_ID); - assertEquals(DISK_ID, persistentConfiguration.sourceDisk()); - assertEquals(Type.PERSISTENT, persistentConfiguration.type()); + assertEquals(DISK_ID, persistentConfiguration.getSourceDisk()); + assertEquals(Type.PERSISTENT, persistentConfiguration.getType()); assertNull(persistentConfiguration.autoDelete()); assertNull(persistentConfiguration.boot()); - assertNull(persistentConfiguration.interfaceType()); + assertNull(persistentConfiguration.getInterfaceType()); ScratchDiskConfiguration scratchDiskConfiguration = ScratchDiskConfiguration.of(DISK_TYPE_ID); - assertEquals(DISK_TYPE_ID, scratchDiskConfiguration.diskType()); - assertNull(scratchDiskConfiguration.interfaceType()); - assertEquals(Type.SCRATCH, scratchDiskConfiguration.type()); + assertEquals(DISK_TYPE_ID, scratchDiskConfiguration.getDiskType()); + assertNull(scratchDiskConfiguration.getInterfaceType()); + assertEquals(Type.SCRATCH, scratchDiskConfiguration.getType()); assertTrue(scratchDiskConfiguration.autoDelete()); assertFalse(scratchDiskConfiguration.boot()); - assertNull(scratchDiskConfiguration.interfaceType()); + assertNull(scratchDiskConfiguration.getInterfaceType()); CreateDiskConfiguration createDiskConfiguration = CreateDiskConfiguration.of(IMAGE_ID); - assertEquals(IMAGE_ID, createDiskConfiguration.sourceImage()); - assertNull(createDiskConfiguration.diskType()); - assertNull(createDiskConfiguration.diskName()); - assertNull(createDiskConfiguration.diskSizeGb()); - assertNull(createDiskConfiguration.interfaceType()); - assertEquals(Type.PERSISTENT, createDiskConfiguration.type()); + assertEquals(IMAGE_ID, createDiskConfiguration.getSourceImage()); + assertNull(createDiskConfiguration.getDiskType()); + assertNull(createDiskConfiguration.getDiskName()); + assertNull(createDiskConfiguration.getDiskSizeGb()); + assertNull(createDiskConfiguration.getInterfaceType()); + assertEquals(Type.PERSISTENT, createDiskConfiguration.getType()); assertNull(createDiskConfiguration.autoDelete()); assertTrue(createDiskConfiguration.boot()); - assertNull(createDiskConfiguration.interfaceType()); + assertNull(createDiskConfiguration.getInterfaceType()); } @Test public void testOf() { AttachedDisk attachedDisk = AttachedDisk.of(DEVICE_NAME, PERSISTENT_DISK_CONFIGURATION); - assertEquals(PERSISTENT_DISK_CONFIGURATION, attachedDisk.configuration()); - assertEquals(DEVICE_NAME, attachedDisk.deviceName()); - assertNull(attachedDisk.index()); - assertNull(attachedDisk.licenses()); + assertEquals(PERSISTENT_DISK_CONFIGURATION, attachedDisk.getConfiguration()); + assertEquals(DEVICE_NAME, attachedDisk.getDeviceName()); + assertNull(attachedDisk.getIndex()); + assertNull(attachedDisk.getLicenses()); attachedDisk = AttachedDisk.of(PERSISTENT_DISK_CONFIGURATION); - assertEquals(PERSISTENT_DISK_CONFIGURATION, attachedDisk.configuration()); - assertNull(attachedDisk.deviceName()); - assertNull(attachedDisk.index()); - assertNull(attachedDisk.licenses()); + assertEquals(PERSISTENT_DISK_CONFIGURATION, attachedDisk.getConfiguration()); + assertNull(attachedDisk.getDeviceName()); + assertNull(attachedDisk.getIndex()); + assertNull(attachedDisk.getLicenses()); attachedDisk = AttachedDisk.of(DEVICE_NAME, SCRATCH_DISK_CONFIGURATION); - assertEquals(SCRATCH_DISK_CONFIGURATION, attachedDisk.configuration()); - assertEquals(DEVICE_NAME, attachedDisk.deviceName()); - assertNull(attachedDisk.index()); - assertNull(attachedDisk.licenses()); + assertEquals(SCRATCH_DISK_CONFIGURATION, attachedDisk.getConfiguration()); + assertEquals(DEVICE_NAME, attachedDisk.getDeviceName()); + assertNull(attachedDisk.getIndex()); + assertNull(attachedDisk.getLicenses()); attachedDisk = AttachedDisk.of(SCRATCH_DISK_CONFIGURATION); - assertEquals(SCRATCH_DISK_CONFIGURATION, attachedDisk.configuration()); - assertNull(attachedDisk.deviceName()); - assertNull(attachedDisk.index()); - assertNull(attachedDisk.licenses()); + assertEquals(SCRATCH_DISK_CONFIGURATION, attachedDisk.getConfiguration()); + assertNull(attachedDisk.getDeviceName()); + assertNull(attachedDisk.getIndex()); + assertNull(attachedDisk.getLicenses()); attachedDisk = AttachedDisk.of(DEVICE_NAME, CREATE_DISK_CONFIGURATION); - assertEquals(CREATE_DISK_CONFIGURATION, attachedDisk.configuration()); - assertEquals(DEVICE_NAME, attachedDisk.deviceName()); - assertNull(attachedDisk.index()); - assertNull(attachedDisk.licenses()); + assertEquals(CREATE_DISK_CONFIGURATION, attachedDisk.getConfiguration()); + assertEquals(DEVICE_NAME, attachedDisk.getDeviceName()); + assertNull(attachedDisk.getIndex()); + assertNull(attachedDisk.getLicenses()); attachedDisk = AttachedDisk.of(CREATE_DISK_CONFIGURATION); - assertEquals(CREATE_DISK_CONFIGURATION, attachedDisk.configuration()); - assertNull(attachedDisk.deviceName()); - assertNull(attachedDisk.index()); - assertNull(attachedDisk.licenses()); + assertEquals(CREATE_DISK_CONFIGURATION, attachedDisk.getConfiguration()); + assertNull(attachedDisk.getDeviceName()); + assertNull(attachedDisk.getIndex()); + assertNull(attachedDisk.getLicenses()); } @Test @@ -313,8 +390,8 @@ public void testConfigurationSetProjectId() { ScratchDiskConfiguration.of(DiskTypeId.of("project", "zone", "diskType")), scratchDiskConfiguration.setProjectId("project")); CreateDiskConfiguration createDiskConfiguration = CREATE_DISK_CONFIGURATION.toBuilder() - .diskType(DiskTypeId.of("zone", "diskType")) - .sourceImage(ImageId.of("image")) + .setDiskType(DiskTypeId.of("zone", "diskType")) + .setSourceImage(ImageId.of("image")) .build(); compareCreateDiskConfiguration(CREATE_DISK_CONFIGURATION, createDiskConfiguration.setProjectId("project")); @@ -342,8 +419,8 @@ public void testSetProjectId() { compareAttachedDisk(AttachedDisk.of(createDiskConfigurationWithProject), AttachedDisk.of(createDiskConfiguration).setProjectId("project")); createDiskConfiguration = CREATE_DISK_CONFIGURATION.toBuilder() - .diskType(DiskTypeId.of("zone", "diskType")) - .sourceImage(ImageId.of("image")) + .setDiskType(DiskTypeId.of("zone", "diskType")) + .setSourceImage(ImageId.of("image")) .build(); compareAttachedDisk(AttachedDisk.of(CREATE_DISK_CONFIGURATION), AttachedDisk.of(createDiskConfiguration).setProjectId("project")); @@ -352,8 +429,8 @@ public void testSetProjectId() { public void compareAttachedDiskConfiguration(AttachedDisk.AttachedDiskConfiguration expected, AttachedDisk.AttachedDiskConfiguration value) { assertEquals(expected, value); - assertEquals(expected.type(), value.type()); - assertEquals(expected.interfaceType(), value.interfaceType()); + assertEquals(expected.getType(), value.getType()); + assertEquals(expected.getInterfaceType(), value.getInterfaceType()); assertEquals(expected.boot(), value.boot()); assertEquals(expected.autoDelete(), value.autoDelete()); assertEquals(expected.hashCode(), value.hashCode()); @@ -362,31 +439,31 @@ public void compareAttachedDiskConfiguration(AttachedDisk.AttachedDiskConfigurat public void comparePersistentDiskConfiguration(PersistentDiskConfiguration expected, PersistentDiskConfiguration value) { compareAttachedDiskConfiguration(expected, value); - assertEquals(expected.mode(), value.mode()); - assertEquals(expected.sourceDisk(), value.sourceDisk()); + assertEquals(expected.getMode(), value.getMode()); + assertEquals(expected.getSourceDisk(), value.getSourceDisk()); } public void compareCreateDiskConfiguration(CreateDiskConfiguration expected, CreateDiskConfiguration value) { compareAttachedDiskConfiguration(expected, value); - assertEquals(expected.diskName(), value.diskName()); - assertEquals(expected.diskType(), value.diskType()); - assertEquals(expected.diskSizeGb(), value.diskSizeGb()); - assertEquals(expected.sourceImage(), value.sourceImage()); + assertEquals(expected.getDiskName(), value.getDiskName()); + assertEquals(expected.getDiskType(), value.getDiskType()); + assertEquals(expected.getDiskSizeGb(), value.getDiskSizeGb()); + assertEquals(expected.getSourceImage(), value.getSourceImage()); } public void compareScratchDiskConfiguration(ScratchDiskConfiguration expected, ScratchDiskConfiguration value) { compareAttachedDiskConfiguration(expected, value); - assertEquals(expected.diskType(), value.diskType()); + assertEquals(expected.getDiskType(), value.getDiskType()); } public void compareAttachedDisk(AttachedDisk expected, AttachedDisk value) { assertEquals(expected, value); - assertEquals(expected.deviceName(), value.deviceName()); - assertEquals(expected.index(), value.index()); - assertEquals(expected.configuration(), value.configuration()); - assertEquals(expected.licenses(), value.licenses()); + assertEquals(expected.getDeviceName(), value.getDeviceName()); + assertEquals(expected.getIndex(), value.getIndex()); + assertEquals(expected.getConfiguration(), value.getConfiguration()); + assertEquals(expected.getLicenses(), value.getLicenses()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/ComputeImplTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/ComputeImplTest.java index 6d1226df1a08..b8c4205586ff 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/ComputeImplTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/ComputeImplTest.java @@ -55,13 +55,13 @@ public class ComputeImplTest { private static final String VALID_DISK_SIZE = "10GB-10TB"; private static final Long DEFAULT_DISK_SIZE_GB = 10L; private static final DiskTypeId DISK_TYPE_ID = DiskTypeId.of("project", "zone", "diskType"); - private static final DiskType DISK_TYPE = DiskType.builder() - .generatedId(GENERATED_ID) - .diskTypeId(DISK_TYPE_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .validDiskSize(VALID_DISK_SIZE) - .defaultDiskSizeGb(DEFAULT_DISK_SIZE_GB) + private static final DiskType DISK_TYPE = DiskType.newBuilder() + .setGeneratedId(GENERATED_ID) + .setDiskTypeId(DISK_TYPE_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setValidDiskSize(VALID_DISK_SIZE) + .setDefaultDiskSizeGb(DEFAULT_DISK_SIZE_GB) .build(); private static final MachineTypeId MACHINE_TYPE_ID = MachineTypeId.of("project", "zone", "type"); private static final Integer GUEST_CPUS = 1; @@ -69,16 +69,16 @@ public class ComputeImplTest { private static final List SCRATCH_DISKS = ImmutableList.of(3); private static final Integer MAXIMUM_PERSISTENT_DISKS = 4; private static final Long MAXIMUM_PERSISTENT_DISKS_SIZE_GB = 5L; - private static final MachineType MACHINE_TYPE = MachineType.builder() - .generatedId(GENERATED_ID) - .machineTypeId(MACHINE_TYPE_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .cpus(GUEST_CPUS) - .memoryMb(MEMORY_MB) - .scratchDisksSizeGb(SCRATCH_DISKS) - .maximumPersistentDisks(MAXIMUM_PERSISTENT_DISKS) - .maximumPersistentDisksSizeGb(MAXIMUM_PERSISTENT_DISKS_SIZE_GB) + private static final MachineType MACHINE_TYPE = MachineType.newBuilder() + .setGeneratedId(GENERATED_ID) + .setMachineTypeId(MACHINE_TYPE_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setCpus(GUEST_CPUS) + .setMemoryMb(MEMORY_MB) + .setScratchDisksSizeGb(SCRATCH_DISKS) + .setMaximumPersistentDisks(MAXIMUM_PERSISTENT_DISKS) + .setMaximumPersistentDisksSizeGb(MAXIMUM_PERSISTENT_DISKS_SIZE_GB) .build(); private static final RegionId REGION_ID = RegionId.of("project", "region"); private static final Region.Status REGION_STATUS = Region.Status.DOWN; @@ -91,23 +91,23 @@ public class ComputeImplTest { new Region.Quota("METRIC2", 4, 3); private static final List QUOTAS = ImmutableList.of(QUOTA1, QUOTA2); private static final Region REGION = Region.builder() - .regionId(REGION_ID) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(REGION_STATUS) - .zones(ZONES) - .quotas(QUOTAS) + .setRegionId(REGION_ID) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(REGION_STATUS) + .setZones(ZONES) + .setQuotas(QUOTAS) .build(); private static final ZoneId ZONE_ID = ZoneId.of("project", "zone"); private static final Zone.Status ZONE_STATUS = Zone.Status.DOWN; private static final Zone ZONE = Zone.builder() - .zoneId(ZONE_ID) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(ZONE_STATUS) - .region(REGION_ID) + .setZoneId(ZONE_ID) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(ZONE_STATUS) + .setRegion(REGION_ID) .build(); private static final LicenseId LICENSE_ID = LicenseId.of("project", "license"); private static final Boolean CHARGES_USE_FEE = true; @@ -147,15 +147,17 @@ public class ComputeImplTest { RegionAddressId.of("project", "region", "address"); private static final GlobalAddressId GLOBAL_ADDRESS_ID = GlobalAddressId.of("project", "address"); - private static final AddressInfo REGION_ADDRESS = AddressInfo.builder(REGION_ADDRESS_ID).build(); - private static final AddressInfo GLOBAL_ADDRESS = AddressInfo.builder(GLOBAL_ADDRESS_ID).build(); + private static final AddressInfo REGION_ADDRESS = + AddressInfo.newBuilder(REGION_ADDRESS_ID).build(); + private static final AddressInfo GLOBAL_ADDRESS = + AddressInfo.newBuilder(GLOBAL_ADDRESS_ID).build(); private static final DiskId DISK_ID = DiskId.of("project", "zone", "disk"); private static final SnapshotId SNAPSHOT_ID = SnapshotId.of("project", "snapshot"); private static final SnapshotInfo SNAPSHOT = SnapshotInfo.of(SNAPSHOT_ID, DISK_ID); private static final ImageId IMAGE_ID = ImageId.of("project", "image"); private static final ImageInfo IMAGE = ImageInfo.of(IMAGE_ID, DiskImageConfiguration.of(DISK_ID)); private static final DeprecationStatus DEPRECATION_STATUS = - DeprecationStatus.builder(DeprecationStatus.Status.DEPRECATED, IMAGE_ID).build(); + DeprecationStatus.newBuilder(DeprecationStatus.Status.DEPRECATED, IMAGE_ID).build(); private static final DiskInfo DISK = DiskInfo.of(DISK_ID, StandardDiskConfiguration.of(DISK_TYPE_ID)); private static final NetworkId NETWORK_ID = NetworkId.of("project", "network"); @@ -222,9 +224,11 @@ public class ComputeImplTest { ComputeRpc.Option.FILTER, "maximumPersistentDisks ne 42"); // MachineType aggregated list options - private static final Compute.MachineTypeAggregatedListOption MACHINE_TYPE_AGGREGATED_LIST_PAGE_TOKEN = + private static final Compute.MachineTypeAggregatedListOption + MACHINE_TYPE_AGGREGATED_LIST_PAGE_TOKEN = Compute.MachineTypeAggregatedListOption.pageToken("cursor"); - private static final Compute.MachineTypeAggregatedListOption MACHINE_TYPE_AGGREGATED_LIST_PAGE_SIZE = + private static final Compute.MachineTypeAggregatedListOption + MACHINE_TYPE_AGGREGATED_LIST_PAGE_SIZE = Compute.MachineTypeAggregatedListOption.pageSize(42L); private static final Compute.MachineTypeAggregatedListOption MACHINE_TYPE_AGGREGATED_LIST_FILTER = Compute.MachineTypeAggregatedListOption.filter(MACHINE_TYPE_FILTER); @@ -256,8 +260,10 @@ public class ComputeImplTest { Compute.ZoneFilter.notEquals(Compute.ZoneField.NAME, "someName"); private static final Compute.ZoneListOption ZONE_LIST_PAGE_TOKEN = Compute.ZoneListOption.pageToken("cursor"); - private static final Compute.ZoneListOption ZONE_LIST_PAGE_SIZE = Compute.ZoneListOption.pageSize(42L); - private static final Compute.ZoneListOption ZONE_LIST_FILTER = Compute.ZoneListOption.filter(ZONE_FILTER); + private static final Compute.ZoneListOption ZONE_LIST_PAGE_SIZE = + Compute.ZoneListOption.pageSize(42L); + private static final Compute.ZoneListOption ZONE_LIST_FILTER = + Compute.ZoneListOption.filter(ZONE_FILTER); private static final Map ZONE_LIST_OPTIONS = ImmutableMap.of( ComputeRpc.Option.PAGE_TOKEN, "cursor", ComputeRpc.Option.MAX_RESULTS, 42L, @@ -294,7 +300,8 @@ public class ComputeImplTest { Compute.AddressFilter.notEquals(Compute.AddressField.REGION, "someRegion"); private static final Compute.AddressListOption ADDRESS_LIST_PAGE_TOKEN = Compute.AddressListOption.pageToken("cursor"); - private static final Compute.AddressListOption ADDRESS_LIST_PAGE_SIZE = Compute.AddressListOption.pageSize(42L); + private static final Compute.AddressListOption ADDRESS_LIST_PAGE_SIZE = + Compute.AddressListOption.pageSize(42L); private static final Compute.AddressListOption ADDRESS_LIST_FILTER = Compute.AddressListOption.filter(ADDRESS_FILTER); private static final Map ADDRESS_LIST_OPTIONS = ImmutableMap.of( @@ -335,9 +342,12 @@ public class ComputeImplTest { // Image list options private static final Compute.ImageFilter IMAGE_FILTER = Compute.ImageFilter.notEquals(Compute.ImageField.DISK_SIZE_GB, 500L); - private static final Compute.ImageListOption IMAGE_LIST_PAGE_TOKEN = Compute.ImageListOption.pageToken("cursor"); - private static final Compute.ImageListOption IMAGE_LIST_PAGE_SIZE = Compute.ImageListOption.pageSize(42L); - private static final Compute.ImageListOption IMAGE_LIST_FILTER = Compute.ImageListOption.filter(IMAGE_FILTER); + private static final Compute.ImageListOption IMAGE_LIST_PAGE_TOKEN = + Compute.ImageListOption.pageToken("cursor"); + private static final Compute.ImageListOption IMAGE_LIST_PAGE_SIZE = + Compute.ImageListOption.pageSize(42L); + private static final Compute.ImageListOption IMAGE_LIST_FILTER = + Compute.ImageListOption.filter(IMAGE_FILTER); private static final Map IMAGE_LIST_OPTIONS = ImmutableMap.of( ComputeRpc.Option.PAGE_TOKEN, "cursor", ComputeRpc.Option.MAX_RESULTS, 42L, @@ -348,10 +358,14 @@ public class ComputeImplTest { Compute.DiskOption.fields(Compute.DiskField.ID, Compute.DiskField.DESCRIPTION); // Disk list options - private static final Compute.DiskFilter DISK_FILTER = Compute.DiskFilter.notEquals(Compute.DiskField.SIZE_GB, 500L); - private static final Compute.DiskListOption DISK_LIST_PAGE_TOKEN = Compute.DiskListOption.pageToken("cursor"); - private static final Compute.DiskListOption DISK_LIST_PAGE_SIZE = Compute.DiskListOption.pageSize(42L); - private static final Compute.DiskListOption DISK_LIST_FILTER = Compute.DiskListOption.filter(DISK_FILTER); + private static final Compute.DiskFilter DISK_FILTER = + Compute.DiskFilter.notEquals(Compute.DiskField.SIZE_GB, 500L); + private static final Compute.DiskListOption DISK_LIST_PAGE_TOKEN = + Compute.DiskListOption.pageToken("cursor"); + private static final Compute.DiskListOption DISK_LIST_PAGE_SIZE = + Compute.DiskListOption.pageSize(42L); + private static final Compute.DiskListOption DISK_LIST_FILTER = + Compute.DiskListOption.filter(DISK_FILTER); private static final Map DISK_LIST_OPTIONS = ImmutableMap.of( ComputeRpc.Option.PAGE_TOKEN, "cursor", ComputeRpc.Option.MAX_RESULTS, 42L, @@ -367,7 +381,8 @@ public class ComputeImplTest { // Subnetwork options private static final Compute.SubnetworkOption SUBNETWORK_OPTION_FIELDS = - Compute.SubnetworkOption.fields(Compute.SubnetworkField.ID, Compute.SubnetworkField.DESCRIPTION); + Compute.SubnetworkOption.fields(Compute.SubnetworkField.ID, + Compute.SubnetworkField.DESCRIPTION); // Subnetwork list options private static final Compute.SubnetworkFilter SUBNETWORK_FILTER = @@ -384,7 +399,8 @@ public class ComputeImplTest { ComputeRpc.Option.FILTER, "ipCidrRange eq 192.168.0.0/16"); // Subnetwork aggregated list options - private static final Compute.SubnetworkAggregatedListOption SUBNETWORK_AGGREGATED_LIST_PAGE_TOKEN = + private static final Compute.SubnetworkAggregatedListOption + SUBNETWORK_AGGREGATED_LIST_PAGE_TOKEN = Compute.SubnetworkAggregatedListOption.pageToken("cursor"); private static final Compute.SubnetworkAggregatedListOption SUBNETWORK_AGGREGATED_LIST_PAGE_SIZE = Compute.SubnetworkAggregatedListOption.pageSize(42L); @@ -470,64 +486,64 @@ public void setUp() { .build(); Compute otherService = options.toBuilder().build().service(); globalOperation = new Operation.Builder(otherService) - .generatedId(GENERATED_ID) - .operationId(GLOBAL_OPERATION_ID) - .clientOperationId(CLIENT_OPERATION_ID) - .operationType(OPERATION_TYPE) - .targetLink(TARGET_LINK) - .targetId(TARGET_ID) - .status(STATUS) - .statusMessage(STATUS_MESSAGE) - .user(USER) - .progress(PROGRESS) - .insertTime(INSERT_TIME) - .startTime(START_TIME) - .endTime(END_TIME) - .errors(ERRORS) - .warnings(WARNINGS) - .httpErrorStatusCode(HTTP_ERROR_STATUS_CODE) - .httpErrorMessage(HTTP_ERROR_MESSAGE) - .description(DESCRIPTION) + .getGeneratedId(GENERATED_ID) + .setOperationId(GLOBAL_OPERATION_ID) + .setClientOperationId(CLIENT_OPERATION_ID) + .setOperationType(OPERATION_TYPE) + .setTargetLink(TARGET_LINK) + .setTargetId(TARGET_ID) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) + .setUser(USER) + .setProgress(PROGRESS) + .setInsertTime(INSERT_TIME) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setErrors(ERRORS) + .setWarnings(WARNINGS) + .setHttpErrorStatusCode(HTTP_ERROR_STATUS_CODE) + .setHttpErrorMessage(HTTP_ERROR_MESSAGE) + .setDescription(DESCRIPTION) .build(); zoneOperation = new Operation.Builder(otherService) - .generatedId(GENERATED_ID) - .operationId(ZONE_OPERATION_ID) - .clientOperationId(CLIENT_OPERATION_ID) - .operationType(OPERATION_TYPE) - .targetLink(TARGET_LINK) - .targetId(TARGET_ID) - .status(STATUS) - .statusMessage(STATUS_MESSAGE) - .user(USER) - .progress(PROGRESS) - .insertTime(INSERT_TIME) - .startTime(START_TIME) - .endTime(END_TIME) - .errors(ERRORS) - .warnings(WARNINGS) - .httpErrorStatusCode(HTTP_ERROR_STATUS_CODE) - .httpErrorMessage(HTTP_ERROR_MESSAGE) - .description(DESCRIPTION) + .getGeneratedId(GENERATED_ID) + .setOperationId(ZONE_OPERATION_ID) + .setClientOperationId(CLIENT_OPERATION_ID) + .setOperationType(OPERATION_TYPE) + .setTargetLink(TARGET_LINK) + .setTargetId(TARGET_ID) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) + .setUser(USER) + .setProgress(PROGRESS) + .setInsertTime(INSERT_TIME) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setErrors(ERRORS) + .setWarnings(WARNINGS) + .setHttpErrorStatusCode(HTTP_ERROR_STATUS_CODE) + .setHttpErrorMessage(HTTP_ERROR_MESSAGE) + .setDescription(DESCRIPTION) .build(); regionOperation = new Operation.Builder(otherService) - .generatedId(GENERATED_ID) - .operationId(REGION_OPERATION_ID) - .clientOperationId(CLIENT_OPERATION_ID) - .operationType(OPERATION_TYPE) - .targetLink(TARGET_LINK) - .targetId(TARGET_ID) - .status(STATUS) - .statusMessage(STATUS_MESSAGE) - .user(USER) - .progress(PROGRESS) - .insertTime(INSERT_TIME) - .startTime(START_TIME) - .endTime(END_TIME) - .errors(ERRORS) - .warnings(WARNINGS) - .httpErrorStatusCode(HTTP_ERROR_STATUS_CODE) - .httpErrorMessage(HTTP_ERROR_MESSAGE) - .description(DESCRIPTION) + .getGeneratedId(GENERATED_ID) + .setOperationId(REGION_OPERATION_ID) + .setClientOperationId(CLIENT_OPERATION_ID) + .setOperationType(OPERATION_TYPE) + .setTargetLink(TARGET_LINK) + .setTargetId(TARGET_ID) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) + .setUser(USER) + .setProgress(PROGRESS) + .setInsertTime(INSERT_TIME) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setErrors(ERRORS) + .setWarnings(WARNINGS) + .setHttpErrorStatusCode(HTTP_ERROR_STATUS_CODE) + .setHttpErrorMessage(HTTP_ERROR_MESSAGE) + .setDescription(DESCRIPTION) .build(); } @@ -545,29 +561,29 @@ public void testGetOptions() { @Test public void testGetDiskType() { - EasyMock.expect( - computeRpcMock.getDiskType(DISK_TYPE_ID.zone(), DISK_TYPE_ID.type(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getDiskType( + DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andReturn(DISK_TYPE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - DiskType diskType = compute.getDiskType(DISK_TYPE_ID.zone(), DISK_TYPE_ID.type()); + DiskType diskType = compute.getDiskType(DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType()); assertEquals(DISK_TYPE, diskType); } @Test public void testGetDiskType_Null() { - EasyMock.expect( - computeRpcMock.getDiskType(DISK_TYPE_ID.zone(), DISK_TYPE_ID.type(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getDiskType( + DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); - assertNull(compute.getDiskType(DISK_TYPE_ID.zone(), DISK_TYPE_ID.type())); + assertNull(compute.getDiskType(DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType())); } @Test public void testGetDiskTypeFromDiskTypeId() { - EasyMock.expect( - computeRpcMock.getDiskType(DISK_TYPE_ID.zone(), DISK_TYPE_ID.type(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getDiskType( + DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andReturn(DISK_TYPE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -580,13 +596,14 @@ public void testGetDiskTypeWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); EasyMock.expect( computeRpcMock.getDiskType( - eq(DISK_TYPE_ID.zone()), eq(DISK_TYPE_ID.type()), capture(capturedOptions))) + eq(DISK_TYPE_ID.getZone()), eq(DISK_TYPE_ID.getType()), capture(capturedOptions))) .andReturn(DISK_TYPE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - DiskType diskType = - compute.getDiskType(DISK_TYPE_ID.zone(), DISK_TYPE_ID.type(), DISK_TYPE_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(DISK_TYPE_OPTION_FIELDS.rpcOption()); + DiskType diskType = compute.getDiskType(DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), + DISK_TYPE_OPTION_FIELDS); + String selector = + (String) capturedOptions.getValue().get(DISK_TYPE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -601,10 +618,10 @@ public void testListDiskTypes() { ImmutableList diskTypeList = ImmutableList.of(DISK_TYPE, DISK_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(diskTypeList, DiskType.TO_PB_FUNCTION)); - EasyMock.expect(computeRpcMock.listDiskTypes(DISK_TYPE_ID.zone(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listDiskTypes(DISK_TYPE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listDiskTypes(DISK_TYPE_ID.zone()); + Page page = compute.listDiskTypes(DISK_TYPE_ID.getZone()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.values(), DiskType.class)); } @@ -619,14 +636,15 @@ public void testListDiskTypesNextPage() { ComputeRpc.Tuple.of(cursor, Iterables.transform(diskTypeList, DiskType.TO_PB_FUNCTION)); ImmutableList nextDiskTypeList = ImmutableList.of(DISK_TYPE); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextDiskTypeList, DiskType.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextDiskTypeList, DiskType.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); - EasyMock.expect(computeRpcMock.listDiskTypes(DISK_TYPE_ID.zone(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listDiskTypes(DISK_TYPE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); - EasyMock.expect(computeRpcMock.listDiskTypes(DISK_TYPE_ID.zone(), nextOptions)) + EasyMock.expect(computeRpcMock.listDiskTypes(DISK_TYPE_ID.getZone(), nextOptions)) .andReturn(nextResult); EasyMock.replay(computeRpcMock); - Page page = compute.listDiskTypes(DISK_TYPE_ID.zone()); + Page page = compute.listDiskTypes(DISK_TYPE_ID.getZone()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.values(), DiskType.class)); page = page.nextPage(); @@ -639,11 +657,11 @@ public void testListEmptyDiskTypes() { ImmutableList diskTypes = ImmutableList.of(); ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, diskTypes); - EasyMock.expect(computeRpcMock.listDiskTypes(DISK_TYPE_ID.zone(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listDiskTypes(DISK_TYPE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); compute = options.service(); - Page page = compute.listDiskTypes(DISK_TYPE_ID.zone()); + Page page = compute.listDiskTypes(DISK_TYPE_ID.getZone()); assertNull(page.nextPageCursor()); assertArrayEquals(diskTypes.toArray(), Iterables.toArray(page.values(), DiskType.class)); } @@ -655,10 +673,10 @@ public void testListDiskTypesWithOptions() { ImmutableList diskTypeList = ImmutableList.of(DISK_TYPE, DISK_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(diskTypeList, DiskType.TO_PB_FUNCTION)); - EasyMock.expect(computeRpcMock.listDiskTypes(DISK_TYPE_ID.zone(), DISK_TYPE_LIST_OPTIONS)) + EasyMock.expect(computeRpcMock.listDiskTypes(DISK_TYPE_ID.getZone(), DISK_TYPE_LIST_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listDiskTypes(DISK_TYPE_ID.zone(), DISK_TYPE_LIST_PAGE_SIZE, + Page page = compute.listDiskTypes(DISK_TYPE_ID.getZone(), DISK_TYPE_LIST_PAGE_SIZE, DISK_TYPE_LIST_PAGE_TOKEN, DISK_TYPE_LIST_FILTER); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.values(), DiskType.class)); @@ -688,7 +706,8 @@ public void testAggregatedListDiskTypesNextPage() { ComputeRpc.Tuple.of(cursor, Iterables.transform(diskTypeList, DiskType.TO_PB_FUNCTION)); ImmutableList nextDiskTypeList = ImmutableList.of(DISK_TYPE); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextDiskTypeList, DiskType.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextDiskTypeList, DiskType.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); EasyMock.expect(computeRpcMock.listDiskTypes(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.expect(computeRpcMock.listDiskTypes(nextOptions)).andReturn(nextResult); @@ -733,12 +752,12 @@ public void testAggregatedListDiskTypesWithOptions() { public void testGetMachineType() { EasyMock.expect( computeRpcMock.getMachineType( - MACHINE_TYPE_ID.zone(), MACHINE_TYPE_ID.type(), EMPTY_RPC_OPTIONS)) + MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andReturn(MACHINE_TYPE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); MachineType machineType = - compute.getMachineType(MACHINE_TYPE_ID.zone(), MACHINE_TYPE_ID.type()); + compute.getMachineType(MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_ID.getType()); assertEquals(MACHINE_TYPE, machineType); } @@ -746,17 +765,17 @@ public void testGetMachineType() { public void testGetMachineType_Null() { EasyMock.expect( computeRpcMock.getMachineType( - MACHINE_TYPE_ID.zone(), MACHINE_TYPE_ID.type(), EMPTY_RPC_OPTIONS)) + MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); - assertNull(compute.getMachineType(MACHINE_TYPE_ID.zone(), MACHINE_TYPE_ID.type())); + assertNull(compute.getMachineType(MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_ID.getType())); } @Test public void testGetMachineTypeFromMachineTypeId() { EasyMock.expect(computeRpcMock.getMachineType( - MACHINE_TYPE_ID.zone(), MACHINE_TYPE_ID.type(), EMPTY_RPC_OPTIONS)) + MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andReturn(MACHINE_TYPE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -768,14 +787,15 @@ public void testGetMachineTypeFromMachineTypeId() { public void testGetMachineTypeWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); EasyMock.expect( - computeRpcMock.getMachineType(eq(MACHINE_TYPE_ID.zone()), eq(MACHINE_TYPE_ID.type()), + computeRpcMock.getMachineType(eq(MACHINE_TYPE_ID.getZone()), eq(MACHINE_TYPE_ID.getType()), capture(capturedOptions))) .andReturn(MACHINE_TYPE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - MachineType machineType = compute.getMachineType(MACHINE_TYPE_ID.zone(), - MACHINE_TYPE_ID.type(), MACHINE_TYPE_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(DISK_TYPE_OPTION_FIELDS.rpcOption()); + MachineType machineType = compute.getMachineType(MACHINE_TYPE_ID.getZone(), + MACHINE_TYPE_ID.getType(), MACHINE_TYPE_OPTION_FIELDS); + String selector = + (String) capturedOptions.getValue().get(DISK_TYPE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -789,11 +809,12 @@ public void testListMachineTypes() { compute = options.service(); ImmutableList machineTypeList = ImmutableList.of(MACHINE_TYPE, MACHINE_TYPE); ComputeRpc.Tuple> result = - ComputeRpc.Tuple.of(cursor, Iterables.transform(machineTypeList, MachineType.TO_PB_FUNCTION)); - EasyMock.expect(computeRpcMock.listMachineTypes(MACHINE_TYPE_ID.zone(), EMPTY_RPC_OPTIONS)) + ComputeRpc.Tuple.of(cursor, + Iterables.transform(machineTypeList, MachineType.TO_PB_FUNCTION)); + EasyMock.expect(computeRpcMock.listMachineTypes(MACHINE_TYPE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listMachineTypes(MACHINE_TYPE_ID.zone()); + Page page = compute.listMachineTypes(MACHINE_TYPE_ID.getZone()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(machineTypeList.toArray(), Iterables.toArray(page.values(), MachineType.class)); @@ -806,17 +827,20 @@ public void testListMachineTypesNextPage() { compute = options.service(); ImmutableList machineTypeList = ImmutableList.of(MACHINE_TYPE, MACHINE_TYPE); ComputeRpc.Tuple> result = - ComputeRpc.Tuple.of(cursor, Iterables.transform(machineTypeList, MachineType.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(cursor, + Iterables.transform(machineTypeList, MachineType.TO_PB_FUNCTION)); ImmutableList nextMachineTypeList = ImmutableList.of(MACHINE_TYPE); - ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextMachineTypeList, MachineType.TO_PB_FUNCTION)); + ComputeRpc.Tuple> + nextResult = + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextMachineTypeList, MachineType.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); - EasyMock.expect(computeRpcMock.listMachineTypes(MACHINE_TYPE_ID.zone(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listMachineTypes(MACHINE_TYPE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); - EasyMock.expect(computeRpcMock.listMachineTypes(MACHINE_TYPE_ID.zone(), nextOptions)) + EasyMock.expect(computeRpcMock.listMachineTypes(MACHINE_TYPE_ID.getZone(), nextOptions)) .andReturn(nextResult); EasyMock.replay(computeRpcMock); - Page page = compute.listMachineTypes(MACHINE_TYPE_ID.zone()); + Page page = compute.listMachineTypes(MACHINE_TYPE_ID.getZone()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(machineTypeList.toArray(), Iterables.toArray(page.values(), MachineType.class)); @@ -833,11 +857,11 @@ public void testListEmptyMachineTypes() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, machineTypes); - EasyMock.expect(computeRpcMock.listMachineTypes(MACHINE_TYPE_ID.zone(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listMachineTypes(MACHINE_TYPE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); compute = options.service(); - Page page = compute.listMachineTypes(MACHINE_TYPE_ID.zone()); + Page page = compute.listMachineTypes(MACHINE_TYPE_ID.getZone()); assertNull(page.nextPageCursor()); assertArrayEquals(machineTypes.toArray(), Iterables.toArray(page.values(), MachineType.class)); } @@ -848,12 +872,13 @@ public void testListMachineTypesWithOptions() { compute = options.service(); ImmutableList machineTypeList = ImmutableList.of(MACHINE_TYPE, MACHINE_TYPE); ComputeRpc.Tuple> result = - ComputeRpc.Tuple.of(cursor, Iterables.transform(machineTypeList, MachineType.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(cursor, + Iterables.transform(machineTypeList, MachineType.TO_PB_FUNCTION)); EasyMock.expect( - computeRpcMock.listMachineTypes(MACHINE_TYPE_ID.zone(), MACHINE_TYPE_LIST_OPTIONS)) + computeRpcMock.listMachineTypes(MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_LIST_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listMachineTypes(MACHINE_TYPE_ID.zone(), + Page page = compute.listMachineTypes(MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_LIST_PAGE_SIZE, MACHINE_TYPE_LIST_PAGE_TOKEN, MACHINE_TYPE_LIST_FILTER); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(machineTypeList.toArray(), @@ -866,7 +891,8 @@ public void testAggregatedListMachineTypes() { compute = options.service(); ImmutableList machineTypeList = ImmutableList.of(MACHINE_TYPE, MACHINE_TYPE); ComputeRpc.Tuple> result = - ComputeRpc.Tuple.of(cursor, Iterables.transform(machineTypeList, MachineType.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(cursor, + Iterables.transform(machineTypeList, MachineType.TO_PB_FUNCTION)); EasyMock.expect(computeRpcMock.listMachineTypes(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listMachineTypes(); @@ -882,10 +908,13 @@ public void testAggregatedListMachineTypesNextPage() { compute = options.service(); ImmutableList machineTypeList = ImmutableList.of(MACHINE_TYPE, MACHINE_TYPE); ComputeRpc.Tuple> result = - ComputeRpc.Tuple.of(cursor, Iterables.transform(machineTypeList, MachineType.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(cursor, + Iterables.transform(machineTypeList, MachineType.TO_PB_FUNCTION)); ImmutableList nextMachineTypeList = ImmutableList.of(MACHINE_TYPE); - ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextMachineTypeList, MachineType.TO_PB_FUNCTION)); + ComputeRpc.Tuple> + nextResult = + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextMachineTypeList, MachineType.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); EasyMock.expect(computeRpcMock.listMachineTypes(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.expect(computeRpcMock.listMachineTypes(nextOptions)).andReturn(nextResult); @@ -921,7 +950,8 @@ public void testAggregatedListMachineTypesWithOptions() { compute = options.service(); ImmutableList machineTypeList = ImmutableList.of(MACHINE_TYPE, MACHINE_TYPE); ComputeRpc.Tuple> result = - ComputeRpc.Tuple.of(cursor, Iterables.transform(machineTypeList, MachineType.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(cursor, + Iterables.transform(machineTypeList, MachineType.TO_PB_FUNCTION)); EasyMock.expect(computeRpcMock.listMachineTypes(MACHINE_TYPE_LIST_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); @@ -934,32 +964,32 @@ public void testAggregatedListMachineTypesWithOptions() { @Test public void testGetRegion() { - EasyMock.expect(computeRpcMock.getRegion(REGION_ID.region(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getRegion(REGION_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(REGION.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - Region region = compute.getRegion(REGION_ID.region()); + Region region = compute.getRegion(REGION_ID.getRegion()); assertEquals(REGION, region); } @Test public void testGetRegion_Null() { - EasyMock.expect(computeRpcMock.getRegion(REGION_ID.region(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getRegion(REGION_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); - assertNull(compute.getRegion(REGION_ID.region())); + assertNull(compute.getRegion(REGION_ID.getRegion())); } @Test public void testGetRegionWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.getRegion(eq(REGION_ID.region()), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.getRegion(eq(REGION_ID.getRegion()), capture(capturedOptions))) .andReturn(REGION.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - Region region = compute.getRegion(REGION_ID.region(), REGION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(REGION_OPTION_FIELDS.rpcOption()); + Region region = compute.getRegion(REGION_ID.getRegion(), REGION_OPTION_FIELDS); + String selector = (String) capturedOptions.getValue().get(REGION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -1035,31 +1065,31 @@ public void testListRegionsWithOptions() { @Test public void testGetZone() { - EasyMock.expect(computeRpcMock.getZone(ZONE_ID.zone(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getZone(ZONE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(ZONE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - Zone zone = compute.getZone(ZONE_ID.zone()); + Zone zone = compute.getZone(ZONE_ID.getZone()); assertEquals(ZONE, zone); } @Test public void testGetZone_Null() { - EasyMock.expect(computeRpcMock.getZone(ZONE_ID.zone(), EMPTY_RPC_OPTIONS)).andReturn(null); + EasyMock.expect(computeRpcMock.getZone(ZONE_ID.getZone(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); - assertNull(compute.getZone(ZONE_ID.zone())); + assertNull(compute.getZone(ZONE_ID.getZone())); } @Test public void testGetZoneWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.getZone(eq(ZONE_ID.zone()), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.getZone(eq(ZONE_ID.getZone()), capture(capturedOptions))) .andReturn(ZONE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - Zone zone = compute.getZone(ZONE_ID.zone(), ZONE_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(ZONE_OPTION_FIELDS.rpcOption()); + Zone zone = compute.getZone(ZONE_ID.getZone(), ZONE_OPTION_FIELDS); + String selector = (String) capturedOptions.getValue().get(ZONE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -1134,34 +1164,34 @@ public void testListZonesWithOptions() { @Test public void testGetLicenseFromString() { - EasyMock.expect(computeRpcMock.getLicense(PROJECT, LICENSE_ID.license(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getLicense(PROJECT, LICENSE_ID.getLicense(), EMPTY_RPC_OPTIONS)) .andReturn(LICENSE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - License license = compute.getLicense(LICENSE_ID.license()); + License license = compute.getLicense(LICENSE_ID.getLicense()); assertEquals(LICENSE, license); } @Test public void testGetLicenseFromString_Null() { - EasyMock.expect(computeRpcMock.getLicense(PROJECT, LICENSE_ID.license(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getLicense(PROJECT, LICENSE_ID.getLicense(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); - assertNull(compute.getLicense(LICENSE_ID.license())); + assertNull(compute.getLicense(LICENSE_ID.getLicense())); } @Test public void testGetLicenseFromStringWithOptions() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect( - computeRpcMock.getLicense(eq(PROJECT), eq(LICENSE_ID.license()), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.getLicense( + eq(PROJECT), eq(LICENSE_ID.getLicense()), capture(capturedOptions))) .andReturn(LICENSE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - License license = compute.getLicense(LICENSE_ID.license(), LICENSE_OPTION_FIELDS); + License license = compute.getLicense(LICENSE_ID.getLicense(), LICENSE_OPTION_FIELDS); assertEquals(LICENSE, license); - String selector = (String) capturedOptions.getValue().get(LICENSE_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(LICENSE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("chargesUseFee")); assertEquals(22, selector.length()); @@ -1172,14 +1202,14 @@ public void testGetLicenseFromStringWithOptions() { public void testGetLicenseFromIdWithOptions() { Capture> capturedOptions = Capture.newInstance(); LicenseId licenseId = LicenseId.of("project2", "license2"); - EasyMock.expect(computeRpcMock.getLicense(eq(licenseId.project()), eq(licenseId.license()), - capture(capturedOptions))) + EasyMock.expect(computeRpcMock.getLicense( + eq(licenseId.getProject()), eq(licenseId.getLicense()), capture(capturedOptions))) .andReturn(LICENSE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); License license = compute.getLicense(licenseId, LICENSE_OPTION_FIELDS); assertEquals(LICENSE, license); - String selector = (String) capturedOptions.getValue().get(LICENSE_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(LICENSE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("chargesUseFee")); assertEquals(22, selector.length()); @@ -1189,9 +1219,8 @@ public void testGetLicenseFromIdWithOptions() { @Test public void testGetLicenseFromId() { LicenseId licenseId = LicenseId.of("project2", "license2"); - EasyMock.expect( - computeRpcMock.getLicense(licenseId.project(), licenseId.license(), EMPTY_RPC_OPTIONS)) - .andReturn(LICENSE.toPb()); + EasyMock.expect(computeRpcMock.getLicense(licenseId.getProject(), licenseId.getLicense(), + EMPTY_RPC_OPTIONS)).andReturn(LICENSE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); License license = compute.getLicense(licenseId); @@ -1201,8 +1230,8 @@ public void testGetLicenseFromId() { @Test public void testGetLicenseFromId_Null() { LicenseId licenseId = LicenseId.of("project2", "license2"); - EasyMock.expect( - computeRpcMock.getLicense(licenseId.project(), licenseId.license(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getLicense( + licenseId.getProject(), licenseId.getLicense(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -1212,7 +1241,7 @@ public void testGetLicenseFromId_Null() { @Test public void testGetGlobalOperation() { EasyMock.expect( - computeRpcMock.getGlobalOperation(GLOBAL_OPERATION_ID.operation(), EMPTY_RPC_OPTIONS)) + computeRpcMock.getGlobalOperation(GLOBAL_OPERATION_ID.getOperation(), EMPTY_RPC_OPTIONS)) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -1222,7 +1251,7 @@ public void testGetGlobalOperation() { @Test public void testGetGlobalOperation_Null() { EasyMock.expect( - computeRpcMock.getGlobalOperation(GLOBAL_OPERATION_ID.operation(), EMPTY_RPC_OPTIONS)) + computeRpcMock.getGlobalOperation(GLOBAL_OPERATION_ID.getOperation(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -1233,12 +1262,13 @@ public void testGetGlobalOperation_Null() { public void testGetGlobalOperationWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); EasyMock.expect(computeRpcMock.getGlobalOperation( - eq(GLOBAL_OPERATION_ID.operation()), capture(capturedOptions))) + eq(GLOBAL_OPERATION_ID.getOperation()), capture(capturedOptions))) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.getOperation(GLOBAL_OPERATION_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -1270,7 +1300,8 @@ public void testListGlobalOperationsNextPage() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextOperationList, OPERATION_TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextOperationList, OPERATION_TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); EasyMock.expect(computeRpcMock.listGlobalOperations(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.expect(computeRpcMock.listGlobalOperations(nextOptions)).andReturn(nextResult); @@ -1315,7 +1346,7 @@ public void testListGlobalOperationsWithOptions() { @Test public void testDeleteGlobalOperation_True() { - EasyMock.expect(computeRpcMock.deleteGlobalOperation(GLOBAL_OPERATION_ID.operation())) + EasyMock.expect(computeRpcMock.deleteGlobalOperation(GLOBAL_OPERATION_ID.getOperation())) .andReturn(true); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -1324,7 +1355,7 @@ public void testDeleteGlobalOperation_True() { @Test public void testDeleteGlobalOperation_False() { - EasyMock.expect(computeRpcMock.deleteGlobalOperation(GLOBAL_OPERATION_ID.operation())) + EasyMock.expect(computeRpcMock.deleteGlobalOperation(GLOBAL_OPERATION_ID.getOperation())) .andReturn(false); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -1333,8 +1364,8 @@ public void testDeleteGlobalOperation_False() { @Test public void testGetRegionOperation() { - EasyMock.expect(computeRpcMock.getRegionOperation(REGION_OPERATION_ID.region(), - REGION_OPERATION_ID.operation(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getRegionOperation(REGION_OPERATION_ID.getRegion(), + REGION_OPERATION_ID.getOperation(), EMPTY_RPC_OPTIONS)) .andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -1344,8 +1375,8 @@ public void testGetRegionOperation() { @Test public void testGetRegionOperation_Null() { - EasyMock.expect(computeRpcMock.getRegionOperation(REGION_OPERATION_ID.region(), - REGION_OPERATION_ID.operation(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getRegionOperation(REGION_OPERATION_ID.getRegion(), + REGION_OPERATION_ID.getOperation(), EMPTY_RPC_OPTIONS)) .andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -1356,13 +1387,14 @@ public void testGetRegionOperation_Null() { @Test public void testGetRegionOperationWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.getRegionOperation(eq(REGION_OPERATION_ID.region()), - eq(REGION_OPERATION_ID.operation()), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.getRegionOperation(eq(REGION_OPERATION_ID.getRegion()), + eq(REGION_OPERATION_ID.getOperation()), capture(capturedOptions))) .andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.getOperation(REGION_OPERATION_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -1378,10 +1410,10 @@ public void testListRegionOperations() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); EasyMock.expect( - computeRpcMock.listRegionOperations(REGION_OPERATION_ID.region(), EMPTY_RPC_OPTIONS)) + computeRpcMock.listRegionOperations(REGION_OPERATION_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listRegionOperations(REGION_OPERATION_ID.region()); + Page page = compute.listRegionOperations(REGION_OPERATION_ID.getRegion()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); } @@ -1396,14 +1428,15 @@ public void testListRegionOperationsNextPage() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextOperationList, OPERATION_TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextOperationList, OPERATION_TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); - EasyMock.expect(computeRpcMock.listRegionOperations(REGION_OPERATION_ID.region(), + EasyMock.expect(computeRpcMock.listRegionOperations(REGION_OPERATION_ID.getRegion(), EMPTY_RPC_OPTIONS)).andReturn(result); - EasyMock.expect(computeRpcMock.listRegionOperations(REGION_OPERATION_ID.region(), + EasyMock.expect(computeRpcMock.listRegionOperations(REGION_OPERATION_ID.getRegion(), nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); - Page page = compute.listRegionOperations(REGION_OPERATION_ID.region()); + Page page = compute.listRegionOperations(REGION_OPERATION_ID.getRegion()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); page = page.nextPage(); @@ -1419,11 +1452,11 @@ public void testListEmptyRegionOperations() { ComputeRpc.Tuple.>of(null, operations); EasyMock.expect( - computeRpcMock.listRegionOperations(REGION_OPERATION_ID.region(), EMPTY_RPC_OPTIONS)) + computeRpcMock.listRegionOperations(REGION_OPERATION_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); compute = options.service(); - Page page = compute.listRegionOperations(REGION_OPERATION_ID.region()); + Page page = compute.listRegionOperations(REGION_OPERATION_ID.getRegion()); assertNull(page.nextPageCursor()); assertArrayEquals(operations.toArray(), Iterables.toArray(page.values(), Operation.class)); } @@ -1435,11 +1468,11 @@ public void testListRegionOperationsWithOptions() { ImmutableList operationList = ImmutableList.of(regionOperation, regionOperation); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); - EasyMock.expect( - computeRpcMock.listRegionOperations(REGION_OPERATION_ID.region(), OPERATION_LIST_OPTIONS)) + EasyMock.expect(computeRpcMock.listRegionOperations( + REGION_OPERATION_ID.getRegion(), OPERATION_LIST_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listRegionOperations(REGION_OPERATION_ID.region(), + Page page = compute.listRegionOperations(REGION_OPERATION_ID.getRegion(), OPERATION_LIST_PAGE_SIZE, OPERATION_LIST_PAGE_TOKEN, OPERATION_LIST_FILTER); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); @@ -1447,8 +1480,8 @@ public void testListRegionOperationsWithOptions() { @Test public void testDeleteRegionOperation_True() { - EasyMock.expect(computeRpcMock.deleteRegionOperation(REGION_OPERATION_ID.region(), - REGION_OPERATION_ID.operation())).andReturn(true); + EasyMock.expect(computeRpcMock.deleteRegionOperation(REGION_OPERATION_ID.getRegion(), + REGION_OPERATION_ID.getOperation())).andReturn(true); EasyMock.replay(computeRpcMock); compute = options.service(); assertTrue(compute.deleteOperation(REGION_OPERATION_ID)); @@ -1456,8 +1489,8 @@ public void testDeleteRegionOperation_True() { @Test public void testDeleteRegionOperation_False() { - EasyMock.expect(computeRpcMock.deleteRegionOperation(REGION_OPERATION_ID.region(), - REGION_OPERATION_ID.operation())).andReturn(false); + EasyMock.expect(computeRpcMock.deleteRegionOperation(REGION_OPERATION_ID.getRegion(), + REGION_OPERATION_ID.getOperation())).andReturn(false); EasyMock.replay(computeRpcMock); compute = options.service(); assertFalse(compute.deleteOperation(REGION_OPERATION_ID)); @@ -1465,8 +1498,8 @@ public void testDeleteRegionOperation_False() { @Test public void testGetZoneOperation() { - EasyMock.expect(computeRpcMock.getZoneOperation(ZONE_OPERATION_ID.zone(), - ZONE_OPERATION_ID.operation(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); + EasyMock.expect(computeRpcMock.getZoneOperation(ZONE_OPERATION_ID.getZone(), + ZONE_OPERATION_ID.getOperation(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.getOperation(ZONE_OPERATION_ID); @@ -1475,8 +1508,8 @@ public void testGetZoneOperation() { @Test public void testGetZoneOperation_Null() { - EasyMock.expect(computeRpcMock.getZoneOperation(ZONE_OPERATION_ID.zone(), - ZONE_OPERATION_ID.operation(), EMPTY_RPC_OPTIONS)).andReturn(null); + EasyMock.expect(computeRpcMock.getZoneOperation(ZONE_OPERATION_ID.getZone(), + ZONE_OPERATION_ID.getOperation(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); assertNull(compute.getOperation(ZONE_OPERATION_ID)); @@ -1485,13 +1518,14 @@ public void testGetZoneOperation_Null() { @Test public void testGetZoneOperationWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.getZoneOperation(eq(ZONE_OPERATION_ID.zone()), - eq(ZONE_OPERATION_ID.operation()), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.getZoneOperation(eq(ZONE_OPERATION_ID.getZone()), + eq(ZONE_OPERATION_ID.getOperation()), capture(capturedOptions))) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.getOperation(ZONE_OPERATION_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -1507,10 +1541,10 @@ public void testListZoneOperations() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); EasyMock.expect( - computeRpcMock.listZoneOperations(ZONE_OPERATION_ID.zone(), EMPTY_RPC_OPTIONS)) + computeRpcMock.listZoneOperations(ZONE_OPERATION_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listZoneOperations(ZONE_OPERATION_ID.zone()); + Page page = compute.listZoneOperations(ZONE_OPERATION_ID.getZone()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); } @@ -1525,14 +1559,16 @@ public void testListZoneOperationsNextPage() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextOperationList, OPERATION_TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextOperationList, OPERATION_TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); - EasyMock.expect(computeRpcMock.listZoneOperations(ZONE_OPERATION_ID.zone(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listZoneOperations( + ZONE_OPERATION_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); - EasyMock.expect(computeRpcMock.listZoneOperations(ZONE_OPERATION_ID.zone(), nextOptions)) + EasyMock.expect(computeRpcMock.listZoneOperations(ZONE_OPERATION_ID.getZone(), nextOptions)) .andReturn(nextResult); EasyMock.replay(computeRpcMock); - Page page = compute.listZoneOperations(ZONE_OPERATION_ID.zone()); + Page page = compute.listZoneOperations(ZONE_OPERATION_ID.getZone()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); page = page.nextPage(); @@ -1548,11 +1584,11 @@ public void testListEmptyZoneOperations() { ComputeRpc.Tuple.>of(null, operations); EasyMock.expect( - computeRpcMock.listZoneOperations(ZONE_OPERATION_ID.zone(), EMPTY_RPC_OPTIONS)) + computeRpcMock.listZoneOperations(ZONE_OPERATION_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); compute = options.service(); - Page page = compute.listZoneOperations(ZONE_OPERATION_ID.zone()); + Page page = compute.listZoneOperations(ZONE_OPERATION_ID.getZone()); assertNull(page.nextPageCursor()); assertArrayEquals(operations.toArray(), Iterables.toArray(page.values(), Operation.class)); } @@ -1565,10 +1601,10 @@ public void testListZoneOperationsWithOptions() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); EasyMock.expect( - computeRpcMock.listZoneOperations(ZONE_OPERATION_ID.zone(), OPERATION_LIST_OPTIONS)) + computeRpcMock.listZoneOperations(ZONE_OPERATION_ID.getZone(), OPERATION_LIST_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listZoneOperations(ZONE_OPERATION_ID.zone(), + Page page = compute.listZoneOperations(ZONE_OPERATION_ID.getZone(), OPERATION_LIST_PAGE_SIZE, OPERATION_LIST_PAGE_TOKEN, OPERATION_LIST_FILTER); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); @@ -1576,8 +1612,8 @@ public void testListZoneOperationsWithOptions() { @Test public void testDeleteZoneOperation_True() { - EasyMock.expect(computeRpcMock.deleteZoneOperation(ZONE_OPERATION_ID.zone(), - ZONE_OPERATION_ID.operation())).andReturn(true); + EasyMock.expect(computeRpcMock.deleteZoneOperation(ZONE_OPERATION_ID.getZone(), + ZONE_OPERATION_ID.getOperation())).andReturn(true); EasyMock.replay(computeRpcMock); compute = options.service(); assertTrue(compute.deleteOperation(ZONE_OPERATION_ID)); @@ -1585,8 +1621,8 @@ public void testDeleteZoneOperation_True() { @Test public void testDeleteZoneOperation_False() { - EasyMock.expect(computeRpcMock.deleteZoneOperation(ZONE_OPERATION_ID.zone(), - ZONE_OPERATION_ID.operation())).andReturn(false); + EasyMock.expect(computeRpcMock.deleteZoneOperation(ZONE_OPERATION_ID.getZone(), + ZONE_OPERATION_ID.getOperation())).andReturn(false); EasyMock.replay(computeRpcMock); compute = options.service(); assertFalse(compute.deleteOperation(ZONE_OPERATION_ID)); @@ -1594,7 +1630,8 @@ public void testDeleteZoneOperation_False() { @Test public void testGetGlobalAddress() { - EasyMock.expect(computeRpcMock.getGlobalAddress(GLOBAL_ADDRESS_ID.address(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getGlobalAddress( + GLOBAL_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)) .andReturn(GLOBAL_ADDRESS.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -1604,7 +1641,8 @@ public void testGetGlobalAddress() { @Test public void testGetGlobalAddress_Null() { - EasyMock.expect(computeRpcMock.getGlobalAddress(GLOBAL_ADDRESS_ID.address(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getGlobalAddress( + GLOBAL_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -1615,12 +1653,12 @@ public void testGetGlobalAddress_Null() { public void testGetGlobalAddressWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); EasyMock.expect(computeRpcMock.getGlobalAddress( - eq(GLOBAL_ADDRESS_ID.address()), capture(capturedOptions))) + eq(GLOBAL_ADDRESS_ID.getAddress()), capture(capturedOptions))) .andReturn(GLOBAL_ADDRESS.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Address address = compute.getAddress(GLOBAL_ADDRESS_ID, ADDRESS_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(ADDRESS_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(ADDRESS_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -1630,8 +1668,8 @@ public void testGetGlobalAddressWithSelectedFields() { @Test public void testGetRegionAddress() { - EasyMock.expect(computeRpcMock.getRegionAddress(REGION_ADDRESS_ID.region(), - REGION_ADDRESS_ID.address(), EMPTY_RPC_OPTIONS)).andReturn(REGION_ADDRESS.toPb()); + EasyMock.expect(computeRpcMock.getRegionAddress(REGION_ADDRESS_ID.getRegion(), + REGION_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)).andReturn(REGION_ADDRESS.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Address address = compute.getAddress(REGION_ADDRESS_ID); @@ -1640,8 +1678,8 @@ public void testGetRegionAddress() { @Test public void testGetRegionAddress_Null() { - EasyMock.expect(computeRpcMock.getRegionAddress(REGION_ADDRESS_ID.region(), - REGION_ADDRESS_ID.address(), EMPTY_RPC_OPTIONS)).andReturn(REGION_ADDRESS.toPb()); + EasyMock.expect(computeRpcMock.getRegionAddress(REGION_ADDRESS_ID.getRegion(), + REGION_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)).andReturn(REGION_ADDRESS.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Address address = compute.getAddress(REGION_ADDRESS_ID); @@ -1651,13 +1689,13 @@ public void testGetRegionAddress_Null() { @Test public void testGetRegionAddressWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.getRegionAddress(eq(REGION_ADDRESS_ID.region()), - eq(REGION_ADDRESS_ID.address()), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.getRegionAddress(eq(REGION_ADDRESS_ID.getRegion()), + eq(REGION_ADDRESS_ID.getAddress()), capture(capturedOptions))) .andReturn(REGION_ADDRESS.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Address address = compute.getAddress(REGION_ADDRESS_ID, ADDRESS_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(ADDRESS_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(ADDRESS_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -1667,8 +1705,8 @@ public void testGetRegionAddressWithSelectedFields() { @Test public void testDeleteGlobalAddress_Operation() { - EasyMock - .expect(computeRpcMock.deleteGlobalAddress(GLOBAL_ADDRESS_ID.address(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.deleteGlobalAddress( + GLOBAL_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -1678,12 +1716,13 @@ public void testDeleteGlobalAddress_Operation() { @Test public void testDeleteGlobalAddressWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.deleteGlobalAddress(eq(GLOBAL_ADDRESS_ID.address()), + EasyMock.expect(computeRpcMock.deleteGlobalAddress(eq(GLOBAL_ADDRESS_ID.getAddress()), capture(capturedOptions))).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.deleteAddress(GLOBAL_ADDRESS_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -1693,8 +1732,8 @@ public void testDeleteGlobalAddressWithSelectedFields_Operation() { @Test public void testDeleteGlobalAddress_Null() { - EasyMock - .expect(computeRpcMock.deleteGlobalAddress(GLOBAL_ADDRESS_ID.address(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.deleteGlobalAddress( + GLOBAL_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -1703,8 +1742,8 @@ public void testDeleteGlobalAddress_Null() { @Test public void testDeleteRegionAddress_Operation() { - EasyMock.expect(computeRpcMock.deleteRegionAddress(REGION_ADDRESS_ID.region(), - REGION_ADDRESS_ID.address(), EMPTY_RPC_OPTIONS)).andReturn(regionOperation.toPb()); + EasyMock.expect(computeRpcMock.deleteRegionAddress(REGION_ADDRESS_ID.getRegion(), + REGION_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)).andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); assertEquals(regionOperation, compute.deleteAddress(REGION_ADDRESS_ID)); @@ -1713,13 +1752,14 @@ public void testDeleteRegionAddress_Operation() { @Test public void testDeleteRegionAddressWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.deleteRegionAddress(eq(REGION_ADDRESS_ID.region()), - eq(REGION_ADDRESS_ID.address()), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.deleteRegionAddress(eq(REGION_ADDRESS_ID.getRegion()), + eq(REGION_ADDRESS_ID.getAddress()), capture(capturedOptions))) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.deleteAddress(REGION_ADDRESS_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -1729,8 +1769,8 @@ public void testDeleteRegionAddressWithSelectedFields_Operation() { @Test public void testDeleteRegionAddress_Null() { - EasyMock.expect(computeRpcMock.deleteRegionAddress(REGION_ADDRESS_ID.region(), - REGION_ADDRESS_ID.address(), EMPTY_RPC_OPTIONS)).andReturn(null); + EasyMock.expect(computeRpcMock.deleteRegionAddress(REGION_ADDRESS_ID.getRegion(), + REGION_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); assertNull(compute.deleteAddress(REGION_ADDRESS_ID)); @@ -1765,7 +1805,8 @@ public void testListGlobalAddressesNextPage() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(addressList, AddressInfo.TO_PB_FUNCTION)); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextAddressList, AddressInfo.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextAddressList, AddressInfo.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); EasyMock.expect(computeRpcMock.listGlobalAddresses(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.expect(computeRpcMock.listGlobalAddresses(nextOptions)).andReturn(nextResult); @@ -1818,10 +1859,10 @@ public void testListRegionAddresses() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(addressList, AddressInfo.TO_PB_FUNCTION)); EasyMock.expect( - computeRpcMock.listRegionAddresses(REGION_ADDRESS_ID.region(), EMPTY_RPC_OPTIONS)) + computeRpcMock.listRegionAddresses(REGION_ADDRESS_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page
page = compute.listRegionAddresses(REGION_ADDRESS_ID.region()); + Page
page = compute.listRegionAddresses(REGION_ADDRESS_ID.getRegion()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(addressList.toArray(), Iterables.toArray(page.values(), Address.class)); } @@ -1839,16 +1880,17 @@ public void testListRegionAddressesNextPage() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(addressList, AddressInfo.TO_PB_FUNCTION)); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextAddressList, AddressInfo.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextAddressList, AddressInfo.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); EasyMock.expect( - computeRpcMock.listRegionAddresses(REGION_ADDRESS_ID.region(), EMPTY_RPC_OPTIONS)) + computeRpcMock.listRegionAddresses(REGION_ADDRESS_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.expect( - computeRpcMock.listRegionAddresses(REGION_ADDRESS_ID.region(), nextOptions)) + computeRpcMock.listRegionAddresses(REGION_ADDRESS_ID.getRegion(), nextOptions)) .andReturn(nextResult); EasyMock.replay(computeRpcMock); - Page
page = compute.listRegionAddresses(REGION_ADDRESS_ID.region()); + Page
page = compute.listRegionAddresses(REGION_ADDRESS_ID.getRegion()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(addressList.toArray(), Iterables.toArray(page.values(), Address.class)); page = page.nextPage(); @@ -1862,11 +1904,11 @@ public void testListEmptyRegionAddresses() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, addresses); EasyMock.expect( - computeRpcMock.listRegionAddresses(REGION_ADDRESS_ID.region(), EMPTY_RPC_OPTIONS)) + computeRpcMock.listRegionAddresses(REGION_ADDRESS_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); compute = options.service(); - Page
page = compute.listRegionAddresses(REGION_ADDRESS_ID.region()); + Page
page = compute.listRegionAddresses(REGION_ADDRESS_ID.getRegion()); assertNull(page.nextPageCursor()); assertArrayEquals(addresses.toArray(), Iterables.toArray(page.values(), Address.class)); } @@ -1881,10 +1923,10 @@ public void testListRegionAddressesWithOptions() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(addressList, AddressInfo.TO_PB_FUNCTION)); EasyMock.expect( - computeRpcMock.listRegionAddresses(REGION_ADDRESS_ID.region(), ADDRESS_LIST_OPTIONS)) + computeRpcMock.listRegionAddresses(REGION_ADDRESS_ID.getRegion(), ADDRESS_LIST_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page
page = compute.listRegionAddresses(REGION_ADDRESS_ID.region(), + Page
page = compute.listRegionAddresses(REGION_ADDRESS_ID.getRegion(), ADDRESS_LIST_PAGE_SIZE, ADDRESS_LIST_PAGE_TOKEN, ADDRESS_LIST_FILTER); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(addressList.toArray(), Iterables.toArray(page.values(), Address.class)); @@ -1919,7 +1961,8 @@ public void testAggregatedListAddressesNextPage() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(addressList, AddressInfo.TO_PB_FUNCTION)); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextAddressList, AddressInfo.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextAddressList, AddressInfo.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); EasyMock.expect(computeRpcMock.listAddresses(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.expect(computeRpcMock.listAddresses(nextOptions)).andReturn(nextResult); @@ -1970,7 +2013,7 @@ public void testCreateGlobalAddress() { compute = options.service(); AddressId incompleteId = GlobalAddressId.of("address"); Operation operation = - compute.create(GLOBAL_ADDRESS.toBuilder().addressId(incompleteId).build()); + compute.create(GLOBAL_ADDRESS.toBuilder().setAddressId(incompleteId).build()); assertEquals(globalOperation, operation); } @@ -1983,7 +2026,8 @@ public void testCreateGlobalAddressWithOptions() { EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.create(GLOBAL_ADDRESS, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -1993,25 +2037,26 @@ public void testCreateGlobalAddressWithOptions() { @Test public void testCreateRegionAddress() { - EasyMock.expect(computeRpcMock.createRegionAddress(REGION_ADDRESS_ID.region(), + EasyMock.expect(computeRpcMock.createRegionAddress(REGION_ADDRESS_ID.getRegion(), REGION_ADDRESS.toPb(), EMPTY_RPC_OPTIONS)).andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); AddressId incompleteId = RegionAddressId.of("region", "address"); Operation operation = - compute.create(REGION_ADDRESS.toBuilder().addressId(incompleteId).build()); + compute.create(REGION_ADDRESS.toBuilder().setAddressId(incompleteId).build()); assertEquals(regionOperation, operation); } @Test public void testCreateRegionAddressWithOptions() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.createRegionAddress(eq(REGION_ADDRESS_ID.region()), + EasyMock.expect(computeRpcMock.createRegionAddress(eq(REGION_ADDRESS_ID.getRegion()), eq(REGION_ADDRESS.toPb()), capture(capturedOptions))).andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.create(REGION_ADDRESS, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2021,8 +2066,8 @@ public void testCreateRegionAddressWithOptions() { @Test public void testCreateSnapshot() { - EasyMock.expect(computeRpcMock.createSnapshot(DISK_ID.zone(), DISK_ID.disk(), - SNAPSHOT_ID.snapshot(), null, EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); + EasyMock.expect(computeRpcMock.createSnapshot(DISK_ID.getZone(), DISK_ID.getDisk(), + SNAPSHOT_ID.getSnapshot(), null, EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.create(SNAPSHOT); @@ -2032,13 +2077,14 @@ public void testCreateSnapshot() { @Test public void testCreateSnapshotWithOptions() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.createSnapshot(eq(DISK_ID.zone()), eq(DISK_ID.disk()), - eq(SNAPSHOT_ID.snapshot()), EasyMock.isNull(), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.createSnapshot(eq(DISK_ID.getZone()), eq(DISK_ID.getDisk()), + eq(SNAPSHOT_ID.getSnapshot()), EasyMock.isNull(), capture(capturedOptions))) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.create(SNAPSHOT, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2048,32 +2094,33 @@ public void testCreateSnapshotWithOptions() { @Test public void testGetSnapshot() { - EasyMock.expect(computeRpcMock.getSnapshot(SNAPSHOT_ID.snapshot(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getSnapshot(SNAPSHOT_ID.getSnapshot(), EMPTY_RPC_OPTIONS)) .andReturn(SNAPSHOT.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - Snapshot snapshot = compute.getSnapshot(SNAPSHOT_ID.snapshot()); + Snapshot snapshot = compute.getSnapshot(SNAPSHOT_ID.getSnapshot()); assertEquals(new Snapshot(compute, new SnapshotInfo.BuilderImpl(SNAPSHOT)), snapshot); } @Test public void testGetSnapshot_Null() { - EasyMock.expect(computeRpcMock.getSnapshot(SNAPSHOT_ID.snapshot(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getSnapshot(SNAPSHOT_ID.getSnapshot(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); - assertNull(compute.getSnapshot(SNAPSHOT_ID.snapshot())); + assertNull(compute.getSnapshot(SNAPSHOT_ID.getSnapshot())); } @Test public void testGetSnapshotWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.getSnapshot(eq(SNAPSHOT_ID.snapshot()), + EasyMock.expect(computeRpcMock.getSnapshot(eq(SNAPSHOT_ID.getSnapshot()), capture(capturedOptions))).andReturn(SNAPSHOT.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - Snapshot snapshot = compute.getSnapshot(SNAPSHOT_ID.snapshot(), SNAPSHOT_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(SNAPSHOT_OPTION_FIELDS.rpcOption()); + Snapshot snapshot = compute.getSnapshot(SNAPSHOT_ID.getSnapshot(), SNAPSHOT_OPTION_FIELDS); + String selector = + (String) capturedOptions.getValue().get(SNAPSHOT_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2083,22 +2130,23 @@ public void testGetSnapshotWithSelectedFields() { @Test public void testDeleteSnapshot_Operation() { - EasyMock.expect(computeRpcMock.deleteSnapshot(SNAPSHOT_ID.snapshot(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.deleteSnapshot(SNAPSHOT_ID.getSnapshot(), EMPTY_RPC_OPTIONS)) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - assertEquals(globalOperation, compute.deleteSnapshot(SNAPSHOT_ID.snapshot())); + assertEquals(globalOperation, compute.deleteSnapshot(SNAPSHOT_ID.getSnapshot())); } @Test public void testDeleteSnapshotWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.deleteSnapshot(eq(SNAPSHOT_ID.snapshot()), + EasyMock.expect(computeRpcMock.deleteSnapshot(eq(SNAPSHOT_ID.getSnapshot()), capture(capturedOptions))).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.deleteSnapshot(SNAPSHOT_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2108,7 +2156,7 @@ public void testDeleteSnapshotWithSelectedFields_Operation() { @Test public void testDeleteSnapshot_Null() { - EasyMock.expect(computeRpcMock.deleteSnapshot(SNAPSHOT_ID.snapshot(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.deleteSnapshot(SNAPSHOT_ID.getSnapshot(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2144,7 +2192,8 @@ public void testListSnapshotsNextPage() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(snapshotList, SnapshotInfo.TO_PB_FUNCTION)); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextSnapshotList, SnapshotInfo.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextSnapshotList, SnapshotInfo.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); EasyMock.expect(computeRpcMock.listSnapshots(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.expect(computeRpcMock.listSnapshots(nextOptions)).andReturn(nextResult); @@ -2205,7 +2254,8 @@ public void testCreateImageWithOptions() { EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.create(IMAGE, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2216,7 +2266,7 @@ public void testCreateImageWithOptions() { @Test public void testGetImage() { EasyMock.expect( - computeRpcMock.getImage(IMAGE_ID.project(), IMAGE_ID.image(), EMPTY_RPC_OPTIONS)) + computeRpcMock.getImage(IMAGE_ID.getProject(), IMAGE_ID.getImage(), EMPTY_RPC_OPTIONS)) .andReturn(IMAGE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2227,7 +2277,7 @@ public void testGetImage() { @Test public void testGetImage_Null() { EasyMock.expect( - computeRpcMock.getImage(IMAGE_ID.project(), IMAGE_ID.image(), EMPTY_RPC_OPTIONS)) + computeRpcMock.getImage(IMAGE_ID.getProject(), IMAGE_ID.getImage(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2237,12 +2287,12 @@ public void testGetImage_Null() { @Test public void testGetImageWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.getImage(eq(IMAGE_ID.project()), eq(IMAGE_ID.image()), + EasyMock.expect(computeRpcMock.getImage(eq(IMAGE_ID.getProject()), eq(IMAGE_ID.getImage()), capture(capturedOptions))).andReturn(IMAGE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Image image = compute.getImage(IMAGE_ID, IMAGE_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(IMAGE_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(IMAGE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("sourceDisk")); @@ -2254,7 +2304,7 @@ public void testGetImageWithSelectedFields() { @Test public void testDeleteImage_Operation() { - EasyMock.expect(computeRpcMock.deleteImage(IMAGE_ID.project(), IMAGE_ID.image(), + EasyMock.expect(computeRpcMock.deleteImage(IMAGE_ID.getProject(), IMAGE_ID.getImage(), EMPTY_RPC_OPTIONS)).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2264,12 +2314,13 @@ public void testDeleteImage_Operation() { @Test public void testDeleteImageWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.deleteImage(eq(PROJECT), eq(IMAGE_ID.image()), + EasyMock.expect(computeRpcMock.deleteImage(eq(PROJECT), eq(IMAGE_ID.getImage()), capture(capturedOptions))).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.deleteImage(ImageId.of("image"), OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2279,7 +2330,7 @@ public void testDeleteImageWithSelectedFields_Operation() { @Test public void testDeleteImage_Null() { - EasyMock.expect(computeRpcMock.deleteImage(IMAGE_ID.project(), IMAGE_ID.image(), + EasyMock.expect(computeRpcMock.deleteImage(IMAGE_ID.getProject(), IMAGE_ID.getImage(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2288,7 +2339,7 @@ public void testDeleteImage_Null() { @Test public void testDeprecateImage_Operation() { - EasyMock.expect(computeRpcMock.deprecateImage(IMAGE_ID.project(), IMAGE_ID.image(), + EasyMock.expect(computeRpcMock.deprecateImage(IMAGE_ID.getProject(), IMAGE_ID.getImage(), DEPRECATION_STATUS.toPb(), EMPTY_RPC_OPTIONS)).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2298,13 +2349,14 @@ public void testDeprecateImage_Operation() { @Test public void testDeprecateImageWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.deprecateImage(eq(PROJECT), eq(IMAGE_ID.image()), + EasyMock.expect(computeRpcMock.deprecateImage(eq(PROJECT), eq(IMAGE_ID.getImage()), eq(DEPRECATION_STATUS.toPb()), capture(capturedOptions))).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.deprecate(ImageId.of("image"), DEPRECATION_STATUS, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2314,7 +2366,7 @@ public void testDeprecateImageWithSelectedFields_Operation() { @Test public void testDeprecateImage_Null() { - EasyMock.expect(computeRpcMock.deprecateImage(IMAGE_ID.project(), IMAGE_ID.image(), + EasyMock.expect(computeRpcMock.deprecateImage(IMAGE_ID.getProject(), IMAGE_ID.getImage(), DEPRECATION_STATUS.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2350,7 +2402,8 @@ public void testListImagesNextPage() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(imageList, ImageInfo.TO_PB_FUNCTION)); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextImageList, ImageInfo.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextImageList, ImageInfo.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); EasyMock.expect(computeRpcMock.listImages(PROJECT, EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.expect(computeRpcMock.listImages(PROJECT, nextOptions)).andReturn(nextResult); @@ -2441,7 +2494,7 @@ public void testListImagesForProjectWithOptions() { @Test public void testGetDisk() { - EasyMock.expect(computeRpcMock.getDisk(DISK_ID.zone(), DISK_ID.disk(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getDisk(DISK_ID.getZone(), DISK_ID.getDisk(), EMPTY_RPC_OPTIONS)) .andReturn(DISK.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2451,7 +2504,7 @@ public void testGetDisk() { @Test public void testGetDisk_Null() { - EasyMock.expect(computeRpcMock.getDisk(DISK_ID.zone(), DISK_ID.disk(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getDisk(DISK_ID.getZone(), DISK_ID.getDisk(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2461,12 +2514,12 @@ public void testGetDisk_Null() { @Test public void testGetDiskWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.getDisk(eq(DISK_ID.zone()), eq(DISK_ID.disk()), + EasyMock.expect(computeRpcMock.getDisk(eq(DISK_ID.getZone()), eq(DISK_ID.getDisk()), capture(capturedOptions))).andReturn(DISK.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Disk disk = compute.getDisk(DISK_ID, DISK_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(DISK_OPTION_FIELDS.rpcOption()); + String selector = (String) capturedOptions.getValue().get(DISK_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("type")); assertTrue(selector.contains("sourceImage")); @@ -2479,7 +2532,8 @@ public void testGetDiskWithSelectedFields() { @Test public void testDeleteDisk_Operation() { - EasyMock.expect(computeRpcMock.deleteDisk(DISK_ID.zone(), DISK_ID.disk(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.deleteDisk( + DISK_ID.getZone(), DISK_ID.getDisk(), EMPTY_RPC_OPTIONS)) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2489,12 +2543,13 @@ public void testDeleteDisk_Operation() { @Test public void testDeleteDiskWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.deleteDisk(eq(DISK_ID.zone()), eq(DISK_ID.disk()), + EasyMock.expect(computeRpcMock.deleteDisk(eq(DISK_ID.getZone()), eq(DISK_ID.getDisk()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.deleteDisk(DISK_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2504,7 +2559,8 @@ public void testDeleteDiskWithSelectedFields_Operation() { @Test public void testDeleteDisk_Null() { - EasyMock.expect(computeRpcMock.deleteDisk(DISK_ID.zone(), DISK_ID.disk(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.deleteDisk( + DISK_ID.getZone(), DISK_ID.getDisk(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2520,10 +2576,10 @@ public void testListDisks() { new Disk(compute, new DiskInfo.BuilderImpl(DISK))); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(diskList, DiskInfo.TO_PB_FUNCTION)); - EasyMock.expect(computeRpcMock.listDisks(DISK_ID.zone(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listDisks(DISK_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listDisks(DISK_ID.zone()); + Page page = compute.listDisks(DISK_ID.getZone()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(diskList.toArray(), Iterables.toArray(page.values(), Disk.class)); } @@ -2543,10 +2599,11 @@ public void testListDisksNextPage() { ComputeRpc.Tuple> nextResult = ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextDiskList, DiskInfo.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); - EasyMock.expect(computeRpcMock.listDisks(DISK_ID.zone(), EMPTY_RPC_OPTIONS)).andReturn(result); - EasyMock.expect(computeRpcMock.listDisks(DISK_ID.zone(), nextOptions)).andReturn(nextResult); + EasyMock.expect(computeRpcMock.listDisks(DISK_ID.getZone(), EMPTY_RPC_OPTIONS)) + .andReturn(result); + EasyMock.expect(computeRpcMock.listDisks(DISK_ID.getZone(), nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); - Page page = compute.listDisks(DISK_ID.zone()); + Page page = compute.listDisks(DISK_ID.getZone()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(diskList.toArray(), Iterables.toArray(page.values(), Disk.class)); page = page.nextPage(); @@ -2560,10 +2617,10 @@ public void testListEmptyDisks() { ImmutableList disks = ImmutableList.of(); ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, disks); - EasyMock.expect(computeRpcMock.listDisks(DISK_ID.zone(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listDisks(DISK_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listDisks(DISK_ID.zone()); + Page page = compute.listDisks(DISK_ID.getZone()); assertNull(page.nextPageCursor()); assertArrayEquals(disks.toArray(), Iterables.toArray(page.values(), Disk.class)); } @@ -2577,11 +2634,11 @@ public void testListDisksWithOptions() { new Disk(compute, new DiskInfo.BuilderImpl(DISK))); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(diskList, DiskInfo.TO_PB_FUNCTION)); - EasyMock.expect(computeRpcMock.listDisks(DISK_ID.zone(), DISK_LIST_OPTIONS)) + EasyMock.expect(computeRpcMock.listDisks(DISK_ID.getZone(), DISK_LIST_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listDisks(DISK_ID.zone(), DISK_LIST_PAGE_SIZE, DISK_LIST_PAGE_TOKEN, - DISK_LIST_FILTER); + Page page =compute.listDisks( + DISK_ID.getZone(), DISK_LIST_PAGE_SIZE, DISK_LIST_PAGE_TOKEN, DISK_LIST_FILTER); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(diskList.toArray(), Iterables.toArray(page.values(), Disk.class)); } @@ -2660,15 +2717,15 @@ public void testAggregatedListDisksWithOptions() { @Test public void testCreateDisk() { - EasyMock.expect(computeRpcMock.createDisk(DISK_ID.zone(), DISK.toPb(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.createDisk(DISK_ID.getZone(), DISK.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); DiskId diskId = DiskId.of("zone", "disk"); DiskTypeId diskTypeId = DiskTypeId.of("zone", "diskType"); DiskInfo disk = DISK.toBuilder() - .diskId(diskId) - .configuration(StandardDiskConfiguration.of(diskTypeId)) + .setDiskId(diskId) + .setConfiguration(StandardDiskConfiguration.of(diskTypeId)) .build(); Operation operation = compute.create(disk); assertEquals(zoneOperation, operation); @@ -2677,12 +2734,13 @@ public void testCreateDisk() { @Test public void testCreateDiskWithOptions() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.createDisk(eq(DISK_ID.zone()), eq(DISK.toPb()), + EasyMock.expect(computeRpcMock.createDisk(eq(DISK_ID.getZone()), eq(DISK.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.create(DISK, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2692,7 +2750,7 @@ public void testCreateDiskWithOptions() { @Test public void testResizeDisk_Operation() { - EasyMock.expect(computeRpcMock.resizeDisk(DISK_ID.zone(), DISK_ID.disk(), 42L, + EasyMock.expect(computeRpcMock.resizeDisk(DISK_ID.getZone(), DISK_ID.getDisk(), 42L, EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2702,12 +2760,13 @@ public void testResizeDisk_Operation() { @Test public void testResizeDiskWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.resizeDisk(eq(DISK_ID.zone()), eq(DISK_ID.disk()), eq(42L), + EasyMock.expect(computeRpcMock.resizeDisk(eq(DISK_ID.getZone()), eq(DISK_ID.getDisk()), eq(42L), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.resize(DISK_ID, 42L, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2717,7 +2776,7 @@ public void testResizeDiskWithSelectedFields_Operation() { @Test public void testResizeDisk_Null() { - EasyMock.expect(computeRpcMock.resizeDisk(DISK_ID.zone(), DISK_ID.disk(), 42L, + EasyMock.expect(computeRpcMock.resizeDisk(DISK_ID.getZone(), DISK_ID.getDisk(), 42L, EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2726,8 +2785,9 @@ public void testResizeDisk_Null() { @Test public void testGetSubnetwork() { - EasyMock.expect(computeRpcMock.getSubnetwork(SUBNETWORK_ID.region(), SUBNETWORK_ID.subnetwork(), - EMPTY_RPC_OPTIONS)).andReturn(SUBNETWORK.toPb()); + EasyMock.expect(computeRpcMock.getSubnetwork( + SUBNETWORK_ID.getRegion(), SUBNETWORK_ID.getSubnetwork(), EMPTY_RPC_OPTIONS)) + .andReturn(SUBNETWORK.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Subnetwork subnetwork = compute.getSubnetwork(SUBNETWORK_ID); @@ -2736,8 +2796,9 @@ public void testGetSubnetwork() { @Test public void testGetSubnetwork_Null() { - EasyMock.expect(computeRpcMock.getSubnetwork(SUBNETWORK_ID.region(), SUBNETWORK_ID.subnetwork(), - EMPTY_RPC_OPTIONS)).andReturn(null); + EasyMock.expect(computeRpcMock.getSubnetwork( + SUBNETWORK_ID.getRegion(), SUBNETWORK_ID.getSubnetwork(), EMPTY_RPC_OPTIONS)) + .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); assertNull(compute.getSubnetwork(SUBNETWORK_ID)); @@ -2746,12 +2807,13 @@ public void testGetSubnetwork_Null() { @Test public void testGetSubnetworkWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.getSubnetwork(eq(SUBNETWORK_ID.region()), - eq(SUBNETWORK_ID.subnetwork()), capture(capturedOptions))).andReturn(SUBNETWORK.toPb()); + EasyMock.expect(computeRpcMock.getSubnetwork(eq(SUBNETWORK_ID.getRegion()), + eq(SUBNETWORK_ID.getSubnetwork()), capture(capturedOptions))).andReturn(SUBNETWORK.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Subnetwork subnetwork = compute.getSubnetwork(SUBNETWORK_ID, SUBNETWORK_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(SUBNETWORK_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(SUBNETWORK_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2761,8 +2823,8 @@ public void testGetSubnetworkWithSelectedFields() { @Test public void testDeleteSubnetwork_Operation() { - EasyMock.expect(computeRpcMock.deleteSubnetwork(SUBNETWORK_ID.region(), - SUBNETWORK_ID.subnetwork(), EMPTY_RPC_OPTIONS)).andReturn(regionOperation.toPb()); + EasyMock.expect(computeRpcMock.deleteSubnetwork(SUBNETWORK_ID.getRegion(), + SUBNETWORK_ID.getSubnetwork(), EMPTY_RPC_OPTIONS)).andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); assertEquals(regionOperation, compute.deleteSubnetwork(SUBNETWORK_ID)); @@ -2771,13 +2833,14 @@ public void testDeleteSubnetwork_Operation() { @Test public void testDeleteSubnetworkWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.deleteSubnetwork(eq(SUBNETWORK_ID.region()), - eq(SUBNETWORK_ID.subnetwork()), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.deleteSubnetwork(eq(SUBNETWORK_ID.getRegion()), + eq(SUBNETWORK_ID.getSubnetwork()), capture(capturedOptions))) .andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.deleteSubnetwork(SUBNETWORK_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2787,8 +2850,8 @@ public void testDeleteSubnetworkWithSelectedFields_Operation() { @Test public void testDeleteSubnetwork_Null() { - EasyMock.expect(computeRpcMock.deleteSubnetwork(SUBNETWORK_ID.region(), - SUBNETWORK_ID.subnetwork(), EMPTY_RPC_OPTIONS)).andReturn(null); + EasyMock.expect(computeRpcMock.deleteSubnetwork(SUBNETWORK_ID.getRegion(), + SUBNETWORK_ID.getSubnetwork(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); assertNull(compute.deleteSubnetwork(SUBNETWORK_ID)); @@ -2802,11 +2865,12 @@ public void testListSubnetworks() { new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK)), new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK))); ComputeRpc.Tuple> result = - ComputeRpc.Tuple.of(cursor, Iterables.transform(subnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); - EasyMock.expect(computeRpcMock.listSubnetworks(SUBNETWORK_ID.region(), EMPTY_RPC_OPTIONS)) + ComputeRpc.Tuple.of(cursor, + Iterables.transform(subnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); + EasyMock.expect(computeRpcMock.listSubnetworks(SUBNETWORK_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listSubnetworks(SUBNETWORK_ID.region()); + Page page = compute.listSubnetworks(SUBNETWORK_ID.getRegion()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(subnetworkList.toArray(), Iterables.toArray(page.values(), Subnetwork.class)); } @@ -2822,17 +2886,18 @@ public void testListSubnetworksNextPage() { ImmutableList nextSubnetworkList = ImmutableList.of( new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK))); ComputeRpc.Tuple> result = - ComputeRpc.Tuple.of(cursor, Iterables.transform(subnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); - ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, + ComputeRpc.Tuple.of(cursor, + Iterables.transform(subnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); + ComputeRpc.Tuple> + nextResult = ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextSubnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); - EasyMock.expect(computeRpcMock.listSubnetworks(SUBNETWORK_ID.region(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listSubnetworks(SUBNETWORK_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(result); - EasyMock.expect(computeRpcMock.listSubnetworks(SUBNETWORK_ID.region(), nextOptions)) + EasyMock.expect(computeRpcMock.listSubnetworks(SUBNETWORK_ID.getRegion(), nextOptions)) .andReturn(nextResult); EasyMock.replay(computeRpcMock); - Page page = compute.listSubnetworks(SUBNETWORK_ID.region()); + Page page = compute.listSubnetworks(SUBNETWORK_ID.getRegion()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(subnetworkList.toArray(), Iterables.toArray(page.values(), Subnetwork.class)); page = page.nextPage(); @@ -2849,10 +2914,10 @@ public void testListEmptySubnetworks() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, subnetworks); - EasyMock.expect(computeRpcMock.listSubnetworks(SUBNETWORK_ID.region(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listSubnetworks(SUBNETWORK_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listSubnetworks(SUBNETWORK_ID.region()); + Page page = compute.listSubnetworks(SUBNETWORK_ID.getRegion()); assertNull(page.nextPageCursor()); assertArrayEquals(subnetworks.toArray(), Iterables.toArray(page.values(), Subnetwork.class)); } @@ -2865,11 +2930,13 @@ public void testListSubnetworksWithOptions() { new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK)), new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK))); ComputeRpc.Tuple> result = - ComputeRpc.Tuple.of(cursor, Iterables.transform(subnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); - EasyMock.expect(computeRpcMock.listSubnetworks(SUBNETWORK_ID.region(), SUBNETWORK_LIST_OPTIONS)) + ComputeRpc.Tuple.of(cursor, + Iterables.transform(subnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); + EasyMock.expect(computeRpcMock.listSubnetworks( + SUBNETWORK_ID.getRegion(), SUBNETWORK_LIST_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listSubnetworks(SUBNETWORK_ID.region(), + Page page = compute.listSubnetworks(SUBNETWORK_ID.getRegion(), SUBNETWORK_LIST_PAGE_SIZE, SUBNETWORK_LIST_PAGE_TOKEN, SUBNETWORK_LIST_FILTER); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(subnetworkList.toArray(), Iterables.toArray(page.values(), Subnetwork.class)); @@ -2883,7 +2950,8 @@ public void testAggregatedListSubnetworks() { new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK)), new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK))); ComputeRpc.Tuple> result = - ComputeRpc.Tuple.of(cursor, Iterables.transform(subnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(cursor, + Iterables.transform(subnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); EasyMock.expect(computeRpcMock.listSubnetworks(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listSubnetworks(); @@ -2902,9 +2970,10 @@ public void testAggregatedListSubnetworksNextPage() { ImmutableList nextSubnetworkList = ImmutableList.of( new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK))); ComputeRpc.Tuple> result = - ComputeRpc.Tuple.of(cursor, Iterables.transform(subnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); - ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, + ComputeRpc.Tuple.of(cursor, + Iterables.transform(subnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); + ComputeRpc.Tuple> + nextResult = ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextSubnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); EasyMock.expect(computeRpcMock.listSubnetworks(EMPTY_RPC_OPTIONS)).andReturn(result); @@ -2942,7 +3011,8 @@ public void testAggregatedListSubnetworksWithOptions() { new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK)), new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK))); ComputeRpc.Tuple> result = - ComputeRpc.Tuple.of(cursor, Iterables.transform(subnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(cursor, + Iterables.transform(subnetworkList, SubnetworkInfo.TO_PB_FUNCTION)); EasyMock.expect(computeRpcMock.listSubnetworks(SUBNETWORK_LIST_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listSubnetworks(SUBNETWORK_AGGREGATED_LIST_PAGE_SIZE, @@ -2953,7 +3023,7 @@ public void testAggregatedListSubnetworksWithOptions() { @Test public void testCreateSubnetwork() { - EasyMock.expect(computeRpcMock.createSubnetwork(SUBNETWORK_ID.region(), SUBNETWORK.toPb(), + EasyMock.expect(computeRpcMock.createSubnetwork(SUBNETWORK_ID.getRegion(), SUBNETWORK.toPb(), EMPTY_RPC_OPTIONS)).andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -2967,12 +3037,13 @@ public void testCreateSubnetwork() { @Test public void testCreateSubnetworkWithOptions() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.createSubnetwork(eq(SUBNETWORK_ID.region()), + EasyMock.expect(computeRpcMock.createSubnetwork(eq(SUBNETWORK_ID.getRegion()), eq(SUBNETWORK.toPb()), capture(capturedOptions))).andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.create(SUBNETWORK, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -2982,32 +3053,33 @@ public void testCreateSubnetworkWithOptions() { @Test public void testGetNetwork() { - EasyMock.expect(computeRpcMock.getNetwork(NETWORK_ID.network(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getNetwork(NETWORK_ID.getNetwork(), EMPTY_RPC_OPTIONS)) .andReturn(NETWORK.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - Network network = compute.getNetwork(NETWORK_ID.network()); + Network network = compute.getNetwork(NETWORK_ID.getNetwork()); assertEquals(new Network(compute, new NetworkInfo.BuilderImpl(NETWORK)), network); } @Test public void testGetNetwork_Null() { - EasyMock.expect(computeRpcMock.getNetwork(NETWORK_ID.network(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getNetwork(NETWORK_ID.getNetwork(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); - assertNull(compute.getNetwork(NETWORK_ID.network())); + assertNull(compute.getNetwork(NETWORK_ID.getNetwork())); } @Test public void testGetNetworkWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.getNetwork(eq(NETWORK_ID.network()), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.getNetwork(eq( + NETWORK_ID.getNetwork()), capture(capturedOptions))) .andReturn(NETWORK.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); - Network network = compute.getNetwork(NETWORK_ID.network(), NETWORK_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(NETWORK_OPTION_FIELDS.rpcOption()); + Network network = compute.getNetwork(NETWORK_ID.getNetwork(), NETWORK_OPTION_FIELDS); + String selector = (String) capturedOptions.getValue().get(NETWORK_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3019,7 +3091,7 @@ public void testGetNetworkWithSelectedFields() { @Test public void testDeleteNetwork_Operation() { - EasyMock.expect(computeRpcMock.deleteNetwork(NETWORK_ID.network(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.deleteNetwork(NETWORK_ID.getNetwork(), EMPTY_RPC_OPTIONS)) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3029,12 +3101,13 @@ public void testDeleteNetwork_Operation() { @Test public void testDeleteNetworkWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.deleteNetwork(eq(NETWORK_ID.network()), + EasyMock.expect(computeRpcMock.deleteNetwork(eq(NETWORK_ID.getNetwork()), capture(capturedOptions))).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.deleteNetwork(NETWORK_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3044,7 +3117,7 @@ public void testDeleteNetworkWithSelectedFields_Operation() { @Test public void testDeleteNetwork_Null() { - EasyMock.expect(computeRpcMock.deleteNetwork(NETWORK_ID.network(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.deleteNetwork(NETWORK_ID.getNetwork(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3080,7 +3153,8 @@ public void testListNetworksNextPage() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(networkList, NetworkInfo.TO_PB_FUNCTION)); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextNetworkList, NetworkInfo.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextNetworkList, NetworkInfo.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); EasyMock.expect(computeRpcMock.listNetworks(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.expect(computeRpcMock.listNetworks(nextOptions)).andReturn(nextResult); @@ -3143,7 +3217,8 @@ public void testCreateNetworkWithOptions() { EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.create(NETWORK, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3153,7 +3228,7 @@ public void testCreateNetworkWithOptions() { @Test public void testGetInstance() { - EasyMock.expect(computeRpcMock.getInstance(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.getInstance(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(INSTANCE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3163,7 +3238,7 @@ public void testGetInstance() { @Test public void testGetInstance_Null() { - EasyMock.expect(computeRpcMock.getInstance(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.getInstance(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3173,12 +3248,14 @@ public void testGetInstance_Null() { @Test public void testGetInstanceWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.getInstance(eq(INSTANCE_ID.zone()), eq(INSTANCE_ID.instance()), - capture(capturedOptions))).andReturn(INSTANCE.toPb()); + EasyMock.expect(computeRpcMock.getInstance( + eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), capture(capturedOptions))) + .andReturn(INSTANCE.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Instance instance = compute.getInstance(INSTANCE_ID, INSTANCE_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(INSTANCE_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(INSTANCE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3188,7 +3265,7 @@ public void testGetInstanceWithSelectedFields() { @Test public void testDeleteInstance_Operation() { - EasyMock.expect(computeRpcMock.deleteInstance(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.deleteInstance(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3198,12 +3275,13 @@ public void testDeleteInstance_Operation() { @Test public void testDeleteInstanceWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.deleteInstance(eq(INSTANCE_ID.zone()), - eq(INSTANCE_ID.instance()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); + EasyMock.expect(computeRpcMock.deleteInstance(eq(INSTANCE_ID.getZone()), + eq(INSTANCE_ID.getInstance()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.deleteInstance(INSTANCE_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3213,7 +3291,7 @@ public void testDeleteInstanceWithSelectedFields_Operation() { @Test public void testDeleteInstance_Null() { - EasyMock.expect(computeRpcMock.deleteInstance(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.deleteInstance(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3229,10 +3307,10 @@ public void testListInstances() { new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE))); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(instanceList, InstanceInfo.TO_PB_FUNCTION)); - EasyMock.expect(computeRpcMock.listInstances(INSTANCE_ID.zone(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listInstances(INSTANCE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listInstances(INSTANCE_ID.zone()); + Page page = compute.listInstances(INSTANCE_ID.getZone()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.values(), Instance.class)); } @@ -3250,14 +3328,15 @@ public void testListInstancesNextPage() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(instanceList, InstanceInfo.TO_PB_FUNCTION)); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextInstanceList, InstanceInfo.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextInstanceList, InstanceInfo.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); - EasyMock.expect(computeRpcMock.listInstances(INSTANCE_ID.zone(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listInstances(INSTANCE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); - EasyMock.expect(computeRpcMock.listInstances(INSTANCE_ID.zone(), nextOptions)) + EasyMock.expect(computeRpcMock.listInstances(INSTANCE_ID.getZone(), nextOptions)) .andReturn(nextResult); EasyMock.replay(computeRpcMock); - Page page = compute.listInstances(INSTANCE_ID.zone()); + Page page = compute.listInstances(INSTANCE_ID.getZone()); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.values(), Instance.class)); page = page.nextPage(); @@ -3271,10 +3350,10 @@ public void testListEmptyInstances() { ImmutableList instances = ImmutableList.of(); ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, instances); - EasyMock.expect(computeRpcMock.listInstances(INSTANCE_ID.zone(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.listInstances(INSTANCE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listInstances(INSTANCE_ID.zone()); + Page page = compute.listInstances(INSTANCE_ID.getZone()); assertNull(page.nextPageCursor()); assertArrayEquals(instances.toArray(), Iterables.toArray(page.values(), Instance.class)); } @@ -3288,10 +3367,10 @@ public void testListInstancesWithOptions() { new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE))); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(instanceList, InstanceInfo.TO_PB_FUNCTION)); - EasyMock.expect(computeRpcMock.listInstances(INSTANCE_ID.zone(), INSTANCE_LIST_OPTIONS)) + EasyMock.expect(computeRpcMock.listInstances(INSTANCE_ID.getZone(), INSTANCE_LIST_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - Page page = compute.listInstances(INSTANCE_ID.zone(), INSTANCE_LIST_PAGE_SIZE, + Page page = compute.listInstances(INSTANCE_ID.getZone(), INSTANCE_LIST_PAGE_SIZE, INSTANCE_LIST_PAGE_TOKEN, INSTANCE_LIST_FILTER); assertEquals(cursor, page.nextPageCursor()); assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.values(), Instance.class)); @@ -3326,7 +3405,8 @@ public void testAggregatedListInstancesNextPage() { ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(instanceList, InstanceInfo.TO_PB_FUNCTION)); ComputeRpc.Tuple> nextResult = - ComputeRpc.Tuple.of(nextCursor, Iterables.transform(nextInstanceList, InstanceInfo.TO_PB_FUNCTION)); + ComputeRpc.Tuple.of(nextCursor, + Iterables.transform(nextInstanceList, InstanceInfo.TO_PB_FUNCTION)); Map nextOptions = ImmutableMap.of(ComputeRpc.Option.PAGE_TOKEN, cursor); EasyMock.expect(computeRpcMock.listInstances(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.expect(computeRpcMock.listInstances(nextOptions)).andReturn(nextResult); @@ -3372,7 +3452,7 @@ public void testAggregatedListInstancesWithOptions() { @Test public void testCreateInstance() { - EasyMock.expect(computeRpcMock.createInstance(INSTANCE_ID.zone(), INSTANCE.toPb(), + EasyMock.expect(computeRpcMock.createInstance(INSTANCE_ID.getZone(), INSTANCE.toPb(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3386,12 +3466,13 @@ public void testCreateInstance() { @Test public void testCreateInstanceWithOptions() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.createInstance(eq(INSTANCE_ID.zone()), eq(INSTANCE.toPb()), + EasyMock.expect(computeRpcMock.createInstance(eq(INSTANCE_ID.getZone()), eq(INSTANCE.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.create(INSTANCE, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3402,7 +3483,7 @@ public void testCreateInstanceWithOptions() { @Test public void testAddAccessConfig_Operation() { AccessConfig accessConfig = AccessConfig.of("192.168.1.1"); - EasyMock.expect(computeRpcMock.addAccessConfig(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.addAccessConfig(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), "networkInterface", accessConfig.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); @@ -3415,14 +3496,15 @@ public void testAddAccessConfig_Operation() { public void testAddAccessConfigWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); AccessConfig accessConfig = AccessConfig.of("192.168.1.1"); - EasyMock.expect(computeRpcMock.addAccessConfig(eq(INSTANCE_ID.zone()), - eq(INSTANCE_ID.instance()), eq("networkInterface"), eq(accessConfig.toPb()), + EasyMock.expect(computeRpcMock.addAccessConfig(eq(INSTANCE_ID.getZone()), + eq(INSTANCE_ID.getInstance()), eq("networkInterface"), eq(accessConfig.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.addAccessConfig(INSTANCE_ID, "networkInterface", accessConfig, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3433,7 +3515,7 @@ public void testAddAccessConfigWithSelectedFields_Operation() { @Test public void testAddAccessConfig_Null() { AccessConfig accessConfig = AccessConfig.of("192.168.1.1"); - EasyMock.expect(computeRpcMock.addAccessConfig(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.addAccessConfig(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), "networkInterface", accessConfig.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3443,7 +3525,7 @@ public void testAddAccessConfig_Null() { @Test public void testAttachDisk_Operation() { AttachedDisk attachedDisk = AttachedDisk.of(PERSISTENT_DISK_CONFIGURATION); - EasyMock.expect(computeRpcMock.attachDisk(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.attachDisk(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), attachedDisk.toPb(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3454,13 +3536,15 @@ public void testAttachDisk_Operation() { public void testAttachDiskWithSelectedFields_Operation() { AttachedDisk attachedDisk = AttachedDisk.of(PERSISTENT_DISK_CONFIGURATION); Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.attachDisk(eq(INSTANCE_ID.zone()), eq(INSTANCE_ID.instance()), - eq(attachedDisk.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); + EasyMock.expect(computeRpcMock.attachDisk( + eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), eq(attachedDisk.toPb()), + capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.attachDisk(INSTANCE_ID, PERSISTENT_DISK_CONFIGURATION, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3471,7 +3555,7 @@ public void testAttachDiskWithSelectedFields_Operation() { @Test public void testAttachDisk_Null() { AttachedDisk attachedDisk = AttachedDisk.of(PERSISTENT_DISK_CONFIGURATION); - EasyMock.expect(computeRpcMock.attachDisk(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.attachDisk(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), attachedDisk.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3481,7 +3565,7 @@ public void testAttachDisk_Null() { @Test public void testAttachDiskName_Operation() { AttachedDisk attachedDisk = AttachedDisk.of("dev0", PERSISTENT_DISK_CONFIGURATION); - EasyMock.expect(computeRpcMock.attachDisk(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.attachDisk(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), attachedDisk.toPb(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3493,13 +3577,15 @@ public void testAttachDiskName_Operation() { public void testAttachDiskNameWithSelectedFields_Operation() { AttachedDisk attachedDisk = AttachedDisk.of("dev0", PERSISTENT_DISK_CONFIGURATION); Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.attachDisk(eq(INSTANCE_ID.zone()), eq(INSTANCE_ID.instance()), - eq(attachedDisk.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); + EasyMock.expect(computeRpcMock.attachDisk( + eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), eq(attachedDisk.toPb()), + capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.attachDisk(INSTANCE_ID, "dev0", PERSISTENT_DISK_CONFIGURATION, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3510,7 +3596,7 @@ public void testAttachDiskNameWithSelectedFields_Operation() { @Test public void testAttachDiskName_Null() { AttachedDisk attachedDisk = AttachedDisk.of("dev0", PERSISTENT_DISK_CONFIGURATION); - EasyMock.expect(computeRpcMock.attachDisk(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.attachDisk(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), attachedDisk.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3519,8 +3605,9 @@ public void testAttachDiskName_Null() { @Test public void testDeleteAccessConfig_Operation() { - EasyMock.expect(computeRpcMock.deleteAccessConfig(INSTANCE_ID.zone(), INSTANCE_ID.instance(), - "networkInterface", "accessConfig", EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); + EasyMock.expect(computeRpcMock.deleteAccessConfig(INSTANCE_ID.getZone(), + INSTANCE_ID.getInstance(), "networkInterface", "accessConfig", EMPTY_RPC_OPTIONS)) + .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); assertEquals(zoneOperation, @@ -3530,14 +3617,15 @@ public void testDeleteAccessConfig_Operation() { @Test public void testDeleteAccessConfigWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.deleteAccessConfig(eq(INSTANCE_ID.zone()), - eq(INSTANCE_ID.instance()), eq("networkInterface"), eq("accessConfig"), + EasyMock.expect(computeRpcMock.deleteAccessConfig(eq(INSTANCE_ID.getZone()), + eq(INSTANCE_ID.getInstance()), eq("networkInterface"), eq("accessConfig"), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.deleteAccessConfig(INSTANCE_ID, "networkInterface", "accessConfig", OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3547,8 +3635,9 @@ public void testDeleteAccessConfigWithSelectedFields_Operation() { @Test public void testDeleteAccessConfig_Null() { - EasyMock.expect(computeRpcMock.deleteAccessConfig(INSTANCE_ID.zone(), INSTANCE_ID.instance(), - "networkInterface", "accessConfig", EMPTY_RPC_OPTIONS)).andReturn(null); + EasyMock.expect(computeRpcMock.deleteAccessConfig(INSTANCE_ID.getZone(), + INSTANCE_ID.getInstance(), "networkInterface", "accessConfig", EMPTY_RPC_OPTIONS)) + .andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); assertNull(compute.deleteAccessConfig(INSTANCE_ID, "networkInterface", "accessConfig")); @@ -3556,7 +3645,7 @@ public void testDeleteAccessConfig_Null() { @Test public void testDetachDisk_Operation() { - EasyMock.expect(computeRpcMock.detachDisk(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.detachDisk(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), "device", EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3566,13 +3655,14 @@ public void testDetachDisk_Operation() { @Test public void testDetachDiskWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.detachDisk(eq(INSTANCE_ID.zone()), - eq(INSTANCE_ID.instance()), eq("device"), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.detachDisk(eq(INSTANCE_ID.getZone()), + eq(INSTANCE_ID.getInstance()), eq("device"), capture(capturedOptions))) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.detachDisk(INSTANCE_ID, "device", OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3582,8 +3672,8 @@ public void testDetachDiskWithSelectedFields_Operation() { @Test public void testDetachDisk_Null() { - EasyMock.expect(computeRpcMock.detachDisk(INSTANCE_ID.zone(), INSTANCE_ID.instance(), "device", - EMPTY_RPC_OPTIONS)).andReturn(null); + EasyMock.expect(computeRpcMock.detachDisk(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), + "device", EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); assertNull(compute.detachDisk(INSTANCE_ID, "device")); @@ -3592,8 +3682,8 @@ public void testDetachDisk_Null() { @Test public void testSerialPortOutputFromPort() { String output = "output"; - EasyMock.expect(computeRpcMock.getSerialPortOutput(INSTANCE_ID.zone(), INSTANCE_ID.instance(), - 2, EMPTY_RPC_OPTIONS)).andReturn(output); + EasyMock.expect(computeRpcMock.getSerialPortOutput(INSTANCE_ID.getZone(), + INSTANCE_ID.getInstance(), 2, EMPTY_RPC_OPTIONS)).andReturn(output); EasyMock.replay(computeRpcMock); compute = options.service(); assertEquals(output, compute.getSerialPortOutput(INSTANCE_ID, 2)); @@ -3602,8 +3692,8 @@ public void testSerialPortOutputFromPort() { @Test public void testSerialPortOutputDefault() { String output = "output"; - EasyMock.expect(computeRpcMock.getSerialPortOutput(INSTANCE_ID.zone(), INSTANCE_ID.instance(), - null, EMPTY_RPC_OPTIONS)).andReturn(output); + EasyMock.expect(computeRpcMock.getSerialPortOutput(INSTANCE_ID.getZone(), + INSTANCE_ID.getInstance(), null, EMPTY_RPC_OPTIONS)).andReturn(output); EasyMock.replay(computeRpcMock); compute = options.service(); assertEquals(output, compute.getSerialPortOutput(INSTANCE_ID)); @@ -3611,8 +3701,8 @@ public void testSerialPortOutputDefault() { @Test public void testSerialPortOutputFromPort_Null() { - EasyMock.expect(computeRpcMock.getSerialPortOutput(INSTANCE_ID.zone(), INSTANCE_ID.instance(), - 2, EMPTY_RPC_OPTIONS)).andReturn(null); + EasyMock.expect(computeRpcMock.getSerialPortOutput(INSTANCE_ID.getZone(), + INSTANCE_ID.getInstance(), 2, EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); assertNull(compute.getSerialPortOutput(INSTANCE_ID, 2)); @@ -3620,8 +3710,8 @@ public void testSerialPortOutputFromPort_Null() { @Test public void testSerialPortOutputDefault_Null() { - EasyMock.expect(computeRpcMock.getSerialPortOutput(INSTANCE_ID.zone(), INSTANCE_ID.instance(), - null, EMPTY_RPC_OPTIONS)).andReturn(null); + EasyMock.expect(computeRpcMock.getSerialPortOutput(INSTANCE_ID.getZone(), + INSTANCE_ID.getInstance(), null, EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); assertNull(compute.getSerialPortOutput(INSTANCE_ID)); @@ -3629,7 +3719,7 @@ public void testSerialPortOutputDefault_Null() { @Test public void testResetInstance_Operation() { - EasyMock.expect(computeRpcMock.reset(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.reset(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3639,12 +3729,13 @@ public void testResetInstance_Operation() { @Test public void testResetInstanceWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.reset(eq(INSTANCE_ID.zone()), eq(INSTANCE_ID.instance()), + EasyMock.expect(computeRpcMock.reset(eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.reset(INSTANCE_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3654,7 +3745,7 @@ public void testResetInstanceWithSelectedFields_Operation() { @Test public void testResetInstance_Null() { - EasyMock.expect(computeRpcMock.reset(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.reset(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3663,8 +3754,9 @@ public void testResetInstance_Null() { @Test public void testSetDiskAutodelete_Operation() { - EasyMock.expect(computeRpcMock.setDiskAutoDelete(INSTANCE_ID.zone(), INSTANCE_ID.instance(), - "device", true, EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); + EasyMock.expect(computeRpcMock.setDiskAutoDelete(INSTANCE_ID.getZone(), + INSTANCE_ID.getInstance(), "device", true, EMPTY_RPC_OPTIONS)) + .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); assertEquals(zoneOperation, compute.setDiskAutoDelete(INSTANCE_ID, "device", true)); @@ -3673,14 +3765,15 @@ public void testSetDiskAutodelete_Operation() { @Test public void testSetDiskAutodeleteWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.setDiskAutoDelete(eq(INSTANCE_ID.zone()), - eq(INSTANCE_ID.instance()), eq("device"), eq(true), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.setDiskAutoDelete(eq(INSTANCE_ID.getZone()), + eq(INSTANCE_ID.getInstance()), eq("device"), eq(true), capture(capturedOptions))) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.setDiskAutoDelete(INSTANCE_ID, "device", true, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3690,8 +3783,8 @@ public void testSetDiskAutodeleteWithSelectedFields_Operation() { @Test public void testSetDiskAutodelete_Null() { - EasyMock.expect(computeRpcMock.setDiskAutoDelete(INSTANCE_ID.zone(), INSTANCE_ID.instance(), - "device", false, EMPTY_RPC_OPTIONS)).andReturn(null); + EasyMock.expect(computeRpcMock.setDiskAutoDelete(INSTANCE_ID.getZone(), + INSTANCE_ID.getInstance(), "device", false, EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); assertNull(compute.setDiskAutoDelete(INSTANCE_ID, "device", false)); @@ -3699,8 +3792,8 @@ public void testSetDiskAutodelete_Null() { @Test public void testSetMachineType_Operation() { - EasyMock.expect(computeRpcMock.setMachineType(INSTANCE_ID.zone(), INSTANCE_ID.instance(), - MACHINE_TYPE_ID.selfLink(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); + EasyMock.expect(computeRpcMock.setMachineType(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), + MACHINE_TYPE_ID.getSelfLink(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); assertEquals(zoneOperation, @@ -3710,14 +3803,15 @@ public void testSetMachineType_Operation() { @Test public void testSetMachineTypeWithOptions_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.setMachineType(eq(INSTANCE_ID.zone()), - eq(INSTANCE_ID.instance()), eq(MACHINE_TYPE_ID.selfLink()), capture(capturedOptions))) + EasyMock.expect(computeRpcMock.setMachineType(eq(INSTANCE_ID.getZone()), + eq(INSTANCE_ID.getInstance()), eq(MACHINE_TYPE_ID.getSelfLink()), capture(capturedOptions))) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.setMachineType(INSTANCE_ID, MachineTypeId.of("zone", "type"), OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3727,8 +3821,8 @@ public void testSetMachineTypeWithOptions_Operation() { @Test public void testSetMachineType_Null() { - EasyMock.expect(computeRpcMock.setMachineType(INSTANCE_ID.zone(), INSTANCE_ID.instance(), - MACHINE_TYPE_ID.selfLink(), EMPTY_RPC_OPTIONS)).andReturn(null); + EasyMock.expect(computeRpcMock.setMachineType(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), + MACHINE_TYPE_ID.getSelfLink(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); assertNull(compute.setMachineType(INSTANCE_ID, MachineTypeId.of("zone", "type"))); @@ -3736,11 +3830,11 @@ public void testSetMachineType_Null() { @Test public void testSetMetadata_Operation() { - Metadata metadata = Metadata.builder() + Metadata metadata = Metadata.newBuilder() .add("key", "value") - .fingerprint("fingerprint") + .setFingerprint("fingerprint") .build(); - EasyMock.expect(computeRpcMock.setMetadata(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.setMetadata(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), metadata.toPb(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3750,16 +3844,18 @@ public void testSetMetadata_Operation() { @Test public void testSetMetadataWithOptions_Operation() { Capture> capturedOptions = Capture.newInstance(); - Metadata metadata = Metadata.builder() + Metadata metadata = Metadata.newBuilder() .add("key", "value") - .fingerprint("fingerprint") + .setFingerprint("fingerprint") .build(); - EasyMock.expect(computeRpcMock.setMetadata(eq(INSTANCE_ID.zone()), eq(INSTANCE_ID.instance()), - eq(metadata.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); + EasyMock.expect(computeRpcMock.setMetadata(eq(INSTANCE_ID.getZone()), + eq(INSTANCE_ID.getInstance()), eq(metadata.toPb()), capture(capturedOptions))) + .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.setMetadata(INSTANCE_ID, metadata, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3769,11 +3865,11 @@ public void testSetMetadataWithOptions_Operation() { @Test public void testSetMetadata_Null() { - Metadata metadata = Metadata.builder() + Metadata metadata = Metadata.newBuilder() .add("key", "value") - .fingerprint("fingerprint") + .setFingerprint("fingerprint") .build(); - EasyMock.expect(computeRpcMock.setMetadata(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.setMetadata(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), metadata.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3784,7 +3880,7 @@ public void testSetMetadata_Null() { public void testSetSchedulingOptions_Operation() { SchedulingOptions schedulingOptions = SchedulingOptions.standard(true, SchedulingOptions.Maintenance.MIGRATE); - EasyMock.expect(computeRpcMock.setScheduling(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.setScheduling(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), schedulingOptions.toPb(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3796,13 +3892,15 @@ public void testSetSchedulingOptionsWithOptions_Operation() { Capture> capturedOptions = Capture.newInstance(); SchedulingOptions schedulingOptions = SchedulingOptions.standard(true, SchedulingOptions.Maintenance.MIGRATE); - EasyMock.expect(computeRpcMock.setScheduling(eq(INSTANCE_ID.zone()), eq(INSTANCE_ID.instance()), - eq(schedulingOptions.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); + EasyMock.expect(computeRpcMock.setScheduling(eq(INSTANCE_ID.getZone()), + eq(INSTANCE_ID.getInstance()), eq(schedulingOptions.toPb()), capture(capturedOptions))) + .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.setSchedulingOptions(INSTANCE_ID, schedulingOptions, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3814,7 +3912,7 @@ public void testSetSchedulingOptionsWithOptions_Operation() { public void testSetSchedulingOptions_Null() { SchedulingOptions schedulingOptions = SchedulingOptions.standard(true, SchedulingOptions.Maintenance.MIGRATE); - EasyMock.expect(computeRpcMock.setScheduling(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.setScheduling(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), schedulingOptions.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3824,8 +3922,8 @@ public void testSetSchedulingOptions_Null() { @Test public void testTags_Operation() { Tags tags = Tags.of("tag1", "tag2"); - EasyMock.expect(computeRpcMock.setTags(INSTANCE_ID.zone(), INSTANCE_ID.instance(), tags.toPb(), - EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); + EasyMock.expect(computeRpcMock.setTags(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), + tags.toPb(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); assertEquals(zoneOperation, compute.setTags(INSTANCE_ID, tags)); @@ -3835,12 +3933,13 @@ public void testTags_Operation() { public void testSetTagsWithOptions_Operation() { Tags tags = Tags.of("tag1", "tag2"); Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.setTags(eq(INSTANCE_ID.zone()), eq(INSTANCE_ID.instance()), + EasyMock.expect(computeRpcMock.setTags(eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), eq(tags.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.setTags(INSTANCE_ID, tags, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3851,8 +3950,8 @@ public void testSetTagsWithOptions_Operation() { @Test public void testSetTags_Null() { Tags tags = Tags.of("tag1", "tag2"); - EasyMock.expect(computeRpcMock.setTags(INSTANCE_ID.zone(), INSTANCE_ID.instance(), tags.toPb(), - EMPTY_RPC_OPTIONS)).andReturn(null); + EasyMock.expect(computeRpcMock.setTags(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), + tags.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); assertNull(compute.setTags(INSTANCE_ID, tags)); @@ -3860,7 +3959,7 @@ public void testSetTags_Null() { @Test public void testStartInstance_Operation() { - EasyMock.expect(computeRpcMock.start(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.start(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3870,12 +3969,13 @@ public void testStartInstance_Operation() { @Test public void testStartInstanceWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.start(eq(INSTANCE_ID.zone()), eq(INSTANCE_ID.instance()), + EasyMock.expect(computeRpcMock.start(eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.start(INSTANCE_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3885,7 +3985,7 @@ public void testStartInstanceWithSelectedFields_Operation() { @Test public void testStartInstance_Null() { - EasyMock.expect(computeRpcMock.start(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.start(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3894,7 +3994,7 @@ public void testStartInstance_Null() { @Test public void testStopInstance_Operation() { - EasyMock.expect(computeRpcMock.stop(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.stop(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3904,12 +4004,13 @@ public void testStopInstance_Operation() { @Test public void testStopInstanceWithSelectedFields_Operation() { Capture> capturedOptions = Capture.newInstance(); - EasyMock.expect(computeRpcMock.stop(eq(INSTANCE_ID.zone()), eq(INSTANCE_ID.instance()), + EasyMock.expect(computeRpcMock.stop(eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); compute = options.service(); Operation operation = compute.stop(INSTANCE_ID, OPERATION_OPTION_FIELDS); - String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.rpcOption()); + String selector = + (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); assertTrue(selector.contains("id")); assertTrue(selector.contains("description")); @@ -3919,7 +4020,7 @@ public void testStopInstanceWithSelectedFields_Operation() { @Test public void testStopInstance_Null() { - EasyMock.expect(computeRpcMock.stop(INSTANCE_ID.zone(), INSTANCE_ID.instance(), + EasyMock.expect(computeRpcMock.stop(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); compute = options.service(); @@ -3928,8 +4029,8 @@ public void testStopInstance_Null() { @Test public void testRetryableException() { - EasyMock.expect( - computeRpcMock.getDiskType(DISK_TYPE_ID.zone(), DISK_TYPE_ID.type(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getDiskType( + DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andThrow(new ComputeException(500, "InternalError")) .andReturn(DISK_TYPE.toPb()); EasyMock.replay(computeRpcMock); @@ -3941,8 +4042,8 @@ public void testRetryableException() { @Test public void testNonRetryableException() { String exceptionMessage = "Not Implemented"; - EasyMock.expect( - computeRpcMock.getDiskType(DISK_TYPE_ID.zone(), DISK_TYPE_ID.type(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getDiskType( + DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andThrow(new ComputeException(501, exceptionMessage)); EasyMock.replay(computeRpcMock); compute = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); @@ -3954,8 +4055,8 @@ public void testNonRetryableException() { @Test public void testRuntimeException() { String exceptionMessage = "Artificial runtime exception"; - EasyMock.expect( - computeRpcMock.getDiskType(DISK_TYPE_ID.zone(), DISK_TYPE_ID.type(), EMPTY_RPC_OPTIONS)) + EasyMock.expect(computeRpcMock.getDiskType( + DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andThrow(new RuntimeException(exceptionMessage)); EasyMock.replay(computeRpcMock); compute = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/DeprecationStatusTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/DeprecationStatusTest.java index 57fc8ba0a786..e3a423880995 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/DeprecationStatusTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/DeprecationStatusTest.java @@ -38,37 +38,73 @@ public class DeprecationStatusTest { MachineTypeId.of("project", "zone", "machineType"); private static final DeprecationStatus.Status STATUS = DeprecationStatus.Status.DELETED; private static final DeprecationStatus DISK_TYPE_STATUS = - DeprecationStatus.builder(STATUS) - .replacement(DISK_TYPE_ID) - .deprecated(DEPRECATED) - .obsolete(OBSOLETE) - .deleted(DELETED) + DeprecationStatus.newBuilder(STATUS) + .setReplacement(DISK_TYPE_ID) + .setDeprecated(DEPRECATED) + .setObsolete(OBSOLETE) + .setDeleted(DELETED) .build(); private static final DeprecationStatus DISK_TYPE_STATUS_MILLIS = + DeprecationStatus.newBuilder(STATUS) + .setReplacement(DISK_TYPE_ID) + .setDeprecated(DEPRECATED_MILLIS) + .setObsolete(OBSOLETE_MILLIS) + .setDeleted(DELETED_MILLIS) + .build(); + private static final DeprecationStatus MACHINE_TYPE_STATUS = + DeprecationStatus.newBuilder(STATUS, MACHINE_TYPE_ID) + .setDeprecated(DEPRECATED) + .setObsolete(OBSOLETE) + .setDeleted(DELETED) + .build(); + private static final DeprecationStatus DEPRECATED_STATUS = DeprecationStatus.builder(STATUS) .replacement(DISK_TYPE_ID) .deprecated(DEPRECATED_MILLIS) .obsolete(OBSOLETE_MILLIS) .deleted(DELETED_MILLIS) .build(); - private static final DeprecationStatus MACHINE_TYPE_STATUS = - DeprecationStatus.builder(STATUS, MACHINE_TYPE_ID) - .deprecated(DEPRECATED) - .obsolete(OBSOLETE) - .deleted(DELETED) - .build(); @Test public void testBuilder() { compareDeprecationStatus(DISK_TYPE_STATUS, DISK_TYPE_STATUS_MILLIS); - assertEquals(DELETED, DISK_TYPE_STATUS.deleted()); - assertEquals(DEPRECATED, DISK_TYPE_STATUS.deprecated()); - assertEquals(OBSOLETE, DISK_TYPE_STATUS.obsolete()); - assertEquals(DISK_TYPE_ID, DISK_TYPE_STATUS.replacement()); - assertEquals(DEPRECATED_MILLIS, DISK_TYPE_STATUS.deprecatedMillis()); - assertEquals(DELETED_MILLIS, DISK_TYPE_STATUS.deletedMillis()); - assertEquals(OBSOLETE_MILLIS, DISK_TYPE_STATUS.obsoleteMillis()); - assertEquals(STATUS, DISK_TYPE_STATUS.status()); + assertEquals(DELETED, DISK_TYPE_STATUS.getDeleted()); + assertEquals(DEPRECATED, DISK_TYPE_STATUS.getDeprecated()); + assertEquals(OBSOLETE, DISK_TYPE_STATUS.getObsolete()); + assertEquals(DISK_TYPE_ID, DISK_TYPE_STATUS.getReplacement()); + assertEquals(DEPRECATED_MILLIS, DISK_TYPE_STATUS.getDeprecatedMillis()); + assertEquals(DELETED_MILLIS, DISK_TYPE_STATUS.getDeletedMillis()); + assertEquals(OBSOLETE_MILLIS, DISK_TYPE_STATUS.getObsoleteMillis()); + assertEquals(STATUS, DISK_TYPE_STATUS.getStatus()); + assertEquals(DELETED, DISK_TYPE_STATUS_MILLIS.getDeleted()); + assertEquals(DEPRECATED, DISK_TYPE_STATUS_MILLIS.getDeprecated()); + assertEquals(OBSOLETE, DISK_TYPE_STATUS_MILLIS.getObsolete()); + assertEquals(DISK_TYPE_ID, DISK_TYPE_STATUS_MILLIS.getReplacement()); + assertEquals(DEPRECATED_MILLIS, DISK_TYPE_STATUS_MILLIS.getDeprecatedMillis()); + assertEquals(DELETED_MILLIS, DISK_TYPE_STATUS_MILLIS.getDeletedMillis()); + assertEquals(OBSOLETE_MILLIS, DISK_TYPE_STATUS_MILLIS.getObsoleteMillis()); + assertEquals(STATUS, DISK_TYPE_STATUS.getStatus()); + assertEquals(DELETED, MACHINE_TYPE_STATUS.getDeleted()); + assertEquals(DEPRECATED, MACHINE_TYPE_STATUS.getDeprecated()); + assertEquals(OBSOLETE, MACHINE_TYPE_STATUS.getObsolete()); + assertEquals(DEPRECATED_MILLIS, MACHINE_TYPE_STATUS.getDeprecatedMillis()); + assertEquals(DELETED_MILLIS, MACHINE_TYPE_STATUS.getDeletedMillis()); + assertEquals(OBSOLETE_MILLIS, MACHINE_TYPE_STATUS.getObsoleteMillis()); + assertEquals(MACHINE_TYPE_ID, MACHINE_TYPE_STATUS.getReplacement()); + assertEquals(STATUS, MACHINE_TYPE_STATUS.getStatus()); + } + + @Test + public void testBuilderDeprecated() { + compareDeprecationStatus(DISK_TYPE_STATUS, DISK_TYPE_STATUS_MILLIS); + assertEquals(DELETED, DEPRECATED_STATUS.deleted()); + assertEquals(DEPRECATED, DEPRECATED_STATUS.deprecated()); + assertEquals(OBSOLETE, DEPRECATED_STATUS.obsolete()); + assertEquals(DISK_TYPE_ID, DEPRECATED_STATUS.replacement()); + assertEquals(DEPRECATED_MILLIS, DEPRECATED_STATUS.deprecatedMillis()); + assertEquals(DELETED_MILLIS, DEPRECATED_STATUS.deletedMillis()); + assertEquals(OBSOLETE_MILLIS, DEPRECATED_STATUS.obsoleteMillis()); + assertEquals(STATUS, DEPRECATED_STATUS.status()); assertEquals(DELETED, DISK_TYPE_STATUS_MILLIS.deleted()); assertEquals(DEPRECATED, DISK_TYPE_STATUS_MILLIS.deprecated()); assertEquals(OBSOLETE, DISK_TYPE_STATUS_MILLIS.obsolete()); @@ -90,28 +126,28 @@ public void testBuilder() { @Test public void testGettersIllegalArgument() { DeprecationStatus deprecationStatus = - DeprecationStatus.builder(STATUS, MACHINE_TYPE_ID) - .deprecated("deprecated") - .obsolete("obsolete") - .deleted("delete") + DeprecationStatus.newBuilder(STATUS, MACHINE_TYPE_ID) + .setDeprecated("deprecated") + .setObsolete("obsolete") + .setDeleted("delete") .build(); - assertEquals("deprecated", deprecationStatus.deprecated()); + assertEquals("deprecated", deprecationStatus.getDeprecated()); try { - deprecationStatus.deprecatedMillis(); + deprecationStatus.getDeprecatedMillis(); fail("Expected IllegalArgumentException"); } catch (IllegalStateException ex) { // never reached } - assertEquals("obsolete", deprecationStatus.obsolete()); + assertEquals("obsolete", deprecationStatus.getObsolete()); try { - deprecationStatus.obsoleteMillis(); + deprecationStatus.getObsoleteMillis(); fail("Expected IllegalArgumentException"); } catch (IllegalStateException ex) { // never reached } - assertEquals("delete", deprecationStatus.deleted()); + assertEquals("delete", deprecationStatus.getDeleted()); try { - deprecationStatus.deletedMillis(); + deprecationStatus.getDeletedMillis(); fail("Expected IllegalArgumentException"); } catch (IllegalStateException ex) { // never reached @@ -123,10 +159,10 @@ public void testToBuilder() { compareDeprecationStatus(DISK_TYPE_STATUS, DISK_TYPE_STATUS.toBuilder().build()); compareDeprecationStatus(MACHINE_TYPE_STATUS, MACHINE_TYPE_STATUS.toBuilder().build()); DeprecationStatus deprecationStatus = DISK_TYPE_STATUS.toBuilder() - .deleted(DEPRECATED) + .setDeleted(DEPRECATED) .build(); - assertEquals(DEPRECATED, deprecationStatus.deleted()); - deprecationStatus = deprecationStatus.toBuilder().deleted(DELETED).build(); + assertEquals(DEPRECATED, deprecationStatus.getDeleted()); + deprecationStatus = deprecationStatus.toBuilder().setDeleted(DELETED).build(); compareDeprecationStatus(DISK_TYPE_STATUS, deprecationStatus); } @@ -139,11 +175,11 @@ public void testToBuilderIncomplete() { @Test public void testOf() { DeprecationStatus diskStatus = DeprecationStatus.of(STATUS, DISK_TYPE_ID); - assertNull(diskStatus.deleted()); - assertNull(diskStatus.deprecated()); - assertNull(diskStatus.obsolete()); - assertEquals(DISK_TYPE_ID, diskStatus.replacement()); - assertEquals(STATUS, diskStatus.status()); + assertNull(diskStatus.getDeleted()); + assertNull(diskStatus.getDeprecated()); + assertNull(diskStatus.getObsolete()); + assertEquals(DISK_TYPE_ID, diskStatus.getReplacement()); + assertEquals(STATUS, diskStatus.getStatus()); } @Test @@ -154,11 +190,13 @@ public void testToAndFromPb() { DeprecationStatus machineStatus = DeprecationStatus.fromPb(MACHINE_TYPE_STATUS.toPb(), MachineTypeId.FROM_URL_FUNCTION); compareDeprecationStatus(MACHINE_TYPE_STATUS, machineStatus); - diskStatus = DeprecationStatus.builder(STATUS, DISK_TYPE_ID).deprecated(DEPRECATED).build(); + diskStatus = DeprecationStatus.newBuilder(STATUS, DISK_TYPE_ID) + .setDeprecated(DEPRECATED) + .build(); assertEquals(diskStatus, DeprecationStatus.fromPb(diskStatus.toPb(), DiskTypeId.FROM_URL_FUNCTION)); machineStatus = - DeprecationStatus.builder(STATUS, MACHINE_TYPE_ID).deprecated(DEPRECATED).build(); + DeprecationStatus.newBuilder(STATUS, MACHINE_TYPE_ID).setDeprecated(DEPRECATED).build(); assertEquals(machineStatus, DeprecationStatus.fromPb(machineStatus.toPb(), MachineTypeId.FROM_URL_FUNCTION)); diskStatus = DeprecationStatus.of(STATUS, DISK_TYPE_ID); @@ -168,14 +206,14 @@ public void testToAndFromPb() { private void compareDeprecationStatus(DeprecationStatus expected, DeprecationStatus value) { assertEquals(expected, value); - assertEquals(expected.deleted(), value.deleted()); - assertEquals(expected.deprecated(), value.deprecated()); - assertEquals(expected.obsolete(), value.obsolete()); - assertEquals(expected.deletedMillis(), value.deletedMillis()); - assertEquals(expected.deprecatedMillis(), value.deprecatedMillis()); - assertEquals(expected.obsoleteMillis(), value.obsoleteMillis()); - assertEquals(expected.replacement(), value.replacement()); - assertEquals(expected.status(), value.status()); + assertEquals(expected.getDeleted(), value.getDeleted()); + assertEquals(expected.getDeprecated(), value.getDeprecated()); + assertEquals(expected.getObsolete(), value.getObsolete()); + assertEquals(expected.getDeletedMillis(), value.getDeletedMillis()); + assertEquals(expected.getDeprecatedMillis(), value.getDeprecatedMillis()); + assertEquals(expected.getObsoleteMillis(), value.getObsoleteMillis()); + assertEquals(expected.getReplacement(), value.getReplacement()); + assertEquals(expected.getStatus(), value.getStatus()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskIdTest.java index df5fee9e6ac7..1405e993b274 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskIdTest.java @@ -39,6 +39,23 @@ public class DiskIdTest { @Test public void testOf() { + DiskId diskId = DiskId.of(PROJECT, ZONE, NAME); + assertEquals(PROJECT, diskId.getProject()); + assertEquals(ZONE, diskId.getZone()); + assertEquals(NAME, diskId.getDisk()); + assertEquals(URL, diskId.getSelfLink()); + diskId = DiskId.of(ZONE, NAME); + assertNull(diskId.getProject()); + assertEquals(ZONE, diskId.getZone()); + assertEquals(NAME, diskId.getDisk()); + diskId = DiskId.of(ZoneId.of(ZONE), NAME); + assertNull(diskId.getProject()); + assertEquals(ZONE, diskId.getZone()); + assertEquals(NAME, diskId.getDisk()); + } + + @Test + public void testOfDeprecated() { DiskId diskId = DiskId.of(PROJECT, ZONE, NAME); assertEquals(PROJECT, diskId.project()); assertEquals(ZONE, diskId.zone()); @@ -57,7 +74,7 @@ public void testOf() { @Test public void testToAndFromUrl() { DiskId diskId = DiskId.of(PROJECT, ZONE, NAME); - compareDiskId(diskId, DiskId.fromUrl(diskId.selfLink())); + compareDiskId(diskId, DiskId.fromUrl(diskId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid disk URL"); DiskId.fromUrl("notMatchingUrl"); @@ -72,16 +89,16 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(DiskId.matchesUrl(DiskId.of(PROJECT, ZONE, NAME).selfLink())); + assertTrue(DiskId.matchesUrl(DiskId.of(PROJECT, ZONE, NAME).getSelfLink())); assertFalse(DiskId.matchesUrl("notMatchingUrl")); } private void compareDiskId(DiskId expected, DiskId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.zone(), expected.zone()); - assertEquals(expected.disk(), expected.disk()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getZone(), expected.getZone()); + assertEquals(expected.getDisk(), expected.getDisk()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskImageConfigurationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskImageConfigurationTest.java index f5ecf03ddf2a..88699de88664 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskImageConfigurationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskImageConfigurationTest.java @@ -20,7 +20,6 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import org.junit.Assert; import org.junit.Test; public class DiskImageConfigurationTest { @@ -28,12 +27,19 @@ public class DiskImageConfigurationTest { private static final DiskId SOURCE_DISK = DiskId.of("project", "zone", "disk"); private static final String SOURCE_DISK_ID = "diskId"; private static final Long ARCHIVE_SIZE_BYTES = 42L; - private static final ImageConfiguration.SourceType SOURCE_TYPE = ImageConfiguration.SourceType.RAW; + private static final ImageConfiguration.SourceType SOURCE_TYPE = + ImageConfiguration.SourceType.RAW; private static final DiskImageConfiguration CONFIGURATION = + DiskImageConfiguration.newBuilder(SOURCE_DISK) + .setSourceDiskId(SOURCE_DISK_ID) + .setSourceType(SOURCE_TYPE) + .setArchiveSizeBytes(ARCHIVE_SIZE_BYTES) + .build(); + private static final DiskImageConfiguration DEPRECATED_CONFIGURATION = DiskImageConfiguration.builder(SOURCE_DISK) - .sourceDiskId(SOURCE_DISK_ID) - .sourceType(SOURCE_TYPE) - .archiveSizeBytes(ARCHIVE_SIZE_BYTES) + .setSourceDiskId(SOURCE_DISK_ID) + .setSourceType(SOURCE_TYPE) + .setArchiveSizeBytes(ARCHIVE_SIZE_BYTES) .build(); @Test @@ -42,14 +48,14 @@ public void testToBuilder() { DiskId newDisk = DiskId.of("newProject", "newZone", "newDisk"); String newDiskId = "newDiskId"; DiskImageConfiguration configuration = CONFIGURATION.toBuilder() - .sourceDisk(newDisk) - .sourceDiskId(newDiskId) + .setSourceDisk(newDisk) + .setSourceDiskId(newDiskId) .build(); - assertEquals(newDisk, configuration.sourceDisk()); - assertEquals(newDiskId, configuration.sourceDiskId()); + assertEquals(newDisk, configuration.getSourceDisk()); + assertEquals(newDiskId, configuration.getSourceDiskId()); configuration = configuration.toBuilder() - .sourceDiskId(SOURCE_DISK_ID) - .sourceDisk(SOURCE_DISK) + .setSourceDiskId(SOURCE_DISK_ID) + .setSourceDisk(SOURCE_DISK) .build(); compareDiskImageConfiguration(CONFIGURATION, configuration); } @@ -62,11 +68,20 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(SOURCE_TYPE, CONFIGURATION.sourceType()); - assertEquals(SOURCE_DISK, CONFIGURATION.sourceDisk()); - assertEquals(SOURCE_DISK_ID, CONFIGURATION.sourceDiskId()); - assertEquals(ARCHIVE_SIZE_BYTES, CONFIGURATION.archiveSizeBytes()); - Assert.assertEquals(ImageConfiguration.Type.DISK, CONFIGURATION.type()); + assertEquals(SOURCE_TYPE, CONFIGURATION.getSourceType()); + assertEquals(SOURCE_DISK, CONFIGURATION.getSourceDisk()); + assertEquals(SOURCE_DISK_ID, CONFIGURATION.getSourceDiskId()); + assertEquals(ARCHIVE_SIZE_BYTES, CONFIGURATION.getArchiveSizeBytes()); + assertEquals(ImageConfiguration.Type.DISK, CONFIGURATION.getType()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(SOURCE_TYPE, DEPRECATED_CONFIGURATION.sourceType()); + assertEquals(SOURCE_DISK, DEPRECATED_CONFIGURATION.sourceDisk()); + assertEquals(SOURCE_DISK_ID, DEPRECATED_CONFIGURATION.sourceDiskId()); + assertEquals(ARCHIVE_SIZE_BYTES, DEPRECATED_CONFIGURATION.archiveSizeBytes()); + assertEquals(ImageConfiguration.Type.DISK, DEPRECATED_CONFIGURATION.type()); } @Test @@ -82,17 +97,17 @@ public void testToAndFromPb() { @Test public void testOf() { DiskImageConfiguration configuration = DiskImageConfiguration.of(SOURCE_DISK); - Assert.assertEquals(ImageConfiguration.Type.DISK, configuration.type()); - assertNull(configuration.sourceDiskId()); - assertNull(configuration.sourceType()); - assertNull(configuration.archiveSizeBytes()); - assertEquals(SOURCE_DISK, configuration.sourceDisk()); + assertEquals(ImageConfiguration.Type.DISK, configuration.getType()); + assertNull(configuration.getSourceDiskId()); + assertNull(configuration.getSourceType()); + assertNull(configuration.getArchiveSizeBytes()); + assertEquals(SOURCE_DISK, configuration.getSourceDisk()); } @Test public void testSetProjectId() { DiskImageConfiguration configuration = CONFIGURATION.toBuilder() - .sourceDisk(DiskId.of("zone", "disk")) + .setSourceDisk(DiskId.of("zone", "disk")) .build(); compareDiskImageConfiguration(CONFIGURATION, configuration.setProjectId("project")); } @@ -100,11 +115,11 @@ public void testSetProjectId() { private void compareDiskImageConfiguration(DiskImageConfiguration expected, DiskImageConfiguration value) { assertEquals(expected, value); - assertEquals(expected.type(), value.type()); - assertEquals(expected.archiveSizeBytes(), value.archiveSizeBytes()); - assertEquals(expected.sourceDisk(), value.sourceDisk()); - assertEquals(expected.sourceDiskId(), value.sourceDiskId()); - assertEquals(expected.sourceType(), value.sourceType()); + assertEquals(expected.getType(), value.getType()); + assertEquals(expected.getArchiveSizeBytes(), value.getArchiveSizeBytes()); + assertEquals(expected.getSourceDisk(), value.getSourceDisk()); + assertEquals(expected.getSourceDiskId(), value.getSourceDiskId()); + assertEquals(expected.getSourceType(), value.getSourceType()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskInfoTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskInfoTest.java index 7e4bbc31b617..f2c073a177b4 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskInfoTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskInfoTest.java @@ -47,53 +47,86 @@ public class DiskInfoTest { private static final Long LAST_ATTACH_TIMESTAMP = 1453293600000L; private static final Long LAST_DETACH_TIMESTAMP = 1453293660000L; private static final StandardDiskConfiguration DISK_CONFIGURATION = - StandardDiskConfiguration.builder() - .sizeGb(SIZE_GB) - .diskType(TYPE) + StandardDiskConfiguration.newBuilder() + .setSizeGb(SIZE_GB) + .setDiskType(TYPE) .build(); private static final SnapshotDiskConfiguration SNAPSHOT_DISK_CONFIGURATION = - SnapshotDiskConfiguration.builder(SNAPSHOT) - .sizeGb(SIZE_GB) - .diskType(TYPE) - .sourceSnapshotId(SNAPSHOT_ID) + SnapshotDiskConfiguration.newBuilder(SNAPSHOT) + .setSizeGb(SIZE_GB) + .setDiskType(TYPE) + .setSourceSnapshotId(SNAPSHOT_ID) .build(); private static final ImageDiskConfiguration IMAGE_DISK_CONFIGURATION = - ImageDiskConfiguration.builder(IMAGE) - .sizeGb(SIZE_GB) - .diskType(TYPE) - .sourceImageId(IMAGE_ID) + ImageDiskConfiguration.newBuilder(IMAGE) + .setSizeGb(SIZE_GB) + .setDiskType(TYPE) + .setSourceImageId(IMAGE_ID) .build(); - private static final DiskInfo DISK_INFO = DiskInfo.builder(DISK_ID, DISK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .creationStatus(CREATION_STATUS) - .description(DESCRIPTION) - .licenses(LICENSES) - .attachedInstances(ATTACHED_INSTANCES) - .lastAttachTimestamp(LAST_ATTACH_TIMESTAMP) - .lastDetachTimestamp(LAST_DETACH_TIMESTAMP) + private static final DiskInfo DISK_INFO = DiskInfo.newBuilder(DISK_ID, DISK_CONFIGURATION) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setCreationStatus(CREATION_STATUS) + .setDescription(DESCRIPTION) + .setLicenses(LICENSES) + .setAttachedInstances(ATTACHED_INSTANCES) + .setLastAttachTimestamp(LAST_ATTACH_TIMESTAMP) + .setLastDetachTimestamp(LAST_DETACH_TIMESTAMP) .build(); private static final DiskInfo SNAPSHOT_DISK_INFO = + DiskInfo.newBuilder(DISK_ID, SNAPSHOT_DISK_CONFIGURATION) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setCreationStatus(CREATION_STATUS) + .setDescription(DESCRIPTION) + .setLicenses(LICENSES) + .setAttachedInstances(ATTACHED_INSTANCES) + .setLastAttachTimestamp(LAST_ATTACH_TIMESTAMP) + .setLastDetachTimestamp(LAST_DETACH_TIMESTAMP) + .build(); + private static final DiskInfo IMAGE_DISK_INFO = + DiskInfo.newBuilder(DISK_ID, IMAGE_DISK_CONFIGURATION) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setCreationStatus(CREATION_STATUS) + .setDescription(DESCRIPTION) + .setLicenses(LICENSES) + .setAttachedInstances(ATTACHED_INSTANCES) + .setLastAttachTimestamp(LAST_ATTACH_TIMESTAMP) + .setLastDetachTimestamp(LAST_DETACH_TIMESTAMP) + .build(); + private static final DiskInfo DEPRECATED_DISK_INFO = + DiskInfo.builder(DISK_ID, DISK_CONFIGURATION) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setCreationStatus(CREATION_STATUS) + .description(DESCRIPTION) + .setLicenses(LICENSES) + .setAttachedInstances(ATTACHED_INSTANCES) + .setLastAttachTimestamp(LAST_ATTACH_TIMESTAMP) + .setLastDetachTimestamp(LAST_DETACH_TIMESTAMP) + .build(); + private static final DiskInfo DEPRECATED_SNAPSHOT_DISK_INFO = DiskInfo.builder(DISK_ID, SNAPSHOT_DISK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .creationStatus(CREATION_STATUS) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setCreationStatus(CREATION_STATUS) .description(DESCRIPTION) - .licenses(LICENSES) - .attachedInstances(ATTACHED_INSTANCES) - .lastAttachTimestamp(LAST_ATTACH_TIMESTAMP) - .lastDetachTimestamp(LAST_DETACH_TIMESTAMP) + .setLicenses(LICENSES) + .setAttachedInstances(ATTACHED_INSTANCES) + .setLastAttachTimestamp(LAST_ATTACH_TIMESTAMP) + .setLastDetachTimestamp(LAST_DETACH_TIMESTAMP) .build(); - private static final DiskInfo IMAGE_DISK_INFO = + private static final DiskInfo DEPRECATED_IMAGE_DISK_INFO = DiskInfo.builder(DISK_ID, IMAGE_DISK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .creationStatus(CREATION_STATUS) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setCreationStatus(CREATION_STATUS) .description(DESCRIPTION) - .licenses(LICENSES) - .attachedInstances(ATTACHED_INSTANCES) - .lastAttachTimestamp(LAST_ATTACH_TIMESTAMP) - .lastDetachTimestamp(LAST_DETACH_TIMESTAMP) + .setLicenses(LICENSES) + .setAttachedInstances(ATTACHED_INSTANCES) + .setLastAttachTimestamp(LAST_ATTACH_TIMESTAMP) + .setLastDetachTimestamp(LAST_DETACH_TIMESTAMP) .build(); @Test @@ -101,9 +134,9 @@ public void testToBuilder() { compareDiskInfo(DISK_INFO, DISK_INFO.toBuilder().build()); compareDiskInfo(IMAGE_DISK_INFO, IMAGE_DISK_INFO.toBuilder().build()); compareDiskInfo(SNAPSHOT_DISK_INFO, SNAPSHOT_DISK_INFO.toBuilder().build()); - DiskInfo diskInfo = DISK_INFO.toBuilder().description("newDescription").build(); - assertEquals("newDescription", diskInfo.description()); - diskInfo = diskInfo.toBuilder().description("description").build(); + DiskInfo diskInfo = DISK_INFO.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", diskInfo.getDescription()); + diskInfo = diskInfo.toBuilder().setDescription("description").build(); compareDiskInfo(DISK_INFO, diskInfo); } @@ -119,73 +152,107 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(GENERATED_ID, DISK_INFO.generatedId()); - assertEquals(DISK_ID, DISK_INFO.diskId()); - assertEquals(DISK_CONFIGURATION, DISK_INFO.configuration()); - assertEquals(CREATION_TIMESTAMP, DISK_INFO.creationTimestamp()); - assertEquals(CREATION_STATUS, DISK_INFO.creationStatus()); - assertEquals(DESCRIPTION, DISK_INFO.description()); - assertEquals(LICENSES, DISK_INFO.licenses()); - assertEquals(ATTACHED_INSTANCES, DISK_INFO.attachedInstances()); - assertEquals(LAST_ATTACH_TIMESTAMP, DISK_INFO.lastAttachTimestamp()); - assertEquals(LAST_DETACH_TIMESTAMP, DISK_INFO.lastDetachTimestamp()); - assertEquals(GENERATED_ID, IMAGE_DISK_INFO.generatedId()); - assertEquals(DISK_ID, IMAGE_DISK_INFO.diskId()); - assertEquals(IMAGE_DISK_CONFIGURATION, IMAGE_DISK_INFO.configuration()); - assertEquals(CREATION_TIMESTAMP, IMAGE_DISK_INFO.creationTimestamp()); - assertEquals(CREATION_STATUS, IMAGE_DISK_INFO.creationStatus()); - assertEquals(DESCRIPTION, IMAGE_DISK_INFO.description()); - assertEquals(LICENSES, IMAGE_DISK_INFO.licenses()); - assertEquals(ATTACHED_INSTANCES, IMAGE_DISK_INFO.attachedInstances()); - assertEquals(LAST_ATTACH_TIMESTAMP, IMAGE_DISK_INFO.lastAttachTimestamp()); - assertEquals(LAST_DETACH_TIMESTAMP, IMAGE_DISK_INFO.lastDetachTimestamp()); - assertEquals(GENERATED_ID, SNAPSHOT_DISK_INFO.generatedId()); - assertEquals(DISK_ID, SNAPSHOT_DISK_INFO.diskId()); - assertEquals(SNAPSHOT_DISK_CONFIGURATION, SNAPSHOT_DISK_INFO.configuration()); - assertEquals(CREATION_TIMESTAMP, SNAPSHOT_DISK_INFO.creationTimestamp()); - assertEquals(CREATION_STATUS, SNAPSHOT_DISK_INFO.creationStatus()); - assertEquals(DESCRIPTION, SNAPSHOT_DISK_INFO.description()); - assertEquals(LICENSES, SNAPSHOT_DISK_INFO.licenses()); - assertEquals(ATTACHED_INSTANCES, SNAPSHOT_DISK_INFO.attachedInstances()); - assertEquals(LAST_ATTACH_TIMESTAMP, SNAPSHOT_DISK_INFO.lastAttachTimestamp()); - assertEquals(LAST_DETACH_TIMESTAMP, SNAPSHOT_DISK_INFO.lastDetachTimestamp()); + assertEquals(GENERATED_ID, DISK_INFO.getGeneratedId()); + assertEquals(DISK_ID, DISK_INFO.getDiskId()); + assertEquals(DISK_CONFIGURATION, DISK_INFO.getConfiguration()); + assertEquals(CREATION_TIMESTAMP, DISK_INFO.getCreationTimestamp()); + assertEquals(CREATION_STATUS, DISK_INFO.getCreationStatus()); + assertEquals(DESCRIPTION, DISK_INFO.getDescription()); + assertEquals(LICENSES, DISK_INFO.getLicenses()); + assertEquals(ATTACHED_INSTANCES, DISK_INFO.getAttachedInstances()); + assertEquals(LAST_ATTACH_TIMESTAMP, DISK_INFO.getLastAttachTimestamp()); + assertEquals(LAST_DETACH_TIMESTAMP, DISK_INFO.getLastDetachTimestamp()); + assertEquals(GENERATED_ID, IMAGE_DISK_INFO.getGeneratedId()); + assertEquals(DISK_ID, IMAGE_DISK_INFO.getDiskId()); + assertEquals(IMAGE_DISK_CONFIGURATION, IMAGE_DISK_INFO.getConfiguration()); + assertEquals(CREATION_TIMESTAMP, IMAGE_DISK_INFO.getCreationTimestamp()); + assertEquals(CREATION_STATUS, IMAGE_DISK_INFO.getCreationStatus()); + assertEquals(DESCRIPTION, IMAGE_DISK_INFO.getDescription()); + assertEquals(LICENSES, IMAGE_DISK_INFO.getLicenses()); + assertEquals(ATTACHED_INSTANCES, IMAGE_DISK_INFO.getAttachedInstances()); + assertEquals(LAST_ATTACH_TIMESTAMP, IMAGE_DISK_INFO.getLastAttachTimestamp()); + assertEquals(LAST_DETACH_TIMESTAMP, IMAGE_DISK_INFO.getLastDetachTimestamp()); + assertEquals(GENERATED_ID, SNAPSHOT_DISK_INFO.getGeneratedId()); + assertEquals(DISK_ID, SNAPSHOT_DISK_INFO.getDiskId()); + assertEquals(SNAPSHOT_DISK_CONFIGURATION, SNAPSHOT_DISK_INFO.getConfiguration()); + assertEquals(CREATION_TIMESTAMP, SNAPSHOT_DISK_INFO.getCreationTimestamp()); + assertEquals(CREATION_STATUS, SNAPSHOT_DISK_INFO.getCreationStatus()); + assertEquals(DESCRIPTION, SNAPSHOT_DISK_INFO.getDescription()); + assertEquals(LICENSES, SNAPSHOT_DISK_INFO.getLicenses()); + assertEquals(ATTACHED_INSTANCES, SNAPSHOT_DISK_INFO.getAttachedInstances()); + assertEquals(LAST_ATTACH_TIMESTAMP, SNAPSHOT_DISK_INFO.getLastAttachTimestamp()); + assertEquals(LAST_DETACH_TIMESTAMP, SNAPSHOT_DISK_INFO.getLastDetachTimestamp()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(GENERATED_ID, DEPRECATED_DISK_INFO.generatedId()); + assertEquals(DISK_ID, DEPRECATED_DISK_INFO.diskId()); + assertEquals(DISK_CONFIGURATION, DEPRECATED_DISK_INFO.configuration()); + assertEquals(CREATION_TIMESTAMP, DEPRECATED_DISK_INFO.creationTimestamp()); + assertEquals(CREATION_STATUS, DEPRECATED_DISK_INFO.creationStatus()); + assertEquals(DESCRIPTION, DEPRECATED_DISK_INFO.description()); + assertEquals(LICENSES, DEPRECATED_DISK_INFO.licenses()); + assertEquals(ATTACHED_INSTANCES, DEPRECATED_DISK_INFO.attachedInstances()); + assertEquals(LAST_ATTACH_TIMESTAMP, DEPRECATED_DISK_INFO.lastAttachTimestamp()); + assertEquals(LAST_DETACH_TIMESTAMP, DEPRECATED_DISK_INFO.lastDetachTimestamp()); + assertEquals(GENERATED_ID, DEPRECATED_IMAGE_DISK_INFO.generatedId()); + assertEquals(DISK_ID, DEPRECATED_IMAGE_DISK_INFO.diskId()); + assertEquals(IMAGE_DISK_CONFIGURATION, DEPRECATED_IMAGE_DISK_INFO.configuration()); + assertEquals(CREATION_TIMESTAMP, DEPRECATED_IMAGE_DISK_INFO.creationTimestamp()); + assertEquals(CREATION_STATUS, DEPRECATED_IMAGE_DISK_INFO.creationStatus()); + assertEquals(DESCRIPTION, DEPRECATED_IMAGE_DISK_INFO.description()); + assertEquals(LICENSES, DEPRECATED_IMAGE_DISK_INFO.licenses()); + assertEquals(ATTACHED_INSTANCES, DEPRECATED_IMAGE_DISK_INFO.attachedInstances()); + assertEquals(LAST_ATTACH_TIMESTAMP, DEPRECATED_IMAGE_DISK_INFO.lastAttachTimestamp()); + assertEquals(LAST_DETACH_TIMESTAMP, DEPRECATED_IMAGE_DISK_INFO.lastDetachTimestamp()); + assertEquals(GENERATED_ID, DEPRECATED_SNAPSHOT_DISK_INFO.generatedId()); + assertEquals(DISK_ID, DEPRECATED_SNAPSHOT_DISK_INFO.diskId()); + assertEquals(SNAPSHOT_DISK_CONFIGURATION, DEPRECATED_SNAPSHOT_DISK_INFO.configuration()); + assertEquals(CREATION_TIMESTAMP, DEPRECATED_SNAPSHOT_DISK_INFO.creationTimestamp()); + assertEquals(CREATION_STATUS, DEPRECATED_SNAPSHOT_DISK_INFO.creationStatus()); + assertEquals(DESCRIPTION, DEPRECATED_SNAPSHOT_DISK_INFO.description()); + assertEquals(LICENSES, DEPRECATED_SNAPSHOT_DISK_INFO.licenses()); + assertEquals(ATTACHED_INSTANCES, DEPRECATED_SNAPSHOT_DISK_INFO.attachedInstances()); + assertEquals(LAST_ATTACH_TIMESTAMP, DEPRECATED_SNAPSHOT_DISK_INFO.lastAttachTimestamp()); + assertEquals(LAST_DETACH_TIMESTAMP, DEPRECATED_SNAPSHOT_DISK_INFO.lastDetachTimestamp()); } @Test public void testOf() { DiskInfo diskInfo = DiskInfo.of(DISK_ID, DISK_CONFIGURATION); - assertNull(diskInfo.generatedId()); - assertEquals(DISK_ID, diskInfo.diskId()); - assertEquals(DISK_CONFIGURATION, diskInfo.configuration()); - assertNull(diskInfo.creationTimestamp()); - assertNull(diskInfo.creationStatus()); - assertNull(diskInfo.description()); - assertNull(diskInfo.licenses()); - assertNull(diskInfo.attachedInstances()); - assertNull(diskInfo.lastAttachTimestamp()); - assertNull(diskInfo.lastDetachTimestamp()); + assertNull(diskInfo.getGeneratedId()); + assertEquals(DISK_ID, diskInfo.getDiskId()); + assertEquals(DISK_CONFIGURATION, diskInfo.getConfiguration()); + assertNull(diskInfo.getCreationTimestamp()); + assertNull(diskInfo.getCreationStatus()); + assertNull(diskInfo.getDescription()); + assertNull(diskInfo.getLicenses()); + assertNull(diskInfo.getAttachedInstances()); + assertNull(diskInfo.getLastAttachTimestamp()); + assertNull(diskInfo.getLastDetachTimestamp()); diskInfo = DiskInfo.of(DISK_ID, IMAGE_DISK_CONFIGURATION); - assertNull(diskInfo.generatedId()); - assertEquals(DISK_ID, diskInfo.diskId()); - assertEquals(IMAGE_DISK_CONFIGURATION, diskInfo.configuration()); - assertNull(diskInfo.creationTimestamp()); - assertNull(diskInfo.creationStatus()); - assertNull(diskInfo.description()); - assertNull(diskInfo.licenses()); - assertNull(diskInfo.attachedInstances()); - assertNull(diskInfo.lastAttachTimestamp()); - assertNull(diskInfo.lastDetachTimestamp()); + assertNull(diskInfo.getGeneratedId()); + assertEquals(DISK_ID, diskInfo.getDiskId()); + assertEquals(IMAGE_DISK_CONFIGURATION, diskInfo.getConfiguration()); + assertNull(diskInfo.getCreationTimestamp()); + assertNull(diskInfo.getCreationStatus()); + assertNull(diskInfo.getDescription()); + assertNull(diskInfo.getLicenses()); + assertNull(diskInfo.getAttachedInstances()); + assertNull(diskInfo.getLastAttachTimestamp()); + assertNull(diskInfo.getLastDetachTimestamp()); diskInfo = DiskInfo.of(DISK_ID, SNAPSHOT_DISK_CONFIGURATION); - assertNull(diskInfo.generatedId()); - assertEquals(DISK_ID, diskInfo.diskId()); - assertEquals(SNAPSHOT_DISK_CONFIGURATION, diskInfo.configuration()); - assertNull(diskInfo.creationTimestamp()); - assertNull(diskInfo.creationStatus()); - assertNull(diskInfo.description()); - assertNull(diskInfo.licenses()); - assertNull(diskInfo.attachedInstances()); - assertNull(diskInfo.lastAttachTimestamp()); - assertNull(diskInfo.lastDetachTimestamp()); + assertNull(diskInfo.getGeneratedId()); + assertEquals(DISK_ID, diskInfo.getDiskId()); + assertEquals(SNAPSHOT_DISK_CONFIGURATION, diskInfo.getConfiguration()); + assertNull(diskInfo.getCreationTimestamp()); + assertNull(diskInfo.getCreationStatus()); + assertNull(diskInfo.getDescription()); + assertNull(diskInfo.getLicenses()); + assertNull(diskInfo.getAttachedInstances()); + assertNull(diskInfo.getLastAttachTimestamp()); + assertNull(diskInfo.getLastDetachTimestamp()); } @Test @@ -197,25 +264,25 @@ public void testToAndFromPb() { diskInfo = DiskInfo.fromPb(IMAGE_DISK_INFO.toPb()); compareDiskInfo(IMAGE_DISK_INFO, diskInfo); Disk disk = new Disk() - .setSelfLink(DISK_ID.selfLink()) - .setType(TYPE.selfLink()) + .setSelfLink(DISK_ID.getSelfLink()) + .setType(TYPE.getSelfLink()) .setSizeGb(SIZE_GB); diskInfo = DiskInfo.of(DISK_ID, DISK_CONFIGURATION); compareDiskInfo(diskInfo, DiskInfo.fromPb(disk)); disk = new Disk() - .setType(TYPE.selfLink()) + .setType(TYPE.getSelfLink()) .setSizeGb(SIZE_GB) - .setSelfLink(DISK_ID.selfLink()) + .setSelfLink(DISK_ID.getSelfLink()) .setSourceSnapshotId(SNAPSHOT_ID) - .setSourceSnapshot(SNAPSHOT.selfLink()); + .setSourceSnapshot(SNAPSHOT.getSelfLink()); diskInfo = DiskInfo.of(DISK_ID, SNAPSHOT_DISK_CONFIGURATION); compareDiskInfo(diskInfo, DiskInfo.fromPb(disk)); disk = new Disk() - .setType(TYPE.selfLink()) + .setType(TYPE.getSelfLink()) .setSizeGb(SIZE_GB) - .setSelfLink(DISK_ID.selfLink()) + .setSelfLink(DISK_ID.getSelfLink()) .setSourceImageId(IMAGE_ID) - .setSourceImage(IMAGE.selfLink()); + .setSourceImage(IMAGE.getSelfLink()); diskInfo = DiskInfo.of(DISK_ID, IMAGE_DISK_CONFIGURATION); compareDiskInfo(diskInfo, DiskInfo.fromPb(disk)); } @@ -223,45 +290,45 @@ public void testToAndFromPb() { @Test public void testSetProjectId() { StandardDiskConfiguration standardDiskConfiguration = DISK_CONFIGURATION.toBuilder() - .diskType(DiskTypeId.of(TYPE.zone(), TYPE.type())) + .setDiskType(DiskTypeId.of(TYPE.getZone(), TYPE.getType())) .build(); DiskInfo diskInfo = DISK_INFO.toBuilder() - .diskId(DiskId.of(DISK_ID.zone(), DISK_ID.disk())) - .configuration(standardDiskConfiguration) + .setDiskId(DiskId.of(DISK_ID.getZone(), DISK_ID.getDisk())) + .setConfiguration(standardDiskConfiguration) .build(); compareDiskInfo(DISK_INFO, diskInfo.setProjectId("project")); SnapshotDiskConfiguration snapshotDiskConfiguration = SNAPSHOT_DISK_CONFIGURATION.toBuilder() - .diskType(DiskTypeId.of(TYPE.zone(), TYPE.type())) - .sourceSnapshot(SnapshotId.of(SNAPSHOT.snapshot())) + .setDiskType(DiskTypeId.of(TYPE.getZone(), TYPE.getType())) + .setSourceSnapshot(SnapshotId.of(SNAPSHOT.getSnapshot())) .build(); diskInfo = SNAPSHOT_DISK_INFO.toBuilder() - .diskId(DiskId.of(DISK_ID.zone(), DISK_ID.disk())) - .configuration(snapshotDiskConfiguration) + .setDiskId(DiskId.of(DISK_ID.getZone(), DISK_ID.getDisk())) + .setConfiguration(snapshotDiskConfiguration) .build(); compareDiskInfo(SNAPSHOT_DISK_INFO, diskInfo.setProjectId("project")); ImageDiskConfiguration imageDiskConfiguration = IMAGE_DISK_CONFIGURATION.toBuilder() - .diskType(DiskTypeId.of(TYPE.zone(), TYPE.type())) - .sourceImage(ImageId.of(IMAGE.image())) + .setDiskType(DiskTypeId.of(TYPE.getZone(), TYPE.getType())) + .setSourceImage(ImageId.of(IMAGE.getImage())) .build(); diskInfo = IMAGE_DISK_INFO.toBuilder() - .diskId(DiskId.of(DISK_ID.zone(), DISK_ID.disk())) - .configuration(imageDiskConfiguration) + .setDiskId(DiskId.of(DISK_ID.getZone(), DISK_ID.getDisk())) + .setConfiguration(imageDiskConfiguration) .build(); compareDiskInfo(IMAGE_DISK_INFO, diskInfo.setProjectId("project")); } public void compareDiskInfo(DiskInfo expected, DiskInfo value) { assertEquals(expected, value); - assertEquals(expected.configuration(), value.configuration()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.diskId(), value.diskId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.creationStatus(), value.creationStatus()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.licenses(), value.licenses()); - assertEquals(expected.attachedInstances(), value.attachedInstances()); - assertEquals(expected.lastAttachTimestamp(), value.lastAttachTimestamp()); - assertEquals(expected.lastDetachTimestamp(), value.lastDetachTimestamp()); + assertEquals(expected.getConfiguration(), value.getConfiguration()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getDiskId(), value.getDiskId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getCreationStatus(), value.getCreationStatus()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getLicenses(), value.getLicenses()); + assertEquals(expected.getAttachedInstances(), value.getAttachedInstances()); + assertEquals(expected.getLastAttachTimestamp(), value.getLastAttachTimestamp()); + assertEquals(expected.getLastDetachTimestamp(), value.getLastDetachTimestamp()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTest.java index 03182493803c..24b214d6a5bd 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTest.java @@ -54,21 +54,21 @@ public class DiskTest { private static final Long LAST_ATTACH_TIMESTAMP = 1453293600000L; private static final Long LAST_DETACH_TIMESTAMP = 1453293660000L; private static final StandardDiskConfiguration DISK_CONFIGURATION = - StandardDiskConfiguration.builder() - .sizeGb(SIZE_GB) - .diskType(TYPE) + StandardDiskConfiguration.newBuilder() + .setSizeGb(SIZE_GB) + .setDiskType(TYPE) .build(); private static final SnapshotDiskConfiguration SNAPSHOT_DISK_CONFIGURATION = - SnapshotDiskConfiguration.builder(SNAPSHOT) - .sizeGb(SIZE_GB) - .diskType(TYPE) - .sourceSnapshotId(SNAPSHOT_ID) + SnapshotDiskConfiguration.newBuilder(SNAPSHOT) + .setSizeGb(SIZE_GB) + .setDiskType(TYPE) + .setSourceSnapshotId(SNAPSHOT_ID) .build(); private static final ImageDiskConfiguration IMAGE_DISK_CONFIGURATION = - ImageDiskConfiguration.builder(IMAGE) - .sizeGb(SIZE_GB) - .diskType(TYPE) - .sourceImageId(IMAGE_ID) + ImageDiskConfiguration.newBuilder(IMAGE) + .setSizeGb(SIZE_GB) + .setDiskType(TYPE) + .setSourceImageId(IMAGE_ID) .build(); private final Compute serviceMockReturnsOptions = createStrictMock(Compute.class); @@ -83,46 +83,46 @@ private void initializeExpectedDisk(int optionsCalls) { expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); standardDisk = new Disk.Builder(serviceMockReturnsOptions, DISK_ID, DISK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .creationStatus(CREATION_STATUS) - .description(DESCRIPTION) - .licenses(LICENSES) - .attachedInstances(ATTACHED_INSTANCES) - .lastAttachTimestamp(LAST_ATTACH_TIMESTAMP) - .lastDetachTimestamp(LAST_DETACH_TIMESTAMP) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setCreationStatus(CREATION_STATUS) + .setDescription(DESCRIPTION) + .setLicenses(LICENSES) + .setAttachedInstances(ATTACHED_INSTANCES) + .setLastAttachTimestamp(LAST_ATTACH_TIMESTAMP) + .setLastDetachTimestamp(LAST_DETACH_TIMESTAMP) .build(); snapshotDisk = new Disk.Builder(serviceMockReturnsOptions, DISK_ID, SNAPSHOT_DISK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .creationStatus(CREATION_STATUS) - .description(DESCRIPTION) - .licenses(LICENSES) - .attachedInstances(ATTACHED_INSTANCES) - .lastAttachTimestamp(LAST_ATTACH_TIMESTAMP) - .lastDetachTimestamp(LAST_DETACH_TIMESTAMP) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setCreationStatus(CREATION_STATUS) + .setDescription(DESCRIPTION) + .setLicenses(LICENSES) + .setAttachedInstances(ATTACHED_INSTANCES) + .setLastAttachTimestamp(LAST_ATTACH_TIMESTAMP) + .setLastDetachTimestamp(LAST_DETACH_TIMESTAMP) .build(); imageDisk = new Disk.Builder(serviceMockReturnsOptions, DISK_ID, IMAGE_DISK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .creationStatus(CREATION_STATUS) - .description(DESCRIPTION) - .licenses(LICENSES) - .attachedInstances(ATTACHED_INSTANCES) - .lastAttachTimestamp(LAST_ATTACH_TIMESTAMP) - .lastDetachTimestamp(LAST_DETACH_TIMESTAMP) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setCreationStatus(CREATION_STATUS) + .setDescription(DESCRIPTION) + .setLicenses(LICENSES) + .setAttachedInstances(ATTACHED_INSTANCES) + .setLastAttachTimestamp(LAST_ATTACH_TIMESTAMP) + .setLastDetachTimestamp(LAST_DETACH_TIMESTAMP) .build(); compute = createStrictMock(Compute.class); } private void initializeDisk() { disk = new Disk.Builder(compute, DISK_ID, DISK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .creationStatus(CREATION_STATUS) - .description(DESCRIPTION) - .licenses(LICENSES) - .attachedInstances(ATTACHED_INSTANCES) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setCreationStatus(CREATION_STATUS) + .setDescription(DESCRIPTION) + .setLicenses(LICENSES) + .setAttachedInstances(ATTACHED_INSTANCES) .build(); } @@ -132,9 +132,9 @@ public void testToBuilder() { compareDisk(standardDisk, standardDisk.toBuilder().build()); compareDisk(imageDisk, imageDisk.toBuilder().build()); compareDisk(snapshotDisk, snapshotDisk.toBuilder().build()); - Disk newDisk = standardDisk.toBuilder().description("newDescription").build(); - assertEquals("newDescription", newDisk.description()); - newDisk = newDisk.toBuilder().description("description").build(); + Disk newDisk = standardDisk.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", newDisk.getDescription()); + newDisk = newDisk.toBuilder().setDescription("description").build(); compareDisk(standardDisk, newDisk); } @@ -154,6 +154,59 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { + initializeExpectedDisk(4); + assertEquals(DISK_ID, standardDisk.getDiskId()); + assertEquals(GENERATED_ID, standardDisk.getGeneratedId()); + assertEquals(DISK_CONFIGURATION, standardDisk.getConfiguration()); + assertEquals(CREATION_TIMESTAMP, standardDisk.getCreationTimestamp()); + assertEquals(CREATION_STATUS, standardDisk.getCreationStatus()); + assertEquals(DESCRIPTION, standardDisk.getDescription()); + assertEquals(LICENSES, standardDisk.getLicenses()); + assertEquals(ATTACHED_INSTANCES, standardDisk.getAttachedInstances()); + assertEquals(LAST_ATTACH_TIMESTAMP, standardDisk.getLastAttachTimestamp()); + assertEquals(LAST_DETACH_TIMESTAMP, standardDisk.getLastDetachTimestamp()); + assertSame(serviceMockReturnsOptions, standardDisk.getCompute()); + assertEquals(DISK_ID, imageDisk.getDiskId()); + assertEquals(GENERATED_ID, imageDisk.getGeneratedId()); + assertEquals(IMAGE_DISK_CONFIGURATION, imageDisk.getConfiguration()); + assertEquals(CREATION_TIMESTAMP, imageDisk.getCreationTimestamp()); + assertEquals(CREATION_STATUS, imageDisk.getCreationStatus()); + assertEquals(DESCRIPTION, imageDisk.getDescription()); + assertEquals(LICENSES, imageDisk.getLicenses()); + assertEquals(ATTACHED_INSTANCES, imageDisk.getAttachedInstances()); + assertEquals(LAST_ATTACH_TIMESTAMP, imageDisk.getLastAttachTimestamp()); + assertEquals(LAST_DETACH_TIMESTAMP, imageDisk.getLastDetachTimestamp()); + assertSame(serviceMockReturnsOptions, imageDisk.getCompute()); + assertEquals(DISK_ID, snapshotDisk.getDiskId()); + assertEquals(GENERATED_ID, snapshotDisk.getGeneratedId()); + assertEquals(SNAPSHOT_DISK_CONFIGURATION, snapshotDisk.getConfiguration()); + assertEquals(CREATION_TIMESTAMP, snapshotDisk.getCreationTimestamp()); + assertEquals(CREATION_STATUS, snapshotDisk.getCreationStatus()); + assertEquals(DESCRIPTION, snapshotDisk.getDescription()); + assertEquals(LICENSES, snapshotDisk.getLicenses()); + assertEquals(ATTACHED_INSTANCES, snapshotDisk.getAttachedInstances()); + assertEquals(LAST_ATTACH_TIMESTAMP, snapshotDisk.getLastAttachTimestamp()); + assertEquals(LAST_DETACH_TIMESTAMP, snapshotDisk.getLastDetachTimestamp()); + assertSame(serviceMockReturnsOptions, snapshotDisk.getCompute()); + Disk disk = new Disk.Builder(serviceMockReturnsOptions, DISK_ID, DISK_CONFIGURATION) + .setDiskId(DiskId.of("newProject", "newZone")) + .setConfiguration(SNAPSHOT_DISK_CONFIGURATION) + .build(); + assertEquals(DiskId.of("newProject", "newZone"), disk.getDiskId()); + assertNull(disk.getGeneratedId()); + assertEquals(SNAPSHOT_DISK_CONFIGURATION, disk.getConfiguration()); + assertNull(disk.getCreationTimestamp()); + assertNull(disk.getCreationStatus()); + assertNull(disk.getDescription()); + assertNull(disk.getLicenses()); + assertNull(disk.getAttachedInstances()); + assertNull(disk.getLastAttachTimestamp()); + assertNull(disk.getLastDetachTimestamp()); + assertSame(serviceMockReturnsOptions, disk.getCompute()); + } + + @Test + public void testBuilderDeprecated() { initializeExpectedDisk(4); assertEquals(DISK_ID, standardDisk.diskId()); assertEquals(GENERATED_ID, standardDisk.generatedId()); @@ -225,7 +278,7 @@ public void testDeleteOperation() { initializeExpectedDisk(4); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "zone", "op")) + .setOperationId(ZoneOperationId.of("project", "zone", "op")) .build(); expect(compute.deleteDisk(DISK_ID)).andReturn(operation); replay(compute); @@ -307,14 +360,14 @@ public void testCreateSnapshot() { initializeExpectedDisk(4); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "zone", "op")) + .setOperationId(ZoneOperationId.of("project", "zone", "op")) .build(); - SnapshotId snapshotId = SnapshotId.of(SNAPSHOT.snapshot()); - SnapshotInfo snapshot = SnapshotInfo.builder(snapshotId, DISK_ID).build(); + SnapshotId snapshotId = SnapshotId.of(SNAPSHOT.getSnapshot()); + SnapshotInfo snapshot = SnapshotInfo.newBuilder(snapshotId, DISK_ID).build(); expect(compute.create(snapshot)).andReturn(operation); replay(compute); initializeDisk(); - assertSame(operation, disk.createSnapshot(SNAPSHOT.snapshot())); + assertSame(operation, disk.createSnapshot(SNAPSHOT.getSnapshot())); } @Test @@ -322,16 +375,16 @@ public void testCreateSnapshotWithDescription() { initializeExpectedDisk(4); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "zone", "op")) + .setOperationId(ZoneOperationId.of("project", "zone", "op")) .build(); - SnapshotId snapshotId = SnapshotId.of(SNAPSHOT.snapshot()); - SnapshotInfo snapshot = SnapshotInfo.builder(snapshotId, DISK_ID) - .description("description") + SnapshotId snapshotId = SnapshotId.of(SNAPSHOT.getSnapshot()); + SnapshotInfo snapshot = SnapshotInfo.newBuilder(snapshotId, DISK_ID) + .setDescription("description") .build(); expect(compute.create(snapshot)).andReturn(operation); replay(compute); initializeDisk(); - assertSame(operation, disk.createSnapshot(SNAPSHOT.snapshot(), "description")); + assertSame(operation, disk.createSnapshot(SNAPSHOT.getSnapshot(), "description")); } @Test @@ -339,15 +392,15 @@ public void testCreateSnapshotWithOptions() { initializeExpectedDisk(4); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "zone", "op")) + .setOperationId(ZoneOperationId.of("project", "zone", "op")) .build(); - SnapshotId snapshotId = SnapshotId.of(SNAPSHOT.snapshot()); - SnapshotInfo snapshot = SnapshotInfo.builder(snapshotId, DISK_ID).build(); + SnapshotId snapshotId = SnapshotId.of(SNAPSHOT.getSnapshot()); + SnapshotInfo snapshot = SnapshotInfo.newBuilder(snapshotId, DISK_ID).build(); expect(compute.create(snapshot, Compute.OperationOption.fields())).andReturn(operation); replay(compute); initializeDisk(); assertSame(operation, - disk.createSnapshot(SNAPSHOT.snapshot(), Compute.OperationOption.fields())); + disk.createSnapshot(SNAPSHOT.getSnapshot(), Compute.OperationOption.fields())); } @Test @@ -355,17 +408,17 @@ public void testCreateSnapshotWithDescriptionAndOptions() { initializeExpectedDisk(4); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "zone", "op")) + .setOperationId(ZoneOperationId.of("project", "zone", "op")) .build(); - SnapshotId snapshotId = SnapshotId.of(SNAPSHOT.snapshot()); - SnapshotInfo snapshot = SnapshotInfo.builder(snapshotId, DISK_ID) - .description("description") + SnapshotId snapshotId = SnapshotId.of(SNAPSHOT.getSnapshot()); + SnapshotInfo snapshot = SnapshotInfo.newBuilder(snapshotId, DISK_ID) + .setDescription("description") .build(); expect(compute.create(snapshot, Compute.OperationOption.fields())).andReturn(operation); replay(compute); initializeDisk(); assertSame(operation, - disk.createSnapshot(SNAPSHOT.snapshot(), "description", Compute.OperationOption.fields())); + disk.createSnapshot(SNAPSHOT.getSnapshot(), "description", Compute.OperationOption.fields())); } @Test @@ -373,14 +426,14 @@ public void testCreateImage() { initializeExpectedDisk(4); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(GlobalOperationId.of("project", "op")) + .setOperationId(GlobalOperationId.of("project", "op")) .build(); - ImageId imageId = ImageId.of(IMAGE.image()); + ImageId imageId = ImageId.of(IMAGE.getImage()); ImageInfo image = ImageInfo.of(imageId, DiskImageConfiguration.of(DISK_ID)); expect(compute.create(image)).andReturn(operation); replay(compute); initializeDisk(); - assertSame(operation, disk.createImage(IMAGE.image())); + assertSame(operation, disk.createImage(IMAGE.getImage())); } @Test @@ -388,16 +441,16 @@ public void testCreateImageWithDescription() { initializeExpectedDisk(4); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(GlobalOperationId.of("project", "op")) + .setOperationId(GlobalOperationId.of("project", "op")) .build(); - ImageId imageId = ImageId.of(IMAGE.image()); - ImageInfo image = ImageInfo.builder(imageId, DiskImageConfiguration.of(DISK_ID)) - .description("description") + ImageId imageId = ImageId.of(IMAGE.getImage()); + ImageInfo image = ImageInfo.newBuilder(imageId, DiskImageConfiguration.of(DISK_ID)) + .setDescription("description") .build(); expect(compute.create(image)).andReturn(operation); replay(compute); initializeDisk(); - assertSame(operation, disk.createImage(IMAGE.image(), "description")); + assertSame(operation, disk.createImage(IMAGE.getImage(), "description")); } @Test @@ -405,14 +458,14 @@ public void testCreateImageWithOptions() { initializeExpectedDisk(4); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(GlobalOperationId.of("project", "op")) + .setOperationId(GlobalOperationId.of("project", "op")) .build(); - ImageId imageId = ImageId.of(IMAGE.image()); + ImageId imageId = ImageId.of(IMAGE.getImage()); ImageInfo image = ImageInfo.of(imageId, DiskImageConfiguration.of(DISK_ID)); expect(compute.create(image, Compute.OperationOption.fields())).andReturn(operation); replay(compute); initializeDisk(); - assertSame(operation, disk.createImage(IMAGE.image(), Compute.OperationOption.fields())); + assertSame(operation, disk.createImage(IMAGE.getImage(), Compute.OperationOption.fields())); } @Test @@ -420,17 +473,17 @@ public void testCreateImageWithDescriptionAndOptions() { initializeExpectedDisk(4); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(GlobalOperationId.of("project", "op")) + .setOperationId(GlobalOperationId.of("project", "op")) .build(); - ImageId imageId = ImageId.of(IMAGE.image()); - ImageInfo image = ImageInfo.builder(imageId, DiskImageConfiguration.of(DISK_ID)) - .description("description") + ImageId imageId = ImageId.of(IMAGE.getImage()); + ImageInfo image = ImageInfo.newBuilder(imageId, DiskImageConfiguration.of(DISK_ID)) + .setDescription("description") .build(); expect(compute.create(image, Compute.OperationOption.fields())).andReturn(operation); replay(compute); initializeDisk(); assertSame(operation, - disk.createImage(IMAGE.image(), "description", Compute.OperationOption.fields())); + disk.createImage(IMAGE.getImage(), "description", Compute.OperationOption.fields())); } @Test @@ -438,7 +491,7 @@ public void testResizeOperation() { initializeExpectedDisk(4); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "zone", "op")) + .setOperationId(ZoneOperationId.of("project", "zone", "op")) .build(); expect(compute.resize(DISK_ID, 42L)).andReturn(operation); replay(compute); @@ -458,17 +511,17 @@ public void testResizeNull() { public void compareDisk(Disk expected, Disk value) { assertEquals(expected, value); - assertEquals(expected.compute().options(), value.compute().options()); - assertEquals(expected.diskId(), value.diskId()); - assertEquals(expected.configuration(), value.configuration()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.creationStatus(), value.creationStatus()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.licenses(), value.licenses()); - assertEquals(expected.attachedInstances(), value.attachedInstances()); - assertEquals(expected.lastAttachTimestamp(), value.lastAttachTimestamp()); - assertEquals(expected.lastDetachTimestamp(), value.lastDetachTimestamp()); + assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getDiskId(), value.getDiskId()); + assertEquals(expected.getConfiguration(), value.getConfiguration()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getCreationStatus(), value.getCreationStatus()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getLicenses(), value.getLicenses()); + assertEquals(expected.getAttachedInstances(), value.getAttachedInstances()); + assertEquals(expected.getLastAttachTimestamp(), value.getLastAttachTimestamp()); + assertEquals(expected.getLastDetachTimestamp(), value.getLastDetachTimestamp()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTypeIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTypeIdTest.java index ac6788329a32..6483c3d70e07 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTypeIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTypeIdTest.java @@ -39,6 +39,19 @@ public class DiskTypeIdTest { @Test public void testOf() { + DiskTypeId diskTypeId = DiskTypeId.of(PROJECT, ZONE, DISK_TYPE); + assertEquals(PROJECT, diskTypeId.getProject()); + assertEquals(ZONE, diskTypeId.getZone()); + assertEquals(DISK_TYPE, diskTypeId.getType()); + assertEquals(URL, diskTypeId.getSelfLink()); + diskTypeId = DiskTypeId.of(ZONE, DISK_TYPE); + assertNull(diskTypeId.getProject()); + assertEquals(ZONE, diskTypeId.getZone()); + assertEquals(DISK_TYPE, diskTypeId.getType()); + } + + @Test + public void testOfDeprecated() { DiskTypeId diskTypeId = DiskTypeId.of(PROJECT, ZONE, DISK_TYPE); assertEquals(PROJECT, diskTypeId.project()); assertEquals(ZONE, diskTypeId.zone()); @@ -54,7 +67,7 @@ public void testOf() { public void testToAndFromUrl() { DiskTypeId diskTypeId = DiskTypeId.of(PROJECT, ZONE, DISK_TYPE); assertSame(diskTypeId, diskTypeId.setProjectId(PROJECT)); - compareDiskTypeId(diskTypeId, DiskTypeId.fromUrl(diskTypeId.selfLink())); + compareDiskTypeId(diskTypeId, DiskTypeId.fromUrl(diskTypeId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid disk type URL"); DiskTypeId.fromUrl("notMatchingUrl"); @@ -69,16 +82,16 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(DiskTypeId.matchesUrl(DiskTypeId.of(PROJECT, ZONE, DISK_TYPE).selfLink())); + assertTrue(DiskTypeId.matchesUrl(DiskTypeId.of(PROJECT, ZONE, DISK_TYPE).getSelfLink())); assertFalse(DiskTypeId.matchesUrl("notMatchingUrl")); } private void compareDiskTypeId(DiskTypeId expected, DiskTypeId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.zone(), expected.zone()); - assertEquals(expected.type(), expected.type()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getZone(), expected.getZone()); + assertEquals(expected.getType(), expected.getType()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTypeTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTypeTest.java index 691d1fcd336d..f0a8747b0880 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTypeTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTypeTest.java @@ -30,18 +30,29 @@ public class DiskTypeTest { private static final DiskTypeId DISK_TYPE_ID = DiskTypeId.of("project", "zone", "diskType"); private static final DeprecationStatus DEPRECATION_STATUS = DeprecationStatus.of(DeprecationStatus.Status.DELETED, DISK_TYPE_ID); - private static final DiskType DISK_TYPE = DiskType.builder() - .generatedId(GENERATED_ID) - .diskTypeId(DISK_TYPE_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .validDiskSize(VALID_DISK_SIZE) - .defaultDiskSizeGb(DEFAULT_DISK_SIZE_GB) - .deprecationStatus(DEPRECATION_STATUS) + private static final DiskType DISK_TYPE = DiskType.newBuilder() + .setGeneratedId(GENERATED_ID) + .setDiskTypeId(DISK_TYPE_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setValidDiskSize(VALID_DISK_SIZE) + .setDefaultDiskSizeGb(DEFAULT_DISK_SIZE_GB) + .setDeprecationStatus(DEPRECATION_STATUS) .build(); @Test public void testBuilder() { + assertEquals(GENERATED_ID, DISK_TYPE.getGeneratedId()); + assertEquals(DISK_TYPE_ID, DISK_TYPE.getDiskTypeId()); + assertEquals(CREATION_TIMESTAMP, DISK_TYPE.getCreationTimestamp()); + assertEquals(DESCRIPTION, DISK_TYPE.getDescription()); + assertEquals(VALID_DISK_SIZE, DISK_TYPE.getValidDiskSize()); + assertEquals(DEFAULT_DISK_SIZE_GB, DISK_TYPE.getDefaultDiskSizeGb()); + assertEquals(DEPRECATION_STATUS, DISK_TYPE.getDeprecationStatus()); + } + + @Test + public void testBuilderDeprecated() { assertEquals(GENERATED_ID, DISK_TYPE.generatedId()); assertEquals(DISK_TYPE_ID, DISK_TYPE.diskTypeId()); assertEquals(CREATION_TIMESTAMP, DISK_TYPE.creationTimestamp()); @@ -54,19 +65,19 @@ public void testBuilder() { @Test public void testToPbAndFromPb() { compareDiskTypes(DISK_TYPE, DiskType.fromPb(DISK_TYPE.toPb())); - DiskType diskType = DiskType.builder().diskTypeId(DISK_TYPE_ID).build(); + DiskType diskType = DiskType.newBuilder().setDiskTypeId(DISK_TYPE_ID).build(); compareDiskTypes(diskType, DiskType.fromPb(diskType.toPb())); } private void compareDiskTypes(DiskType expected, DiskType value) { assertEquals(expected, value); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.diskTypeId(), value.diskTypeId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.validDiskSize(), value.validDiskSize()); - assertEquals(expected.defaultDiskSizeGb(), value.defaultDiskSizeGb()); - assertEquals(expected.deprecationStatus(), value.deprecationStatus()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getDiskTypeId(), value.getDiskTypeId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getValidDiskSize(), value.getValidDiskSize()); + assertEquals(expected.getDefaultDiskSizeGb(), value.getDefaultDiskSizeGb()); + assertEquals(expected.getDeprecationStatus(), value.getDeprecationStatus()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/ForwardingRuleIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/ForwardingRuleIdTest.java index 3afc0c187c05..b3c7aad52b12 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/ForwardingRuleIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/ForwardingRuleIdTest.java @@ -41,6 +41,37 @@ public class ForwardingRuleIdTest { @Test public void testOf() { + GlobalForwardingRuleId forwardingRuleId = GlobalForwardingRuleId.of(PROJECT, NAME); + assertEquals(PROJECT, forwardingRuleId.getProject()); + assertEquals(NAME, forwardingRuleId.getRule()); + assertEquals(GLOBAL_URL, forwardingRuleId.getSelfLink()); + assertEquals(ForwardingRuleId.Type.GLOBAL, forwardingRuleId.getType()); + forwardingRuleId = GlobalForwardingRuleId.of(NAME); + assertNull(forwardingRuleId.getProject()); + assertEquals(NAME, forwardingRuleId.getRule()); + assertEquals(ForwardingRuleId.Type.GLOBAL, forwardingRuleId.getType()); + RegionForwardingRuleId regionForwardingRuleId = + RegionForwardingRuleId.of(PROJECT, REGION, NAME); + assertEquals(PROJECT, regionForwardingRuleId.getProject()); + assertEquals(REGION, regionForwardingRuleId.getRegion()); + assertEquals(NAME, regionForwardingRuleId.getRule()); + assertEquals(REGION_URL, regionForwardingRuleId.getSelfLink()); + assertEquals(ForwardingRuleId.Type.REGION, regionForwardingRuleId.getType()); + regionForwardingRuleId = RegionForwardingRuleId.of(RegionId.of(PROJECT, REGION), NAME); + assertEquals(PROJECT, regionForwardingRuleId.getProject()); + assertEquals(REGION, regionForwardingRuleId.getRegion()); + assertEquals(NAME, regionForwardingRuleId.getRule()); + assertEquals(REGION_URL, regionForwardingRuleId.getSelfLink()); + assertEquals(ForwardingRuleId.Type.REGION, regionForwardingRuleId.getType()); + regionForwardingRuleId = RegionForwardingRuleId.of(REGION, NAME); + assertNull(regionForwardingRuleId.getProject()); + assertEquals(REGION, regionForwardingRuleId.getRegion()); + assertEquals(NAME, regionForwardingRuleId.getRule()); + assertEquals(ForwardingRuleId.Type.REGION, regionForwardingRuleId.getType()); + } + + @Test + public void testOfDeprecated() { GlobalForwardingRuleId forwardingRuleId = GlobalForwardingRuleId.of(PROJECT, NAME); assertEquals(PROJECT, forwardingRuleId.project()); assertEquals(NAME, forwardingRuleId.rule()); @@ -74,11 +105,11 @@ public void testOf() { public void testToAndFromUrlGlobal() { GlobalForwardingRuleId forwardingRuleId = GlobalForwardingRuleId.of(PROJECT, NAME); compareGlobalForwardingRuleId(forwardingRuleId, - GlobalForwardingRuleId.fromUrl(forwardingRuleId.selfLink())); + GlobalForwardingRuleId.fromUrl(forwardingRuleId.getSelfLink())); RegionForwardingRuleId regionForwardingRuleId = RegionForwardingRuleId.of(PROJECT, REGION, NAME); compareRegionForwardingRuleId(regionForwardingRuleId, - RegionForwardingRuleId.fromUrl(regionForwardingRuleId.selfLink())); + RegionForwardingRuleId.fromUrl(regionForwardingRuleId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid global forwarding rule URL"); GlobalForwardingRuleId.fromUrl("notMatchingUrl"); @@ -89,7 +120,7 @@ public void testToAndFromUrlRegion() { RegionForwardingRuleId regionForwardingRuleId = RegionForwardingRuleId.of(PROJECT, REGION, NAME); compareRegionForwardingRuleId(regionForwardingRuleId, - RegionForwardingRuleId.fromUrl(regionForwardingRuleId.selfLink())); + RegionForwardingRuleId.fromUrl(regionForwardingRuleId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid region forwarding rule URL"); RegionForwardingRuleId.fromUrl("notMatchingUrl"); @@ -111,29 +142,29 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { assertTrue(GlobalForwardingRuleId.matchesUrl( - GlobalForwardingRuleId.of(PROJECT, NAME).selfLink())); + GlobalForwardingRuleId.of(PROJECT, NAME).getSelfLink())); assertFalse(GlobalForwardingRuleId.matchesUrl("notMatchingUrl")); assertTrue(RegionForwardingRuleId.matchesUrl( - RegionForwardingRuleId.of(PROJECT, REGION, NAME).selfLink())); + RegionForwardingRuleId.of(PROJECT, REGION, NAME).getSelfLink())); assertFalse(RegionForwardingRuleId.matchesUrl("notMatchingUrl")); } private void compareGlobalForwardingRuleId(GlobalForwardingRuleId expected, GlobalForwardingRuleId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.rule(), expected.rule()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getRule(), expected.getRule()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } private void compareRegionForwardingRuleId(RegionForwardingRuleId expected, RegionForwardingRuleId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.region(), expected.region()); - assertEquals(expected.rule(), expected.rule()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getRegion(), expected.getRegion()); + assertEquals(expected.getRule(), expected.getRule()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageDiskConfigurationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageDiskConfigurationTest.java index db8974ddeee4..4fcd856d544c 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageDiskConfigurationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageDiskConfigurationTest.java @@ -31,10 +31,16 @@ public class ImageDiskConfigurationTest { private static final ImageId IMAGE = ImageId.of("project", "image"); private static final String IMAGE_ID = "imageId"; private static final ImageDiskConfiguration DISK_CONFIGURATION = + ImageDiskConfiguration.newBuilder(IMAGE) + .setSizeGb(SIZE) + .setDiskType(DISK_TYPE) + .setSourceImageId(IMAGE_ID) + .build(); + private static final ImageDiskConfiguration DEPRECATED_DISK_CONFIGURATION = ImageDiskConfiguration.builder(IMAGE) .sizeGb(SIZE) .diskType(DISK_TYPE) - .sourceImageId(IMAGE_ID) + .setSourceImageId(IMAGE_ID) .build(); @Test @@ -42,17 +48,17 @@ public void testToBuilder() { compareImageDiskConfiguration(DISK_CONFIGURATION, DISK_CONFIGURATION.toBuilder().build()); ImageId newImageId = ImageId.of("newProject", "newImage"); ImageDiskConfiguration diskConfiguration = DISK_CONFIGURATION.toBuilder() - .sizeGb(24L) - .sourceImage(newImageId) - .sourceImageId("newImageId") + .setSizeGb(24L) + .setSourceImage(newImageId) + .setSourceImageId("newImageId") .build(); - assertEquals(24L, diskConfiguration.sizeGb().longValue()); - assertEquals(newImageId, diskConfiguration.sourceImage()); - assertEquals("newImageId", diskConfiguration.sourceImageId()); + assertEquals(24L, diskConfiguration.getSizeGb().longValue()); + assertEquals(newImageId, diskConfiguration.getSourceImage()); + assertEquals("newImageId", diskConfiguration.getSourceImageId()); diskConfiguration = diskConfiguration.toBuilder() - .sizeGb(SIZE) - .sourceImage(IMAGE) - .sourceImageId(IMAGE_ID) + .setSizeGb(SIZE) + .setSourceImage(IMAGE) + .setSourceImageId(IMAGE_ID) .build(); compareImageDiskConfiguration(DISK_CONFIGURATION, diskConfiguration); } @@ -65,11 +71,20 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(DISK_TYPE, DISK_CONFIGURATION.diskType()); - assertEquals(SIZE, DISK_CONFIGURATION.sizeGb()); - assertEquals(IMAGE, DISK_CONFIGURATION.sourceImage()); - assertEquals(IMAGE_ID, DISK_CONFIGURATION.sourceImageId()); - assertEquals(Type.IMAGE, DISK_CONFIGURATION.type()); + assertEquals(DISK_TYPE, DISK_CONFIGURATION.getDiskType()); + assertEquals(SIZE, DISK_CONFIGURATION.getSizeGb()); + assertEquals(IMAGE, DISK_CONFIGURATION.getSourceImage()); + assertEquals(IMAGE_ID, DISK_CONFIGURATION.getSourceImageId()); + assertEquals(Type.IMAGE, DISK_CONFIGURATION.getType()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(DISK_TYPE, DEPRECATED_DISK_CONFIGURATION.diskType()); + assertEquals(SIZE, DEPRECATED_DISK_CONFIGURATION.sizeGb()); + assertEquals(IMAGE, DEPRECATED_DISK_CONFIGURATION.sourceImage()); + assertEquals(IMAGE_ID, DEPRECATED_DISK_CONFIGURATION.sourceImageId()); + assertEquals(Type.IMAGE, DEPRECATED_DISK_CONFIGURATION.type()); } @Test @@ -83,18 +98,18 @@ public void testToAndFromPb() { @Test public void testOf() { ImageDiskConfiguration configuration = ImageDiskConfiguration.of(IMAGE); - assertNull(configuration.diskType()); - assertNull(configuration.sizeGb()); - assertNull(configuration.sourceImageId()); - assertEquals(IMAGE, configuration.sourceImage()); - assertEquals(Type.IMAGE, configuration.type()); + assertNull(configuration.getDiskType()); + assertNull(configuration.getSizeGb()); + assertNull(configuration.getSourceImageId()); + assertEquals(IMAGE, configuration.getSourceImage()); + assertEquals(Type.IMAGE, configuration.getType()); } @Test public void testSetProjectId() { ImageDiskConfiguration diskConfiguration = DISK_CONFIGURATION.toBuilder() - .diskType(DiskTypeId.of(DISK_TYPE.zone(), DISK_TYPE.type())) - .sourceImage(ImageId.of(IMAGE.image())) + .setDiskType(DiskTypeId.of(DISK_TYPE.getZone(), DISK_TYPE.getType())) + .setSourceImage(ImageId.of(IMAGE.getImage())) .build(); compareImageDiskConfiguration(DISK_CONFIGURATION, diskConfiguration.setProjectId("project")); } @@ -102,11 +117,11 @@ public void testSetProjectId() { private void compareImageDiskConfiguration(ImageDiskConfiguration expected, ImageDiskConfiguration value) { assertEquals(expected, value); - assertEquals(expected.diskType(), value.diskType()); - assertEquals(expected.sizeGb(), value.sizeGb()); - assertEquals(expected.sourceImage(), value.sourceImage()); - assertEquals(expected.sourceImageId(), value.sourceImageId()); - assertEquals(expected.type(), value.type()); + assertEquals(expected.getDiskType(), value.getDiskType()); + assertEquals(expected.getSizeGb(), value.getSizeGb()); + assertEquals(expected.getSourceImage(), value.getSourceImage()); + assertEquals(expected.getSourceImageId(), value.getSourceImageId()); + assertEquals(expected.getType(), value.getType()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageIdTest.java index 32f8ac7c024b..a773ea1942fb 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageIdTest.java @@ -38,6 +38,17 @@ public class ImageIdTest { @Test public void testOf() { + ImageId imageId = ImageId.of(PROJECT, NAME); + assertEquals(PROJECT, imageId.getProject()); + assertEquals(NAME, imageId.getImage()); + assertEquals(URL, imageId.getSelfLink()); + imageId = ImageId.of(NAME); + assertNull(imageId.getProject()); + assertEquals(NAME, imageId.getImage()); + } + + @Test + public void testOfDeprecated() { ImageId imageId = ImageId.of(PROJECT, NAME); assertEquals(PROJECT, imageId.project()); assertEquals(NAME, imageId.image()); @@ -50,7 +61,7 @@ public void testOf() { @Test public void testToAndFromUrl() { ImageId imageId = ImageId.of(PROJECT, NAME); - compareImageId(imageId, ImageId.fromUrl(imageId.selfLink())); + compareImageId(imageId, ImageId.fromUrl(imageId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid image URL"); ImageId.fromUrl("notMatchingUrl"); @@ -65,15 +76,15 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(ImageId.matchesUrl(ImageId.of(PROJECT, NAME).selfLink())); + assertTrue(ImageId.matchesUrl(ImageId.of(PROJECT, NAME).getSelfLink())); assertFalse(ImageId.matchesUrl("notMatchingUrl")); } private void compareImageId(ImageId expected, ImageId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.image(), expected.image()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getImage(), expected.getImage()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageInfoTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageInfoTest.java index 4433fbe96ffb..131fc55929da 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageInfoTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageInfoTest.java @@ -43,46 +43,68 @@ public class ImageInfoTest { private static final String SOURCE_DISK_ID = "diskId"; private static final SourceType SOURCE_TYPE = SourceType.RAW; private static final StorageImageConfiguration STORAGE_CONFIGURATION = - StorageImageConfiguration.builder(STORAGE_SOURCE) - .archiveSizeBytes(ARCHIVE_SIZE_BYTES) - .containerType(StorageImageConfiguration.ContainerType.TAR) - .sha1(SHA1_CHECKSUM) - .sourceType(SOURCE_TYPE) + StorageImageConfiguration.newBuilder(STORAGE_SOURCE) + .setArchiveSizeBytes(ARCHIVE_SIZE_BYTES) + .setContainerType(StorageImageConfiguration.ContainerType.TAR) + .setSha1(SHA1_CHECKSUM) + .setSourceType(SOURCE_TYPE) .build(); private static final DiskImageConfiguration DISK_CONFIGURATION = - DiskImageConfiguration.builder(SOURCE_DISK) - .archiveSizeBytes(ARCHIVE_SIZE_BYTES) - .sourceDiskId(SOURCE_DISK_ID) - .sourceType(SOURCE_TYPE) + DiskImageConfiguration.newBuilder(SOURCE_DISK) + .setArchiveSizeBytes(ARCHIVE_SIZE_BYTES) + .setSourceDiskId(SOURCE_DISK_ID) + .setSourceType(SOURCE_TYPE) .build(); private static final DeprecationStatus DEPRECATION_STATUS = DeprecationStatus.of(DeprecationStatus.Status.DELETED, IMAGE_ID); - private static final ImageInfo STORAGE_IMAGE = ImageInfo.builder(IMAGE_ID, STORAGE_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .diskSizeGb(DISK_SIZE_GB) - .licenses(LICENSES) - .deprecationStatus(DEPRECATION_STATUS) - .build(); - private static final ImageInfo DISK_IMAGE = ImageInfo.builder(IMAGE_ID, DISK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .diskSizeGb(DISK_SIZE_GB) - .licenses(LICENSES) - .deprecationStatus(DEPRECATION_STATUS) - .build(); + private static final ImageInfo STORAGE_IMAGE = + ImageInfo.newBuilder(IMAGE_ID, STORAGE_CONFIGURATION) + .setGeneratedId(GENERATED_ID) + .getCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setDiskSizeGb(DISK_SIZE_GB) + .setLicenses(LICENSES) + .setDeprecationStatus(DEPRECATION_STATUS) + .build(); + private static final ImageInfo DISK_IMAGE = + ImageInfo.newBuilder(IMAGE_ID, DISK_CONFIGURATION) + .setGeneratedId(GENERATED_ID) + .getCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setDiskSizeGb(DISK_SIZE_GB) + .setLicenses(LICENSES) + .setDeprecationStatus(DEPRECATION_STATUS) + .build(); + private static final ImageInfo DEPRECATED_STORAGE_IMAGE = + ImageInfo.builder(IMAGE_ID, STORAGE_CONFIGURATION) + .setGeneratedId(GENERATED_ID) + .getCreationTimestamp(CREATION_TIMESTAMP) + .description(DESCRIPTION) + .setStatus(STATUS) + .setDiskSizeGb(DISK_SIZE_GB) + .setLicenses(LICENSES) + .setDeprecationStatus(DEPRECATION_STATUS) + .build(); + private static final ImageInfo DEPRECATED_DISK_IMAGE = + ImageInfo.builder(IMAGE_ID, DISK_CONFIGURATION) + .setGeneratedId(GENERATED_ID) + .getCreationTimestamp(CREATION_TIMESTAMP) + .description(DESCRIPTION) + .setStatus(STATUS) + .setDiskSizeGb(DISK_SIZE_GB) + .setLicenses(LICENSES) + .setDeprecationStatus(DEPRECATION_STATUS) + .build(); @Test public void testToBuilder() { compareImageInfo(STORAGE_IMAGE, STORAGE_IMAGE.toBuilder().build()); compareImageInfo(DISK_IMAGE, DISK_IMAGE.toBuilder().build()); - ImageInfo imageInfo = STORAGE_IMAGE.toBuilder().description("newDescription").build(); - assertEquals("newDescription", imageInfo.description()); - imageInfo = imageInfo.toBuilder().description("description").build(); + ImageInfo imageInfo = STORAGE_IMAGE.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", imageInfo.getDescription()); + imageInfo = imageInfo.toBuilder().setDescription("description").build(); compareImageInfo(STORAGE_IMAGE, imageInfo); } @@ -96,48 +118,70 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(GENERATED_ID, STORAGE_IMAGE.generatedId()); - assertEquals(IMAGE_ID, STORAGE_IMAGE.imageId()); - assertEquals(CREATION_TIMESTAMP, STORAGE_IMAGE.creationTimestamp()); - assertEquals(DESCRIPTION, STORAGE_IMAGE.description()); - assertEquals(STORAGE_CONFIGURATION, STORAGE_IMAGE.configuration()); - assertEquals(STATUS, STORAGE_IMAGE.status()); - assertEquals(DISK_SIZE_GB, STORAGE_IMAGE.diskSizeGb()); - assertEquals(LICENSES, STORAGE_IMAGE.licenses()); - assertEquals(DEPRECATION_STATUS, STORAGE_IMAGE.deprecationStatus()); - assertEquals(GENERATED_ID, DISK_IMAGE.generatedId()); - assertEquals(IMAGE_ID, DISK_IMAGE.imageId()); - assertEquals(CREATION_TIMESTAMP, DISK_IMAGE.creationTimestamp()); - assertEquals(DESCRIPTION, DISK_IMAGE.description()); - assertEquals(DISK_CONFIGURATION, DISK_IMAGE.configuration()); - assertEquals(STATUS, DISK_IMAGE.status()); - assertEquals(DISK_SIZE_GB, DISK_IMAGE.diskSizeGb()); - assertEquals(LICENSES, DISK_IMAGE.licenses()); - assertEquals(DEPRECATION_STATUS, DISK_IMAGE.deprecationStatus()); + assertEquals(GENERATED_ID, STORAGE_IMAGE.getGeneratedId()); + assertEquals(IMAGE_ID, STORAGE_IMAGE.getImageId()); + assertEquals(CREATION_TIMESTAMP, STORAGE_IMAGE.getCreationTimestamp()); + assertEquals(DESCRIPTION, STORAGE_IMAGE.getDescription()); + assertEquals(STORAGE_CONFIGURATION, STORAGE_IMAGE.getConfiguration()); + assertEquals(STATUS, STORAGE_IMAGE.getStatus()); + assertEquals(DISK_SIZE_GB, STORAGE_IMAGE.getDiskSizeGb()); + assertEquals(LICENSES, STORAGE_IMAGE.getLicenses()); + assertEquals(DEPRECATION_STATUS, STORAGE_IMAGE.getDeprecationStatus()); + assertEquals(GENERATED_ID, DISK_IMAGE.getGeneratedId()); + assertEquals(IMAGE_ID, DISK_IMAGE.getImageId()); + assertEquals(CREATION_TIMESTAMP, DISK_IMAGE.getCreationTimestamp()); + assertEquals(DESCRIPTION, DISK_IMAGE.getDescription()); + assertEquals(DISK_CONFIGURATION, DISK_IMAGE.getConfiguration()); + assertEquals(STATUS, DISK_IMAGE.getStatus()); + assertEquals(DISK_SIZE_GB, DISK_IMAGE.getDiskSizeGb()); + assertEquals(LICENSES, DISK_IMAGE.getLicenses()); + assertEquals(DEPRECATION_STATUS, DISK_IMAGE.getDeprecationStatus()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(GENERATED_ID, DEPRECATED_STORAGE_IMAGE.generatedId()); + assertEquals(IMAGE_ID, DEPRECATED_STORAGE_IMAGE.imageId()); + assertEquals(CREATION_TIMESTAMP, DEPRECATED_STORAGE_IMAGE.creationTimestamp()); + assertEquals(DESCRIPTION, DEPRECATED_STORAGE_IMAGE.description()); + assertEquals(STORAGE_CONFIGURATION, DEPRECATED_STORAGE_IMAGE.configuration()); + assertEquals(STATUS, DEPRECATED_STORAGE_IMAGE.status()); + assertEquals(DISK_SIZE_GB, DEPRECATED_STORAGE_IMAGE.diskSizeGb()); + assertEquals(LICENSES, DEPRECATED_STORAGE_IMAGE.licenses()); + assertEquals(DEPRECATION_STATUS, DEPRECATED_STORAGE_IMAGE.deprecationStatus()); + assertEquals(GENERATED_ID, DEPRECATED_DISK_IMAGE.generatedId()); + assertEquals(IMAGE_ID, DEPRECATED_DISK_IMAGE.imageId()); + assertEquals(CREATION_TIMESTAMP, DEPRECATED_DISK_IMAGE.creationTimestamp()); + assertEquals(DESCRIPTION, DEPRECATED_DISK_IMAGE.description()); + assertEquals(DISK_CONFIGURATION, DEPRECATED_DISK_IMAGE.configuration()); + assertEquals(STATUS, DEPRECATED_DISK_IMAGE.status()); + assertEquals(DISK_SIZE_GB, DEPRECATED_DISK_IMAGE.diskSizeGb()); + assertEquals(LICENSES, DEPRECATED_DISK_IMAGE.licenses()); + assertEquals(DEPRECATION_STATUS, DEPRECATED_DISK_IMAGE.deprecationStatus()); } @Test public void testOf() { ImageInfo imageInfo = ImageInfo.of(IMAGE_ID, STORAGE_CONFIGURATION); - assertEquals(IMAGE_ID, imageInfo.imageId()); - assertEquals(STORAGE_CONFIGURATION, imageInfo.configuration()); - assertNull(imageInfo.generatedId()); - assertNull(imageInfo.creationTimestamp()); - assertNull(imageInfo.description()); - assertNull(imageInfo.status()); - assertNull(imageInfo.diskSizeGb()); - assertNull(imageInfo.licenses()); - assertNull(imageInfo.deprecationStatus()); + assertEquals(IMAGE_ID, imageInfo.getImageId()); + assertEquals(STORAGE_CONFIGURATION, imageInfo.getConfiguration()); + assertNull(imageInfo.getGeneratedId()); + assertNull(imageInfo.getCreationTimestamp()); + assertNull(imageInfo.getDescription()); + assertNull(imageInfo.getStatus()); + assertNull(imageInfo.getDiskSizeGb()); + assertNull(imageInfo.getLicenses()); + assertNull(imageInfo.getDeprecationStatus()); imageInfo = ImageInfo.of(IMAGE_ID, DISK_CONFIGURATION); - assertEquals(IMAGE_ID, imageInfo.imageId()); - assertEquals(DISK_CONFIGURATION, imageInfo.configuration()); - assertNull(imageInfo.generatedId()); - assertNull(imageInfo.creationTimestamp()); - assertNull(imageInfo.description()); - assertNull(imageInfo.status()); - assertNull(imageInfo.diskSizeGb()); - assertNull(imageInfo.licenses()); - assertNull(imageInfo.deprecationStatus()); + assertEquals(IMAGE_ID, imageInfo.getImageId()); + assertEquals(DISK_CONFIGURATION, imageInfo.getConfiguration()); + assertNull(imageInfo.getGeneratedId()); + assertNull(imageInfo.getCreationTimestamp()); + assertNull(imageInfo.getDescription()); + assertNull(imageInfo.getStatus()); + assertNull(imageInfo.getDiskSizeGb()); + assertNull(imageInfo.getLicenses()); + assertNull(imageInfo.getDeprecationStatus()); } @Test @@ -153,23 +197,25 @@ public void testToAndFromPb() { @Test public void testSetProjectId() { ImageInfo imageInfo = DISK_IMAGE.toBuilder() - .imageId(ImageId.of("image")) - .configuration(DISK_CONFIGURATION.toBuilder().sourceDisk(DiskId.of("zone", "disk")).build()) + .setImageId(ImageId.of("image")) + .setConfiguration(DISK_CONFIGURATION.toBuilder() + .setSourceDisk(DiskId.of("zone", "disk")) + .build()) .build(); compareImageInfo(DISK_IMAGE, imageInfo.setProjectId("project")); } public void compareImageInfo(ImageInfo expected, ImageInfo value) { assertEquals(expected, value); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.imageId(), value.imageId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.configuration(), value.configuration()); - assertEquals(expected.status(), value.status()); - assertEquals(expected.diskSizeGb(), value.diskSizeGb()); - assertEquals(expected.licenses(), value.licenses()); - assertEquals(expected.deprecationStatus(), value.deprecationStatus()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getImageId(), value.getImageId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getConfiguration(), value.getConfiguration()); + assertEquals(expected.getStatus(), value.getStatus()); + assertEquals(expected.getDiskSizeGb(), value.getDiskSizeGb()); + assertEquals(expected.getLicenses(), value.getLicenses()); + assertEquals(expected.getDeprecationStatus(), value.getDeprecationStatus()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageTest.java index ca1cd009c5eb..2dc8694361c5 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageTest.java @@ -48,19 +48,20 @@ public class ImageTest { private static final String SHA1_CHECKSUM = "checksum"; private static final DiskId SOURCE_DISK = DiskId.of("project", "zone", "disk"); private static final String SOURCE_DISK_ID = "diskId"; - private static final ImageConfiguration.SourceType SOURCE_TYPE = ImageConfiguration.SourceType.RAW; + private static final ImageConfiguration.SourceType SOURCE_TYPE = + ImageConfiguration.SourceType.RAW; private static final StorageImageConfiguration STORAGE_CONFIGURATION = - StorageImageConfiguration.builder(STORAGE_SOURCE) - .archiveSizeBytes(ARCHIVE_SIZE_BYTES) - .containerType(StorageImageConfiguration.ContainerType.TAR) - .sha1(SHA1_CHECKSUM) - .sourceType(SOURCE_TYPE) + StorageImageConfiguration.newBuilder(STORAGE_SOURCE) + .setArchiveSizeBytes(ARCHIVE_SIZE_BYTES) + .setContainerType(StorageImageConfiguration.ContainerType.TAR) + .setSha1(SHA1_CHECKSUM) + .setSourceType(SOURCE_TYPE) .build(); private static final DiskImageConfiguration DISK_CONFIGURATION = - DiskImageConfiguration.builder(SOURCE_DISK) - .archiveSizeBytes(ARCHIVE_SIZE_BYTES) - .sourceDiskId(SOURCE_DISK_ID) - .sourceType(SOURCE_TYPE) + DiskImageConfiguration.newBuilder(SOURCE_DISK) + .setArchiveSizeBytes(ARCHIVE_SIZE_BYTES) + .setSourceDiskId(SOURCE_DISK_ID) + .setSourceType(SOURCE_TYPE) .build(); private static final DeprecationStatus DEPRECATION_STATUS = DeprecationStatus.of(DeprecationStatus.Status.DELETED, IMAGE_ID); @@ -76,35 +77,35 @@ private void initializeExpectedImage(int optionsCalls) { expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); diskImage = new Image.Builder(serviceMockReturnsOptions, IMAGE_ID, DISK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .diskSizeGb(DISK_SIZE_GB) - .licenses(LICENSES) - .deprecationStatus(DEPRECATION_STATUS) + .setGeneratedId(GENERATED_ID) + .getCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setDiskSizeGb(DISK_SIZE_GB) + .setLicenses(LICENSES) + .setDeprecationStatus(DEPRECATION_STATUS) .build(); storageImage = new Image.Builder(serviceMockReturnsOptions, IMAGE_ID, STORAGE_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .diskSizeGb(DISK_SIZE_GB) - .licenses(LICENSES) - .deprecationStatus(DEPRECATION_STATUS) + .setGeneratedId(GENERATED_ID) + .getCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setDiskSizeGb(DISK_SIZE_GB) + .setLicenses(LICENSES) + .setDeprecationStatus(DEPRECATION_STATUS) .build(); compute = createStrictMock(Compute.class); } private void initializeImage() { image = new Image.Builder(compute, IMAGE_ID, DISK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .diskSizeGb(DISK_SIZE_GB) - .licenses(LICENSES) - .deprecationStatus(DEPRECATION_STATUS) + .setGeneratedId(GENERATED_ID) + .getCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setDiskSizeGb(DISK_SIZE_GB) + .setLicenses(LICENSES) + .setDeprecationStatus(DEPRECATION_STATUS) .build(); } @@ -113,9 +114,9 @@ public void testToBuilder() { initializeExpectedImage(12); compareImage(diskImage, diskImage.toBuilder().build()); compareImage(storageImage, storageImage.toBuilder().build()); - Image newImage = diskImage.toBuilder().description("newDescription").build(); - assertEquals("newDescription", newImage.description()); - newImage = newImage.toBuilder().description("description").build(); + Image newImage = diskImage.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", newImage.getDescription()); + newImage = newImage.toBuilder().setDescription("description").build(); compareImage(diskImage, newImage); } @@ -130,6 +131,46 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { + initializeExpectedImage(3); + assertEquals(GENERATED_ID, diskImage.getGeneratedId()); + assertEquals(IMAGE_ID, diskImage.getImageId()); + assertEquals(CREATION_TIMESTAMP, diskImage.getCreationTimestamp()); + assertEquals(DESCRIPTION, diskImage.getDescription()); + assertEquals(DISK_CONFIGURATION, diskImage.getConfiguration()); + assertEquals(STATUS, diskImage.getStatus()); + assertEquals(DISK_SIZE_GB, diskImage.getDiskSizeGb()); + assertEquals(LICENSES, diskImage.getLicenses()); + assertEquals(DEPRECATION_STATUS, diskImage.getDeprecationStatus()); + assertSame(serviceMockReturnsOptions, diskImage.getCompute()); + assertEquals(GENERATED_ID, storageImage.getGeneratedId()); + assertEquals(IMAGE_ID, storageImage.getImageId()); + assertEquals(CREATION_TIMESTAMP, storageImage.getCreationTimestamp()); + assertEquals(DESCRIPTION, storageImage.getDescription()); + assertEquals(STORAGE_CONFIGURATION, storageImage.getConfiguration()); + assertEquals(STATUS, storageImage.getStatus()); + assertEquals(DISK_SIZE_GB, storageImage.getDiskSizeGb()); + assertEquals(LICENSES, storageImage.getLicenses()); + assertEquals(DEPRECATION_STATUS, storageImage.getDeprecationStatus()); + assertSame(serviceMockReturnsOptions, storageImage.getCompute()); + ImageId imageId = ImageId.of("otherImage"); + Image image = new Image.Builder(serviceMockReturnsOptions, IMAGE_ID, STORAGE_CONFIGURATION) + .setImageId(imageId) + .setConfiguration(DISK_CONFIGURATION) + .build(); + assertNull(image.getGeneratedId()); + assertEquals(imageId, image.getImageId()); + assertNull(image.getCreationTimestamp()); + assertNull(image.getDescription()); + assertEquals(DISK_CONFIGURATION, image.getConfiguration()); + assertNull(image.getStatus()); + assertNull(image.getDiskSizeGb()); + assertNull(image.getLicenses()); + assertNull(image.getDeprecationStatus()); + assertSame(serviceMockReturnsOptions, image.getCompute()); + } + + @Test + public void testBuilderDeprecated() { initializeExpectedImage(3); assertEquals(GENERATED_ID, diskImage.generatedId()); assertEquals(IMAGE_ID, diskImage.imageId()); @@ -185,7 +226,7 @@ public void testDeleteOperation() { initializeExpectedImage(3); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(GlobalOperationId.of("project", "op")) + .setOperationId(GlobalOperationId.of("project", "op")) .build(); expect(compute.deleteImage(IMAGE_ID)).andReturn(operation); replay(compute); @@ -267,9 +308,10 @@ public void testDeprecateImage() { initializeExpectedImage(3); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(GlobalOperationId.of("project", "op")) + .setOperationId(GlobalOperationId.of("project", "op")) .build(); - DeprecationStatus status = DeprecationStatus.of(DeprecationStatus.Status.DEPRECATED, IMAGE_ID); + DeprecationStatus status = + DeprecationStatus.of(DeprecationStatus.Status.DEPRECATED, IMAGE_ID); expect(compute.deprecate(IMAGE_ID, status)).andReturn(operation); replay(compute); initializeImage(); @@ -280,7 +322,8 @@ public void testDeprecateImage() { public void testDeprecateNull() { initializeExpectedImage(2); expect(compute.options()).andReturn(mockOptions); - DeprecationStatus status = DeprecationStatus.of(DeprecationStatus.Status.DEPRECATED, IMAGE_ID); + DeprecationStatus status = + DeprecationStatus.of(DeprecationStatus.Status.DEPRECATED, IMAGE_ID); expect(compute.deprecate(IMAGE_ID, status)).andReturn(null); replay(compute); initializeImage(); @@ -289,16 +332,16 @@ public void testDeprecateNull() { public void compareImage(Image expected, Image value) { assertEquals(expected, value); - assertEquals(expected.compute().options(), value.compute().options()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.imageId(), value.imageId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.configuration(), value.configuration()); - assertEquals(expected.status(), value.status()); - assertEquals(expected.diskSizeGb(), value.diskSizeGb()); - assertEquals(expected.licenses(), value.licenses()); - assertEquals(expected.deprecationStatus(), value.deprecationStatus()); + assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getImageId(), value.getImageId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getConfiguration(), value.getConfiguration()); + assertEquals(expected.getStatus(), value.getStatus()); + assertEquals(expected.getDiskSizeGb(), value.getDiskSizeGb()); + assertEquals(expected.getLicenses(), value.getLicenses()); + assertEquals(expected.getDeprecationStatus(), value.getDeprecationStatus()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceIdTest.java index 5c02e6d7c7ee..38a2b788d045 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceIdTest.java @@ -39,6 +39,24 @@ public class InstanceIdTest { @Test public void testOf() { + InstanceId instanceId = InstanceId.of(PROJECT, ZONE, NAME); + assertEquals(PROJECT, instanceId.getProject()); + assertEquals(ZONE, instanceId.getZone()); + assertEquals(NAME, instanceId.getInstance()); + assertEquals(URL, instanceId.getSelfLink()); + instanceId = InstanceId.of(ZoneId.of(PROJECT, ZONE), NAME); + assertEquals(PROJECT, instanceId.getProject()); + assertEquals(ZONE, instanceId.getZone()); + assertEquals(NAME, instanceId.getInstance()); + assertEquals(URL, instanceId.getSelfLink()); + instanceId = InstanceId.of(ZONE, NAME); + assertNull(instanceId.getProject()); + assertEquals(ZONE, instanceId.getZone()); + assertEquals(NAME, instanceId.getInstance()); + } + + @Test + public void testOfDeprecated() { InstanceId instanceId = InstanceId.of(PROJECT, ZONE, NAME); assertEquals(PROJECT, instanceId.project()); assertEquals(ZONE, instanceId.zone()); @@ -58,7 +76,7 @@ public void testOf() { @Test public void testToAndFromUrl() { InstanceId instanceId = InstanceId.of(PROJECT, ZONE, NAME); - compareInstanceId(instanceId, InstanceId.fromUrl(instanceId.selfLink())); + compareInstanceId(instanceId, InstanceId.fromUrl(instanceId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid instance URL"); InstanceId.fromUrl("notMatchingUrl"); @@ -73,16 +91,16 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(InstanceId.matchesUrl(InstanceId.of(PROJECT, ZONE, NAME).selfLink())); + assertTrue(InstanceId.matchesUrl(InstanceId.of(PROJECT, ZONE, NAME).getSelfLink())); assertFalse(InstanceId.matchesUrl("notMatchingUrl")); } private void compareInstanceId(InstanceId expected, InstanceId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.zone(), expected.zone()); - assertEquals(expected.instance(), expected.instance()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getZone(), expected.getZone()); + assertEquals(expected.getInstance(), expected.getInstance()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceInfoTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceInfoTest.java index 13e7a87af06e..dab2308b36d4 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceInfoTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceInfoTest.java @@ -44,7 +44,7 @@ public class InstanceInfoTest { private static final AttachedDisk ATTACHED_DISK = AttachedDisk.of(AttachedDisk.PersistentDiskConfiguration.of(DISK_ID)); private static final List ATTACHED_DISKS = ImmutableList.of(ATTACHED_DISK); - private static final Metadata METADATA = Metadata.builder() + private static final Metadata METADATA = Metadata.newBuilder() .add("key1", "value1") .add("key2", "value2") .build(); @@ -53,28 +53,45 @@ public class InstanceInfoTest { private static final List SERVICE_ACCOUNTS = ImmutableList.of(SERVICE_ACCOUNT); private static final SchedulingOptions SCHEDULING_OPTIONS = SchedulingOptions.preemptible(); private static final String CPU_PLATFORM = "cpuPlatform"; - private static final InstanceInfo INSTANCE_INFO = InstanceInfo.builder(INSTANCE_ID, MACHINE_TYPE) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .statusMessage(STATUS_MESSAGE) - .tags(TAGS) - .canIpForward(CAN_IP_FORWARD) - .networkInterfaces(NETWORK_INTERFACES) - .attachedDisks(ATTACHED_DISKS) - .metadata(METADATA) - .serviceAccounts(SERVICE_ACCOUNTS) - .schedulingOptions(SCHEDULING_OPTIONS) - .cpuPlatform(CPU_PLATFORM) - .build(); + private static final InstanceInfo INSTANCE_INFO = + InstanceInfo.newBuilder(INSTANCE_ID, MACHINE_TYPE) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) + .setTags(TAGS) + .setCanIpForward(CAN_IP_FORWARD) + .setNetworkInterfaces(NETWORK_INTERFACES) + .setAttachedDisks(ATTACHED_DISKS) + .setMetadata(METADATA) + .setServiceAccounts(SERVICE_ACCOUNTS) + .setSchedulingOptions(SCHEDULING_OPTIONS) + .setCpuPlatform(CPU_PLATFORM) + .build(); + private static final InstanceInfo DEPRECATED_INSTANCE_INFO = + InstanceInfo.newBuilder(INSTANCE_ID, MACHINE_TYPE) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .description(DESCRIPTION) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) + .tags(TAGS) + .canIpForward(CAN_IP_FORWARD) + .networkInterfaces(NETWORK_INTERFACES) + .attachedDisks(ATTACHED_DISKS) + .metadata(METADATA) + .serviceAccounts(SERVICE_ACCOUNTS) + .schedulingOptions(SCHEDULING_OPTIONS) + .setCpuPlatform(CPU_PLATFORM) + .build(); @Test public void testToBuilder() { compareInstanceInfo(INSTANCE_INFO, INSTANCE_INFO.toBuilder().build()); - InstanceInfo instance = INSTANCE_INFO.toBuilder().description("newDescription").build(); - assertEquals("newDescription", instance.description()); - instance = instance.toBuilder().description(DESCRIPTION).build(); + InstanceInfo instance = INSTANCE_INFO.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", instance.getDescription()); + instance = instance.toBuilder().setDescription(DESCRIPTION).build(); compareInstanceInfo(INSTANCE_INFO, instance); } @@ -87,27 +104,62 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(GENERATED_ID, INSTANCE_INFO.generatedId()); - assertEquals(INSTANCE_ID, INSTANCE_INFO.instanceId()); - assertEquals(CREATION_TIMESTAMP, INSTANCE_INFO.creationTimestamp()); - assertEquals(DESCRIPTION, INSTANCE_INFO.description()); - assertEquals(STATUS, INSTANCE_INFO.status()); - assertEquals(STATUS_MESSAGE, INSTANCE_INFO.statusMessage()); - assertEquals(TAGS, INSTANCE_INFO.tags()); - assertEquals(MACHINE_TYPE, INSTANCE_INFO.machineType()); + assertEquals(GENERATED_ID, INSTANCE_INFO.getGeneratedId()); + assertEquals(INSTANCE_ID, INSTANCE_INFO.getInstanceId()); + assertEquals(CREATION_TIMESTAMP, INSTANCE_INFO.getCreationTimestamp()); + assertEquals(DESCRIPTION, INSTANCE_INFO.getDescription()); + assertEquals(STATUS, INSTANCE_INFO.getStatus()); + assertEquals(STATUS_MESSAGE, INSTANCE_INFO.getStatusMessage()); + assertEquals(TAGS, INSTANCE_INFO.getTags()); + assertEquals(MACHINE_TYPE, INSTANCE_INFO.getMachineType()); assertEquals(CAN_IP_FORWARD, INSTANCE_INFO.canIpForward()); - assertEquals(NETWORK_INTERFACES, INSTANCE_INFO.networkInterfaces()); - assertEquals(ATTACHED_DISKS, INSTANCE_INFO.attachedDisks()); - assertEquals(METADATA, INSTANCE_INFO.metadata()); - assertEquals(SERVICE_ACCOUNTS, INSTANCE_INFO.serviceAccounts()); - assertEquals(SCHEDULING_OPTIONS, INSTANCE_INFO.schedulingOptions()); - assertEquals(CPU_PLATFORM, INSTANCE_INFO.cpuPlatform()); + assertEquals(NETWORK_INTERFACES, INSTANCE_INFO.getNetworkInterfaces()); + assertEquals(ATTACHED_DISKS, INSTANCE_INFO.getAttachedDisks()); + assertEquals(METADATA, INSTANCE_INFO.getMetadata()); + assertEquals(SERVICE_ACCOUNTS, INSTANCE_INFO.getServiceAccounts()); + assertEquals(SCHEDULING_OPTIONS, INSTANCE_INFO.getSchedulingOptions()); + assertEquals(CPU_PLATFORM, INSTANCE_INFO.getCpuPlatform()); + InstanceInfo instanceInfo = InstanceInfo.newBuilder(INSTANCE_ID, MACHINE_TYPE) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) + .setTags(TAGS) + .setCanIpForward(CAN_IP_FORWARD) + .setNetworkInterfaces(NETWORK_INTERFACE) + .setAttachedDisks(ATTACHED_DISK) + .setMetadata(METADATA) + .setServiceAccounts(SERVICE_ACCOUNTS) + .setSchedulingOptions(SCHEDULING_OPTIONS) + .setCpuPlatform(CPU_PLATFORM) + .build(); + compareInstanceInfo(INSTANCE_INFO, instanceInfo); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(GENERATED_ID, DEPRECATED_INSTANCE_INFO.generatedId()); + assertEquals(INSTANCE_ID, DEPRECATED_INSTANCE_INFO.instanceId()); + assertEquals(CREATION_TIMESTAMP, DEPRECATED_INSTANCE_INFO.creationTimestamp()); + assertEquals(DESCRIPTION, DEPRECATED_INSTANCE_INFO.description()); + assertEquals(STATUS, DEPRECATED_INSTANCE_INFO.status()); + assertEquals(STATUS_MESSAGE, DEPRECATED_INSTANCE_INFO.statusMessage()); + assertEquals(TAGS, DEPRECATED_INSTANCE_INFO.tags()); + assertEquals(MACHINE_TYPE, DEPRECATED_INSTANCE_INFO.machineType()); + assertEquals(CAN_IP_FORWARD, DEPRECATED_INSTANCE_INFO.canIpForward()); + assertEquals(NETWORK_INTERFACES, DEPRECATED_INSTANCE_INFO.networkInterfaces()); + assertEquals(ATTACHED_DISKS, DEPRECATED_INSTANCE_INFO.attachedDisks()); + assertEquals(METADATA, DEPRECATED_INSTANCE_INFO.metadata()); + assertEquals(SERVICE_ACCOUNTS, DEPRECATED_INSTANCE_INFO.serviceAccounts()); + assertEquals(SCHEDULING_OPTIONS, DEPRECATED_INSTANCE_INFO.schedulingOptions()); + assertEquals(CPU_PLATFORM, DEPRECATED_INSTANCE_INFO.cpuPlatform()); InstanceInfo instanceInfo = InstanceInfo.builder(INSTANCE_ID, MACHINE_TYPE) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) .description(DESCRIPTION) - .status(STATUS) - .statusMessage(STATUS_MESSAGE) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) .tags(TAGS) .canIpForward(CAN_IP_FORWARD) .networkInterfaces(NETWORK_INTERFACE) @@ -115,7 +167,7 @@ public void testBuilder() { .metadata(METADATA) .serviceAccounts(SERVICE_ACCOUNTS) .schedulingOptions(SCHEDULING_OPTIONS) - .cpuPlatform(CPU_PLATFORM) + .setCpuPlatform(CPU_PLATFORM) .build(); compareInstanceInfo(INSTANCE_INFO, instanceInfo); } @@ -124,21 +176,21 @@ public void testBuilder() { public void testOf() { InstanceInfo instance = InstanceInfo.of(INSTANCE_ID, MACHINE_TYPE, ATTACHED_DISK, NETWORK_INTERFACE); - assertNull(instance.generatedId()); - assertEquals(INSTANCE_ID, instance.instanceId()); - assertNull(instance.creationTimestamp()); - assertNull(instance.description()); - assertNull(instance.status()); - assertNull(instance.statusMessage()); - assertNull(instance.tags()); - assertEquals(MACHINE_TYPE, instance.machineType()); + assertNull(instance.getGeneratedId()); + assertEquals(INSTANCE_ID, instance.getInstanceId()); + assertNull(instance.getCreationTimestamp()); + assertNull(instance.getDescription()); + assertNull(instance.getStatus()); + assertNull(instance.getStatusMessage()); + assertNull(instance.getTags()); + assertEquals(MACHINE_TYPE, instance.getMachineType()); assertNull(instance.canIpForward()); - assertEquals(NETWORK_INTERFACES, instance.networkInterfaces()); - assertEquals(ATTACHED_DISKS, instance.attachedDisks()); - assertNull(instance.metadata()); - assertNull(instance.serviceAccounts()); - assertNull(instance.schedulingOptions()); - assertNull(instance.cpuPlatform()); + assertEquals(NETWORK_INTERFACES, instance.getNetworkInterfaces()); + assertEquals(ATTACHED_DISKS, instance.getAttachedDisks()); + assertNull(instance.getMetadata()); + assertNull(instance.getServiceAccounts()); + assertNull(instance.getSchedulingOptions()); + assertNull(instance.getCpuPlatform()); } @Test @@ -163,21 +215,21 @@ public void testSetProjectId() { public void compareInstanceInfo(InstanceInfo expected, InstanceInfo value) { assertEquals(expected, value); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.instanceId(), value.instanceId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.status(), value.status()); - assertEquals(expected.statusMessage(), value.statusMessage()); - assertEquals(expected.tags(), value.tags()); - assertEquals(expected.machineType(), value.machineType()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getInstanceId(), value.getInstanceId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getStatus(), value.getStatus()); + assertEquals(expected.getStatusMessage(), value.getStatusMessage()); + assertEquals(expected.getTags(), value.getTags()); + assertEquals(expected.getMachineType(), value.getMachineType()); assertEquals(expected.canIpForward(), value.canIpForward()); - assertEquals(expected.networkInterfaces(), value.networkInterfaces()); - assertEquals(expected.attachedDisks(), value.attachedDisks()); - assertEquals(expected.metadata(), value.metadata()); - assertEquals(expected.serviceAccounts(), value.serviceAccounts()); - assertEquals(expected.schedulingOptions(), value.schedulingOptions()); - assertEquals(expected.cpuPlatform(), value.cpuPlatform()); + assertEquals(expected.getNetworkInterfaces(), value.getNetworkInterfaces()); + assertEquals(expected.getAttachedDisks(), value.getAttachedDisks()); + assertEquals(expected.getMetadata(), value.getMetadata()); + assertEquals(expected.getServiceAccounts(), value.getServiceAccounts()); + assertEquals(expected.getSchedulingOptions(), value.getSchedulingOptions()); + assertEquals(expected.getCpuPlatform(), value.getCpuPlatform()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceTest.java index 522e1a7daf28..eacc72f12ab6 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceTest.java @@ -43,9 +43,9 @@ public class InstanceTest { private static final InstanceId INSTANCE_ID = InstanceId.of("project", "zone", "instance"); private static final InstanceInfo.Status STATUS = InstanceInfo.Status.RUNNING; private static final String STATUS_MESSAGE = "statusMessage"; - private static final Tags TAGS = Tags.builder() - .values("tag1", "tag2") - .fingerprint("fingerprint") + private static final Tags TAGS = Tags.newBuilder() + .setValues("tag1", "tag2") + .setFingerprint("fingerprint") .build(); private static final MachineTypeId MACHINE_TYPE = MachineTypeId.of("project", "zone", "type"); private static final Boolean CAN_IP_FORWARD = true; @@ -57,10 +57,10 @@ public class InstanceTest { private static final AttachedDisk ATTACHED_DISK = AttachedDisk.of(AttachedDisk.PersistentDiskConfiguration.of(DISK_ID)); private static final List ATTACHED_DISKS = ImmutableList.of(ATTACHED_DISK); - private static final Metadata METADATA = Metadata.builder() + private static final Metadata METADATA = Metadata.newBuilder() .add("key1", "value1") .add("key2", "value2") - .fingerprint("fingerprint") + .setFingerprint("fingerprint") .build(); private static final ServiceAccount SERVICE_ACCOUNT = ServiceAccount.of("email", ImmutableList.of("scope1")); @@ -80,17 +80,17 @@ private void initializeExpectedInstance(int optionsCalls) { replay(serviceMockReturnsOptions); expectedInstance = new Instance.Builder(serviceMockReturnsOptions, INSTANCE_ID, MACHINE_TYPE, ATTACHED_DISK, NETWORK_INTERFACE) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .statusMessage(STATUS_MESSAGE) - .tags(TAGS) - .canIpForward(CAN_IP_FORWARD) - .metadata(METADATA) - .serviceAccounts(SERVICE_ACCOUNTS) - .schedulingOptions(SCHEDULING_OPTIONS) - .cpuPlatform(CPU_PLATFORM) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) + .setTags(TAGS) + .setCanIpForward(CAN_IP_FORWARD) + .setMetadata(METADATA) + .setServiceAccounts(SERVICE_ACCOUNTS) + .setSchedulingOptions(SCHEDULING_OPTIONS) + .setCpuPlatform(CPU_PLATFORM) .build(); compute = createStrictMock(Compute.class); } @@ -98,17 +98,17 @@ private void initializeExpectedInstance(int optionsCalls) { private void initializeInstance() { instance = new Instance.Builder(compute, INSTANCE_ID, MACHINE_TYPE, ATTACHED_DISK, NETWORK_INTERFACE) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .statusMessage(STATUS_MESSAGE) - .tags(TAGS) - .canIpForward(CAN_IP_FORWARD) - .metadata(METADATA) - .serviceAccounts(SERVICE_ACCOUNTS) - .schedulingOptions(SCHEDULING_OPTIONS) - .cpuPlatform(CPU_PLATFORM) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) + .setTags(TAGS) + .setCanIpForward(CAN_IP_FORWARD) + .setMetadata(METADATA) + .setServiceAccounts(SERVICE_ACCOUNTS) + .setSchedulingOptions(SCHEDULING_OPTIONS) + .setCpuPlatform(CPU_PLATFORM) .build(); } @@ -116,9 +116,9 @@ private void initializeInstance() { public void testToBuilder() { initializeExpectedInstance(8); compareInstance(expectedInstance, expectedInstance.toBuilder().build()); - Instance newInstance = expectedInstance.toBuilder().description("newDescription").build(); - assertEquals("newDescription", newInstance.description()); - newInstance = newInstance.toBuilder().description("description").build(); + Instance newInstance = expectedInstance.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", newInstance.getDescription()); + newInstance = newInstance.toBuilder().setDescription("description").build(); compareInstance(expectedInstance, newInstance); } @@ -134,6 +134,47 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { + initializeExpectedInstance(2); + assertEquals(GENERATED_ID, expectedInstance.getGeneratedId()); + assertEquals(INSTANCE_ID, expectedInstance.getInstanceId()); + assertEquals(CREATION_TIMESTAMP, expectedInstance.getCreationTimestamp()); + assertEquals(DESCRIPTION, expectedInstance.getDescription()); + assertEquals(STATUS, expectedInstance.getStatus()); + assertEquals(STATUS_MESSAGE, expectedInstance.getStatusMessage()); + assertEquals(TAGS, expectedInstance.getTags()); + assertEquals(MACHINE_TYPE, expectedInstance.getMachineType()); + assertEquals(CAN_IP_FORWARD, expectedInstance.canIpForward()); + assertEquals(NETWORK_INTERFACES, expectedInstance.getNetworkInterfaces()); + assertEquals(ATTACHED_DISKS, expectedInstance.getAttachedDisks()); + assertEquals(METADATA, expectedInstance.getMetadata()); + assertEquals(SERVICE_ACCOUNTS, expectedInstance.getServiceAccounts()); + assertEquals(SCHEDULING_OPTIONS, expectedInstance.getSchedulingOptions()); + assertEquals(CPU_PLATFORM, expectedInstance.getCpuPlatform()); + assertSame(serviceMockReturnsOptions, expectedInstance.getCompute()); + InstanceInfo instanceInfo = + InstanceInfo.of(INSTANCE_ID, MACHINE_TYPE, ATTACHED_DISK, NETWORK_INTERFACE); + Instance instance = + new Instance(serviceMockReturnsOptions, new InstanceInfo.BuilderImpl(instanceInfo)); + assertNull(instance.getGeneratedId()); + assertEquals(INSTANCE_ID, instance.getInstanceId()); + assertNull(instance.getCreationTimestamp()); + assertNull(instance.getDescription()); + assertNull(instance.getStatus()); + assertNull(instance.getStatusMessage()); + assertNull(instance.getTags()); + assertEquals(MACHINE_TYPE, instance.getMachineType()); + assertNull(instance.canIpForward()); + assertEquals(NETWORK_INTERFACES, instance.getNetworkInterfaces()); + assertEquals(ATTACHED_DISKS, instance.getAttachedDisks()); + assertNull(instance.getMetadata()); + assertNull(instance.getServiceAccounts()); + assertNull(instance.getSchedulingOptions()); + assertNull(instance.getCpuPlatform()); + assertSame(serviceMockReturnsOptions, instance.getCompute()); + } + + @Test + public void testBuilderDeprecated() { initializeExpectedInstance(2); assertEquals(GENERATED_ID, expectedInstance.generatedId()); assertEquals(INSTANCE_ID, expectedInstance.instanceId()); @@ -188,7 +229,7 @@ public void testDeleteOperation() { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.deleteInstance(INSTANCE_ID)).andReturn(operation); replay(compute); @@ -257,7 +298,8 @@ public void testReloadNull() throws Exception { public void testReloadWithOptions() throws Exception { initializeExpectedInstance(3); expect(compute.options()).andReturn(mockOptions); - expect(compute.getInstance(INSTANCE_ID, Compute.InstanceOption.fields())).andReturn(expectedInstance); + expect(compute.getInstance(INSTANCE_ID, + Compute.InstanceOption.fields())).andReturn(expectedInstance); replay(compute); initializeInstance(); Instance updateInstance = instance.reload(Compute.InstanceOption.fields()); @@ -271,7 +313,7 @@ public void testAddAccessConfig() throws Exception { expect(compute.options()).andReturn(mockOptions); NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.of("192.168.1.1"); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.addAccessConfig(INSTANCE_ID, "nic0", accessConfig)).andReturn(operation); replay(compute); @@ -296,22 +338,25 @@ public void testAddAccessConfigWithOptions() throws Exception { expect(compute.options()).andReturn(mockOptions); NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.of("192.168.1.1"); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); - expect(compute.addAccessConfig(INSTANCE_ID, "nic0", accessConfig, Compute.OperationOption.fields())) + expect(compute.addAccessConfig( + INSTANCE_ID, "nic0", accessConfig, Compute.OperationOption.fields())) .andReturn(operation); replay(compute); initializeInstance(); - assertSame(operation, instance.addAccessConfig("nic0", accessConfig, Compute.OperationOption.fields())); + assertSame(operation, + instance.addAccessConfig("nic0", accessConfig, Compute.OperationOption.fields())); } @Test public void testAttachDisk() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); - AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); + AttachedDisk.PersistentDiskConfiguration configuration = + AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.attachDisk(INSTANCE_ID, configuration)).andReturn(operation); replay(compute); @@ -323,7 +368,8 @@ public void testAttachDisk() throws Exception { public void testAttachDisk_Null() throws Exception { initializeExpectedInstance(1); expect(compute.options()).andReturn(mockOptions); - AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); + AttachedDisk.PersistentDiskConfiguration configuration = + AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); expect(compute.attachDisk(INSTANCE_ID, configuration)).andReturn(null); replay(compute); initializeInstance(); @@ -334,9 +380,10 @@ public void testAttachDisk_Null() throws Exception { public void testAttachDiskWithOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); - AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); + AttachedDisk.PersistentDiskConfiguration configuration = + AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.attachDisk(INSTANCE_ID, configuration, Compute.OperationOption.fields())) .andReturn(operation); @@ -349,9 +396,10 @@ public void testAttachDiskWithOptions() throws Exception { public void testAttachDiskName() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); - AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); + AttachedDisk.PersistentDiskConfiguration configuration = + AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.attachDisk(INSTANCE_ID, "dev0", configuration)).andReturn(operation); replay(compute); @@ -363,7 +411,8 @@ public void testAttachDiskName() throws Exception { public void testAttachDiskName_Null() throws Exception { initializeExpectedInstance(1); expect(compute.options()).andReturn(mockOptions); - AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); + AttachedDisk.PersistentDiskConfiguration configuration = + AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); expect(compute.attachDisk(INSTANCE_ID, "dev0", configuration)).andReturn(null); replay(compute); initializeInstance(); @@ -374,24 +423,27 @@ public void testAttachDiskName_Null() throws Exception { public void testAttachDiskNameWithOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); - AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); + AttachedDisk.PersistentDiskConfiguration configuration = + AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.attachDisk(INSTANCE_ID, "dev0", configuration, Compute.OperationOption.fields())) .andReturn(operation); replay(compute); initializeInstance(); - assertSame(operation, instance.attachDisk("dev0", configuration, Compute.OperationOption.fields())); + assertSame(operation, + instance.attachDisk("dev0", configuration, Compute.OperationOption.fields())); } @Test public void testAttachDiskNameIndex() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); - AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); + AttachedDisk.PersistentDiskConfiguration configuration = + AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.attachDisk(INSTANCE_ID, "dev0", configuration, 1)).andReturn(operation); replay(compute); @@ -403,7 +455,8 @@ public void testAttachDiskNameIndex() throws Exception { public void testAttachDiskNameIndex_Null() throws Exception { initializeExpectedInstance(1); expect(compute.options()).andReturn(mockOptions); - AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); + AttachedDisk.PersistentDiskConfiguration configuration = + AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); expect(compute.attachDisk(INSTANCE_ID, "dev0", configuration, 1)).andReturn(null); replay(compute); initializeInstance(); @@ -414,11 +467,13 @@ public void testAttachDiskNameIndex_Null() throws Exception { public void testAttachDiskNameIndexWithOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); - AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); + AttachedDisk.PersistentDiskConfiguration configuration = + AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); - expect(compute.attachDisk(INSTANCE_ID, "dev0", configuration, 1, Compute.OperationOption.fields())) + expect(compute.attachDisk( + INSTANCE_ID, "dev0", configuration, 1, Compute.OperationOption.fields())) .andReturn(operation); replay(compute); initializeInstance(); @@ -431,7 +486,7 @@ public void testDeleteAccessConfig() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.deleteAccessConfig(INSTANCE_ID, "nic0", "NAT")).andReturn(operation); replay(compute); @@ -454,13 +509,15 @@ public void testDeleteAccessConfigWithOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); - expect(compute.deleteAccessConfig(INSTANCE_ID, "nic0", "NAT", Compute.OperationOption.fields())) + expect(compute.deleteAccessConfig( + INSTANCE_ID, "nic0", "NAT", Compute.OperationOption.fields())) .andReturn(operation); replay(compute); initializeInstance(); - assertSame(operation, instance.deleteAccessConfig("nic0", "NAT", Compute.OperationOption.fields())); + assertSame(operation, + instance.deleteAccessConfig("nic0", "NAT", Compute.OperationOption.fields())); } @Test @@ -468,7 +525,7 @@ public void testDetachDisk() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.detachDisk(INSTANCE_ID, "dev0")).andReturn(operation); replay(compute); @@ -491,9 +548,10 @@ public void testDetachDiskWithOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); - expect(compute.detachDisk(INSTANCE_ID, "dev0", Compute.OperationOption.fields())).andReturn(operation); + expect(compute.detachDisk(INSTANCE_ID, "dev0", Compute.OperationOption.fields())) + .andReturn(operation); replay(compute); initializeInstance(); assertSame(operation, instance.detachDisk("dev0", Compute.OperationOption.fields())); @@ -524,7 +582,7 @@ public void testResetOperation() { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.reset(INSTANCE_ID)).andReturn(operation); replay(compute); @@ -547,7 +605,7 @@ public void testSetDiskAutodelete() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.setDiskAutoDelete(INSTANCE_ID, "dev0", true)).andReturn(operation); replay(compute); @@ -570,13 +628,14 @@ public void testSetDiskAutodeleteWithOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.setDiskAutoDelete(INSTANCE_ID, "dev0", true, Compute.OperationOption.fields())) .andReturn(operation); replay(compute); initializeInstance(); - assertSame(operation, instance.setDiskAutoDelete("dev0", true, Compute.OperationOption.fields())); + assertSame(operation, + instance.setDiskAutoDelete("dev0", true, Compute.OperationOption.fields())); } @Test @@ -584,7 +643,7 @@ public void testSetMachineType() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.setMachineType(INSTANCE_ID, MACHINE_TYPE)).andReturn(operation); replay(compute); @@ -607,7 +666,7 @@ public void testSetMachineTypeWithOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.setMachineType(INSTANCE_ID, MACHINE_TYPE, Compute.OperationOption.fields())) .andReturn(operation); @@ -621,9 +680,9 @@ public void testSetMetadata() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); - Metadata metadata = Metadata.builder().add("k", "v").fingerprint("fingerprint").build(); + Metadata metadata = Metadata.newBuilder().add("k", "v").setFingerprint("fingerprint").build(); expect(compute.setMetadata(INSTANCE_ID, metadata)).andReturn(operation); replay(compute); initializeInstance(); @@ -634,7 +693,7 @@ public void testSetMetadata() throws Exception { public void testSetMetadata_Null() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); - Metadata metadata = Metadata.builder().add("k", "v").fingerprint("fingerprint").build(); + Metadata metadata = Metadata.newBuilder().add("k", "v").setFingerprint("fingerprint").build(); expect(compute.setMetadata(INSTANCE_ID, metadata)).andReturn(null); replay(compute); initializeInstance(); @@ -646,9 +705,9 @@ public void testSetMetadataWithOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); - Metadata metadata = Metadata.builder().add("k", "v").fingerprint("fingerprint").build(); + Metadata metadata = Metadata.newBuilder().add("k", "v").setFingerprint("fingerprint").build(); expect(compute.setMetadata(INSTANCE_ID, metadata, Compute.OperationOption.fields())) .andReturn(operation); replay(compute); @@ -661,10 +720,11 @@ public void testSetMetadataFromMap() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); Map metadataMap = ImmutableMap.of("k", "v"); - Metadata metadata = Metadata.builder().values(metadataMap).fingerprint("fingerprint").build(); + Metadata metadata = + Metadata.newBuilder().setValues(metadataMap).setFingerprint("fingerprint").build(); expect(compute.setMetadata(INSTANCE_ID, metadata)).andReturn(operation); replay(compute); initializeInstance(); @@ -676,7 +736,8 @@ public void testSetMetadataFromMap_Null() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Map metadataMap = ImmutableMap.of("k", "v"); - Metadata metadata = Metadata.builder().values(metadataMap).fingerprint("fingerprint").build(); + Metadata metadata = + Metadata.newBuilder().setValues(metadataMap).setFingerprint("fingerprint").build(); expect(compute.setMetadata(INSTANCE_ID, metadata)).andReturn(null); replay(compute); initializeInstance(); @@ -688,10 +749,11 @@ public void testSetMetadataFromMapWithOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); Map metadataMap = ImmutableMap.of("k", "v"); - Metadata metadata = Metadata.builder().values(metadataMap).fingerprint("fingerprint").build(); + Metadata metadata = + Metadata.newBuilder().setValues(metadataMap).setFingerprint("fingerprint").build(); expect(compute.setMetadata(INSTANCE_ID, metadata, Compute.OperationOption.fields())) .andReturn(operation); replay(compute); @@ -704,9 +766,10 @@ public void testSetSchedulingOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); - SchedulingOptions schedulingOptions = SchedulingOptions.standard(true, SchedulingOptions.Maintenance.MIGRATE); + SchedulingOptions schedulingOptions = + SchedulingOptions.standard(true, SchedulingOptions.Maintenance.MIGRATE); expect(compute.setSchedulingOptions(INSTANCE_ID, schedulingOptions)).andReturn(operation); replay(compute); initializeInstance(); @@ -717,7 +780,8 @@ public void testSetSchedulingOptions() throws Exception { public void testSetSchedulingOptions_Null() throws Exception { initializeExpectedInstance(1); expect(compute.options()).andReturn(mockOptions); - SchedulingOptions schedulingOptions = SchedulingOptions.standard(true, SchedulingOptions.Maintenance.MIGRATE); + SchedulingOptions schedulingOptions = + SchedulingOptions.standard(true, SchedulingOptions.Maintenance.MIGRATE); expect(compute.setSchedulingOptions(INSTANCE_ID, schedulingOptions)).andReturn(null); replay(compute); initializeInstance(); @@ -729,10 +793,12 @@ public void testSetSchedulingOptionsWithOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); - SchedulingOptions schedulingOptions = SchedulingOptions.standard(true, SchedulingOptions.Maintenance.MIGRATE); - expect(compute.setSchedulingOptions(INSTANCE_ID, schedulingOptions, Compute.OperationOption.fields())) + SchedulingOptions schedulingOptions = + SchedulingOptions.standard(true, SchedulingOptions.Maintenance.MIGRATE); + expect(compute.setSchedulingOptions( + INSTANCE_ID, schedulingOptions, Compute.OperationOption.fields())) .andReturn(operation); replay(compute); initializeInstance(); @@ -745,9 +811,9 @@ public void testSetTags() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); - Tags tags = Tags.builder().values("v1", "v2").fingerprint("fingerprint").build(); + Tags tags = Tags.newBuilder().setValues("v1", "v2").setFingerprint("fingerprint").build(); expect(compute.setTags(INSTANCE_ID, tags)).andReturn(operation); replay(compute); initializeInstance(); @@ -758,7 +824,7 @@ public void testSetTags() throws Exception { public void testSetTags_Null() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); - Tags tags = Tags.builder().values("v1", "v2").fingerprint("fingerprint").build(); + Tags tags = Tags.newBuilder().setValues("v1", "v2").setFingerprint("fingerprint").build(); expect(compute.setTags(INSTANCE_ID, tags)).andReturn(null); replay(compute); initializeInstance(); @@ -770,10 +836,11 @@ public void testSetTagsWithOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); - Tags tags = Tags.builder().values("v1", "v2").fingerprint("fingerprint").build(); - expect(compute.setTags(INSTANCE_ID, tags, Compute.OperationOption.fields())).andReturn(operation); + Tags tags = Tags.newBuilder().setValues("v1", "v2").setFingerprint("fingerprint").build(); + expect(compute.setTags(INSTANCE_ID, tags, Compute.OperationOption.fields())) + .andReturn(operation); replay(compute); initializeInstance(); assertSame(operation, instance.setTags(tags, Compute.OperationOption.fields())); @@ -784,10 +851,10 @@ public void testSetTagsFromList() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); List tagList = ImmutableList.of("v1", "v2"); - Tags tags = Tags.builder().values(tagList).fingerprint("fingerprint").build(); + Tags tags = Tags.newBuilder().setValues(tagList).setFingerprint("fingerprint").build(); expect(compute.setTags(INSTANCE_ID, tags)).andReturn(operation); replay(compute); initializeInstance(); @@ -799,7 +866,7 @@ public void testSetTagsFromList_Null() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); List tagList = ImmutableList.of("v1", "v2"); - Tags tags = Tags.builder().values(tagList).fingerprint("fingerprint").build(); + Tags tags = Tags.newBuilder().setValues(tagList).setFingerprint("fingerprint").build(); expect(compute.setTags(INSTANCE_ID, tags)).andReturn(null); replay(compute); initializeInstance(); @@ -811,11 +878,12 @@ public void testSetTagsFromListWithOptions() throws Exception { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); List tagList = ImmutableList.of("v1", "v2"); - Tags tags = Tags.builder().values(tagList).fingerprint("fingerprint").build(); - expect(compute.setTags(INSTANCE_ID, tags, Compute.OperationOption.fields())).andReturn(operation); + Tags tags = Tags.newBuilder().setValues(tagList).setFingerprint("fingerprint").build(); + expect(compute.setTags(INSTANCE_ID, tags, Compute.OperationOption.fields())) + .andReturn(operation); replay(compute); initializeInstance(); assertSame(operation, instance.setTags(tagList, Compute.OperationOption.fields())); @@ -826,7 +894,7 @@ public void testStartOperation() { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.start(INSTANCE_ID)).andReturn(operation); replay(compute); @@ -849,7 +917,7 @@ public void testStopOperation() { initializeExpectedInstance(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZoneOperationId.of("project", "op")) + .setOperationId(ZoneOperationId.of("project", "op")) .build(); expect(compute.stop(INSTANCE_ID)).andReturn(operation); replay(compute); @@ -869,22 +937,22 @@ public void testStopNull() { public void compareInstance(Instance expected, Instance value) { assertEquals(expected, value); - assertEquals(expected.compute().options(), value.compute().options()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.instanceId(), value.instanceId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.status(), value.status()); - assertEquals(expected.statusMessage(), value.statusMessage()); - assertEquals(expected.tags(), value.tags()); - assertEquals(expected.machineType(), value.machineType()); + assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getInstanceId(), value.getInstanceId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getStatus(), value.getStatus()); + assertEquals(expected.getStatusMessage(), value.getStatusMessage()); + assertEquals(expected.getTags(), value.getTags()); + assertEquals(expected.getMachineType(), value.getMachineType()); assertEquals(expected.canIpForward(), value.canIpForward()); - assertEquals(expected.networkInterfaces(), value.networkInterfaces()); - assertEquals(expected.attachedDisks(), value.attachedDisks()); - assertEquals(expected.metadata(), value.metadata()); - assertEquals(expected.serviceAccounts(), value.serviceAccounts()); - assertEquals(expected.schedulingOptions(), value.schedulingOptions()); - assertEquals(expected.cpuPlatform(), value.cpuPlatform()); + assertEquals(expected.getNetworkInterfaces(), value.getNetworkInterfaces()); + assertEquals(expected.getAttachedDisks(), value.getAttachedDisks()); + assertEquals(expected.getMetadata(), value.getMetadata()); + assertEquals(expected.getServiceAccounts(), value.getServiceAccounts()); + assertEquals(expected.getSchedulingOptions(), value.getSchedulingOptions()); + assertEquals(expected.getCpuPlatform(), value.getCpuPlatform()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/LicenseIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/LicenseIdTest.java index cdb5e7adf992..c16b054a7039 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/LicenseIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/LicenseIdTest.java @@ -38,6 +38,17 @@ public class LicenseIdTest { @Test public void testOf() { + LicenseId licenseId = LicenseId.of(PROJECT, LICENSE); + assertEquals(PROJECT, licenseId.getProject()); + assertEquals(LICENSE, licenseId.getLicense()); + assertEquals(URL, licenseId.getSelfLink()); + licenseId = LicenseId.of(LICENSE); + assertNull(licenseId.getProject()); + assertEquals(LICENSE, licenseId.getLicense()); + } + + @Test + public void testOfDeprecated() { LicenseId licenseId = LicenseId.of(PROJECT, LICENSE); assertEquals(PROJECT, licenseId.project()); assertEquals(LICENSE, licenseId.license()); @@ -50,7 +61,7 @@ public void testOf() { @Test public void testToAndFromUrl() { LicenseId licenseId = LicenseId.of(PROJECT, LICENSE); - compareLicenseId(licenseId, LicenseId.fromUrl(licenseId.selfLink())); + compareLicenseId(licenseId, LicenseId.fromUrl(licenseId.getSelfLink())); } @Test @@ -65,15 +76,15 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(LicenseId.matchesUrl(LicenseId.of(PROJECT, LICENSE).selfLink())); + assertTrue(LicenseId.matchesUrl(LicenseId.of(PROJECT, LICENSE).getSelfLink())); assertFalse(LicenseId.matchesUrl("notMatchingUrl")); } private void compareLicenseId(LicenseId expected, LicenseId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.license(), expected.license()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getLicense(), expected.getLicense()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/LicenseTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/LicenseTest.java index 6bbe50b71489..2ce8d2c06572 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/LicenseTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/LicenseTest.java @@ -28,6 +28,12 @@ public class LicenseTest { @Test public void testBuilder() { + assertEquals(LICENSE_ID, LICENSE.getLicenseId()); + assertEquals(CHARGES_USE_FEE, LICENSE.chargesUseFee()); + } + + @Test + public void testBuilderDeprecated() { assertEquals(LICENSE_ID, LICENSE.licenseId()); assertEquals(CHARGES_USE_FEE, LICENSE.chargesUseFee()); } @@ -36,13 +42,13 @@ public void testBuilder() { public void testToAndFromPb() { License license = License.fromPb(LICENSE.toPb()); compareLicenses(LICENSE, license); - assertEquals(LICENSE_ID.project(), license.licenseId().project()); - assertEquals(LICENSE_ID.license(), license.licenseId().license()); + assertEquals(LICENSE_ID.getProject(), license.getLicenseId().getProject()); + assertEquals(LICENSE_ID.getLicense(), license.getLicenseId().getLicense()); } private void compareLicenses(License expected, License value) { assertEquals(expected, value); - assertEquals(expected.licenseId(), value.licenseId()); + assertEquals(expected.getLicenseId(), value.getLicenseId()); assertEquals(expected.chargesUseFee(), value.chargesUseFee()); assertEquals(expected.hashCode(), value.hashCode()); } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/MachineTypeIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/MachineTypeIdTest.java index f7f776aec5a5..baecfad0ed15 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/MachineTypeIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/MachineTypeIdTest.java @@ -39,6 +39,19 @@ public class MachineTypeIdTest { @Test public void testOf() { + MachineTypeId machineTypeId = MachineTypeId.of(PROJECT, ZONE, TYPE); + assertEquals(PROJECT, machineTypeId.getProject()); + assertEquals(ZONE, machineTypeId.getZone()); + assertEquals(TYPE, machineTypeId.getType()); + assertEquals(URL, machineTypeId.getSelfLink()); + machineTypeId = MachineTypeId.of(ZONE, TYPE); + assertNull(machineTypeId.getProject()); + assertEquals(ZONE, machineTypeId.getZone()); + assertEquals(TYPE, machineTypeId.getType()); + } + + @Test + public void testOfDeprecated() { MachineTypeId machineTypeId = MachineTypeId.of(PROJECT, ZONE, TYPE); assertEquals(PROJECT, machineTypeId.project()); assertEquals(ZONE, machineTypeId.zone()); @@ -53,7 +66,7 @@ public void testOf() { @Test public void testToAndFromUrl() { MachineTypeId machineTypeId = MachineTypeId.of(PROJECT, ZONE, TYPE); - compareMachineTypeId(machineTypeId, MachineTypeId.fromUrl(machineTypeId.selfLink())); + compareMachineTypeId(machineTypeId, MachineTypeId.fromUrl(machineTypeId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid machine type URL"); MachineTypeId.fromUrl("notMatchingUrl"); @@ -68,16 +81,16 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(MachineTypeId.matchesUrl(MachineTypeId.of(PROJECT, ZONE, TYPE).selfLink())); + assertTrue(MachineTypeId.matchesUrl(MachineTypeId.of(PROJECT, ZONE, TYPE).getSelfLink())); assertFalse(MachineTypeId.matchesUrl("notMatchingUrl")); } private void compareMachineTypeId(MachineTypeId expected, MachineTypeId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.zone(), expected.zone()); - assertEquals(expected.type(), expected.type()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getZone(), expected.getZone()); + assertEquals(expected.getType(), expected.getType()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/MachineTypeTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/MachineTypeTest.java index 924d22bde36c..90ca3e5320c9 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/MachineTypeTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/MachineTypeTest.java @@ -37,21 +37,35 @@ public class MachineTypeTest { private static final Long MAXIMUM_PERSISTENT_DISKS_SIZE_GB = 5L; private static final DeprecationStatus DEPRECATION_STATUS = DeprecationStatus.of(DeprecationStatus.Status.DELETED, MACHINE_TYPE_ID); - private static final MachineType MACHINE_TYPE = MachineType.builder() - .generatedId(GENERATED_ID) - .machineTypeId(MACHINE_TYPE_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .cpus(CPUS) - .memoryMb(MEMORY_MB) - .scratchDisksSizeGb(SCRATCH_DISKS) - .maximumPersistentDisks(MAXIMUM_PERSISTENT_DISKS) - .maximumPersistentDisksSizeGb(MAXIMUM_PERSISTENT_DISKS_SIZE_GB) - .deprecationStatus(DEPRECATION_STATUS) + private static final MachineType MACHINE_TYPE = MachineType.newBuilder() + .setGeneratedId(GENERATED_ID) + .setMachineTypeId(MACHINE_TYPE_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setCpus(CPUS) + .setMemoryMb(MEMORY_MB) + .setScratchDisksSizeGb(SCRATCH_DISKS) + .setMaximumPersistentDisks(MAXIMUM_PERSISTENT_DISKS) + .setMaximumPersistentDisksSizeGb(MAXIMUM_PERSISTENT_DISKS_SIZE_GB) + .setDeprecationStatus(DEPRECATION_STATUS) .build(); @Test public void testBuilder() { + assertEquals(GENERATED_ID, MACHINE_TYPE.getGeneratedId()); + assertEquals(MACHINE_TYPE_ID, MACHINE_TYPE.getMachineTypeId()); + assertEquals(CREATION_TIMESTAMP, MACHINE_TYPE.getCreationTimestamp()); + assertEquals(DESCRIPTION, MACHINE_TYPE.getDescription()); + assertEquals(CPUS, MACHINE_TYPE.getCpus()); + assertEquals(MEMORY_MB, MACHINE_TYPE.getMemoryMb()); + assertEquals(SCRATCH_DISKS, MACHINE_TYPE.getScratchDisksSizeGb()); + assertEquals(MAXIMUM_PERSISTENT_DISKS, MACHINE_TYPE.getMaximumPersistentDisks()); + assertEquals(MAXIMUM_PERSISTENT_DISKS_SIZE_GB, MACHINE_TYPE.getMaximumPersistentDisksSizeGb()); + assertEquals(DEPRECATION_STATUS, MACHINE_TYPE.getDeprecationStatus()); + } + + @Test + public void testBuilderDeprecated() { assertEquals(GENERATED_ID, MACHINE_TYPE.generatedId()); assertEquals(MACHINE_TYPE_ID, MACHINE_TYPE.machineTypeId()); assertEquals(CREATION_TIMESTAMP, MACHINE_TYPE.creationTimestamp()); @@ -67,22 +81,23 @@ public void testBuilder() { @Test public void testToPbAndFromPb() { compareMachineTypes(MACHINE_TYPE, MachineType.fromPb(MACHINE_TYPE.toPb())); - MachineType machineType = MachineType.builder().machineTypeId(MACHINE_TYPE_ID).build(); + MachineType machineType = MachineType.newBuilder().setMachineTypeId(MACHINE_TYPE_ID).build(); compareMachineTypes(machineType, MachineType.fromPb(machineType.toPb())); } private void compareMachineTypes(MachineType expected, MachineType value) { assertEquals(expected, value); - assertEquals(expected.machineTypeId(), value.machineTypeId()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.cpus(), value.cpus()); - assertEquals(expected.memoryMb(), value.memoryMb()); - assertEquals(expected.scratchDisksSizeGb(), value.scratchDisksSizeGb()); - assertEquals(expected.maximumPersistentDisks(), value.maximumPersistentDisks()); - assertEquals(expected.maximumPersistentDisksSizeGb(), value.maximumPersistentDisksSizeGb()); - assertEquals(expected.deprecationStatus(), value.deprecationStatus()); + assertEquals(expected.getMachineTypeId(), value.getMachineTypeId()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getCpus(), value.getCpus()); + assertEquals(expected.getMemoryMb(), value.getMemoryMb()); + assertEquals(expected.getScratchDisksSizeGb(), value.getScratchDisksSizeGb()); + assertEquals(expected.getMaximumPersistentDisks(), value.getMaximumPersistentDisks()); + assertEquals(expected.getMaximumPersistentDisksSizeGb(), + value.getMaximumPersistentDisksSizeGb()); + assertEquals(expected.getDeprecationStatus(), value.getDeprecationStatus()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/MetadataTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/MetadataTest.java index 9de656ff24d0..93a093686c48 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/MetadataTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/MetadataTest.java @@ -27,22 +27,43 @@ public class MetadataTest { - private static final Metadata METADATA = Metadata.builder() + private static final Metadata METADATA = Metadata.newBuilder() + .add("key1", "value1") + .add("key2", "value2") + .build(); + private static final Metadata DEPRECATED_METADATA = Metadata.builder() .add("key1", "value1") .add("key2", "value2") .build(); @Test public void testToBuilder() { - Metadata metadata = METADATA.toBuilder().fingerprint("newFingerprint").build(); - assertEquals("newFingerprint", metadata.fingerprint()); - compareMetadata(METADATA, metadata.toBuilder().fingerprint(null).build()); + Metadata metadata = METADATA.toBuilder().setFingerprint("newFingerprint").build(); + assertEquals("newFingerprint", metadata.getFingerprint()); + compareMetadata(METADATA, metadata.toBuilder().setFingerprint(null).build()); } @Test public void testBuilder() { - assertEquals(ImmutableMap.of("key1", "value1", "key2", "value2"), METADATA.values()); - assertNull(METADATA.fingerprint()); + assertEquals(ImmutableMap.of("key1", "value1", "key2", "value2"), METADATA.getValues()); + assertNull(METADATA.getFingerprint()); + Metadata metadata = Metadata.newBuilder() + .setValues(ImmutableMap.of("key1", "value1", "key2", "value2")) + .build(); + assertEquals(ImmutableMap.of("key1", "value1", "key2", "value2"), metadata.getValues()); + assertNull(metadata.getFingerprint()); + metadata = Metadata.newBuilder() + .setValues(ImmutableMap.of("key1", "value1", "key2", "value2")) + .setFingerprint("fingerprint") + .build(); + assertEquals(ImmutableMap.of("key1", "value1", "key2", "value2"), metadata.getValues()); + assertEquals("fingerprint", metadata.getFingerprint()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(ImmutableMap.of("key1", "value1", "key2", "value2"), DEPRECATED_METADATA.values()); + assertNull(DEPRECATED_METADATA.fingerprint()); Metadata metadata = Metadata.builder() .values(ImmutableMap.of("key1", "value1", "key2", "value2")) .build(); @@ -65,17 +86,17 @@ public void testOf() { @Test public void testToAndFromPb() { compareMetadata(METADATA, Metadata.fromPb(METADATA.toPb())); - Metadata metadata = Metadata.builder() - .values(ImmutableMap.of("key1", "value1", "key2", "value2")) - .fingerprint("fingerprint") + Metadata metadata = Metadata.newBuilder() + .setValues(ImmutableMap.of("key1", "value1", "key2", "value2")) + .setFingerprint("fingerprint") .build(); compareMetadata(metadata, Metadata.fromPb(metadata.toPb())); } public void compareMetadata(Metadata expected, Metadata value) { assertEquals(expected, value); - assertEquals(expected.fingerprint(), value.fingerprint()); - assertEquals(expected.values(), value.values()); + assertEquals(expected.getFingerprint(), value.getFingerprint()); + assertEquals(expected.getValues(), value.getValues()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkIdTest.java index fb785852cf71..ec8c1905b444 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkIdTest.java @@ -38,6 +38,17 @@ public class NetworkIdTest { @Test public void testOf() { + NetworkId networkId = NetworkId.of(PROJECT, NETWORK); + assertEquals(PROJECT, networkId.getProject()); + assertEquals(NETWORK, networkId.getNetwork()); + assertEquals(URL, networkId.getSelfLink()); + networkId = NetworkId.of(NETWORK); + assertNull(networkId.getProject()); + assertEquals(NETWORK, networkId.getNetwork()); + } + + @Test + public void testOfDeprecated() { NetworkId networkId = NetworkId.of(PROJECT, NETWORK); assertEquals(PROJECT, networkId.project()); assertEquals(NETWORK, networkId.network()); @@ -50,7 +61,7 @@ public void testOf() { @Test public void testToAndFromUrl() { NetworkId networkId = NetworkId.of(PROJECT, NETWORK); - compareNetworkId(networkId, NetworkId.fromUrl(networkId.selfLink())); + compareNetworkId(networkId, NetworkId.fromUrl(networkId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid network URL"); NetworkId.fromUrl("notMatchingUrl"); @@ -65,15 +76,15 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(NetworkId.matchesUrl(NetworkId.of(PROJECT, NETWORK).selfLink())); + assertTrue(NetworkId.matchesUrl(NetworkId.of(PROJECT, NETWORK).getSelfLink())); assertFalse(NetworkId.matchesUrl("notMatchingUrl")); } private void compareNetworkId(NetworkId expected, NetworkId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.network(), expected.network()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getNetwork(), expected.getNetwork()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkInfoTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkInfoTest.java index e2d9c4451ee4..4ba8dd3d5bad 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkInfoTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkInfoTest.java @@ -42,29 +42,41 @@ public class NetworkInfoTest { private static final SubnetNetworkConfiguration SUBNET_NETWORK_CONFIGURATION = new SubnetNetworkConfiguration(AUTO_CREATE_SUBNETWORKS, SUBNETWORKS); private static final NetworkInfo NETWORK_INFO = + NetworkInfo.newBuilder(NETWORK_ID, NETWORK_CONFIGURATION) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .build(); + private static final NetworkInfo SUBNET_NETWORK_INFO = + NetworkInfo.newBuilder(NETWORK_ID, SUBNET_NETWORK_CONFIGURATION) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .build(); + private static final NetworkInfo DEPRECATED_NETWORK_INFO = NetworkInfo.builder(NETWORK_ID, NETWORK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) .description(DESCRIPTION) .build(); - private static final NetworkInfo SUBNET_NETWORK_INFO = + private static final NetworkInfo DEPRECATED_SUBNET_NETWORK_INFO = NetworkInfo.builder(NETWORK_ID, SUBNET_NETWORK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) .description(DESCRIPTION) .build(); @Test public void testToBuilder() { compareNetworkInfo(NETWORK_INFO, NETWORK_INFO.toBuilder().build()); - NetworkInfo networkInfo = NETWORK_INFO.toBuilder().description("newDescription").build(); - assertEquals("newDescription", networkInfo.description()); - networkInfo = networkInfo.toBuilder().description("description").build(); + NetworkInfo networkInfo = NETWORK_INFO.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", networkInfo.getDescription()); + networkInfo = networkInfo.toBuilder().setDescription("description").build(); compareNetworkInfo(NETWORK_INFO, networkInfo); compareNetworkInfo(SUBNET_NETWORK_INFO, SUBNET_NETWORK_INFO.toBuilder().build()); - networkInfo = SUBNET_NETWORK_INFO.toBuilder().description("newDescription").build(); - assertEquals("newDescription", networkInfo.description()); - networkInfo = networkInfo.toBuilder().description("description").build(); + networkInfo = SUBNET_NETWORK_INFO.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", networkInfo.getDescription()); + networkInfo = networkInfo.toBuilder().setDescription("description").build(); compareNetworkInfo(SUBNET_NETWORK_INFO, networkInfo); } @@ -76,26 +88,40 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(GENERATED_ID, NETWORK_INFO.generatedId()); - assertEquals(NETWORK_ID, NETWORK_INFO.networkId()); - assertEquals(CREATION_TIMESTAMP, NETWORK_INFO.creationTimestamp()); - assertEquals(DESCRIPTION, NETWORK_INFO.description()); - assertEquals(NETWORK_CONFIGURATION, NETWORK_INFO.configuration()); - assertEquals(GENERATED_ID, SUBNET_NETWORK_INFO.generatedId()); - assertEquals(NETWORK_ID, SUBNET_NETWORK_INFO.networkId()); - assertEquals(CREATION_TIMESTAMP, SUBNET_NETWORK_INFO.creationTimestamp()); - assertEquals(DESCRIPTION, SUBNET_NETWORK_INFO.description()); - assertEquals(SUBNET_NETWORK_CONFIGURATION, SUBNET_NETWORK_INFO.configuration()); + assertEquals(GENERATED_ID, NETWORK_INFO.getGeneratedId()); + assertEquals(NETWORK_ID, NETWORK_INFO.getNetworkId()); + assertEquals(CREATION_TIMESTAMP, NETWORK_INFO.getCreationTimestamp()); + assertEquals(DESCRIPTION, NETWORK_INFO.getDescription()); + assertEquals(NETWORK_CONFIGURATION, NETWORK_INFO.getConfiguration()); + assertEquals(GENERATED_ID, SUBNET_NETWORK_INFO.getGeneratedId()); + assertEquals(NETWORK_ID, SUBNET_NETWORK_INFO.getNetworkId()); + assertEquals(CREATION_TIMESTAMP, SUBNET_NETWORK_INFO.getCreationTimestamp()); + assertEquals(DESCRIPTION, SUBNET_NETWORK_INFO.getDescription()); + assertEquals(SUBNET_NETWORK_CONFIGURATION, SUBNET_NETWORK_INFO.getConfiguration()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(GENERATED_ID, DEPRECATED_NETWORK_INFO.generatedId()); + assertEquals(NETWORK_ID, DEPRECATED_NETWORK_INFO.networkId()); + assertEquals(CREATION_TIMESTAMP, DEPRECATED_NETWORK_INFO.creationTimestamp()); + assertEquals(DESCRIPTION, DEPRECATED_NETWORK_INFO.description()); + assertEquals(NETWORK_CONFIGURATION, DEPRECATED_NETWORK_INFO.configuration()); + assertEquals(GENERATED_ID, DEPRECATED_SUBNET_NETWORK_INFO.generatedId()); + assertEquals(NETWORK_ID, DEPRECATED_SUBNET_NETWORK_INFO.networkId()); + assertEquals(CREATION_TIMESTAMP, DEPRECATED_SUBNET_NETWORK_INFO.creationTimestamp()); + assertEquals(DESCRIPTION, DEPRECATED_SUBNET_NETWORK_INFO.description()); + assertEquals(SUBNET_NETWORK_CONFIGURATION, DEPRECATED_SUBNET_NETWORK_INFO.configuration()); } @Test public void testOf() { NetworkInfo networkInfo = NetworkInfo.of(NETWORK_ID, NETWORK_CONFIGURATION); - assertNull(networkInfo.generatedId()); - assertEquals(NETWORK_ID, NETWORK_INFO.networkId()); - assertEquals(NETWORK_CONFIGURATION, NETWORK_INFO.configuration()); - assertNull(networkInfo.creationTimestamp()); - assertNull(networkInfo.description()); + assertNull(networkInfo.getGeneratedId()); + assertEquals(NETWORK_ID, NETWORK_INFO.getNetworkId()); + assertEquals(NETWORK_CONFIGURATION, NETWORK_INFO.getConfiguration()); + assertNull(networkInfo.getCreationTimestamp()); + assertNull(networkInfo.getDescription()); } @Test @@ -109,18 +135,18 @@ public void testToAndFromPb() { @Test public void testSetProjectId() { NetworkInfo networkInfo = NETWORK_INFO.toBuilder() - .networkId(NetworkId.of("network")) + .setNetworkId(NetworkId.of("network")) .build(); compareNetworkInfo(NETWORK_INFO, networkInfo.setProjectId("project")); } public void compareNetworkInfo(NetworkInfo expected, NetworkInfo value) { assertEquals(expected, value); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.networkId(), value.networkId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.configuration(), value.configuration()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getNetworkId(), value.getNetworkId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getConfiguration(), value.getConfiguration()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkInterfaceTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkInterfaceTest.java index c36d52d8bd0f..508e0bc87452 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkInterfaceTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkInterfaceTest.java @@ -19,6 +19,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; +import com.google.cloud.compute.NetworkInterface.AccessConfig; import com.google.common.collect.ImmutableList; import org.junit.Assert; @@ -32,39 +33,64 @@ public class NetworkInterfaceTest { private static final NetworkId NETWORK = NetworkId.of("project", "network"); private static final String NETWORK_IP = "192.168.1.1"; private static final SubnetworkId SUBNETWORK = SubnetworkId.of("project", "region", "subnetwork"); - private static final NetworkInterface.AccessConfig ACCESS_CONFIG = NetworkInterface.AccessConfig.builder() - .name("accessConfig") - .natIp("192.168.1.1") - .type(NetworkInterface.AccessConfig.Type.ONE_TO_ONE_NAT) - .build(); - private static final List ACCESS_CONFIGURATIONS = + private static final AccessConfig ACCESS_CONFIG = + AccessConfig.newBuilder() + .setName("accessConfig") + .setNatIp("192.168.1.1") + .setType(AccessConfig.Type.ONE_TO_ONE_NAT) + .build(); + private static final AccessConfig DEPRECATED_ACCESS_CONFIG = + AccessConfig.builder() + .name("accessConfig") + .natIp("192.168.1.1") + .type(AccessConfig.Type.ONE_TO_ONE_NAT) + .build(); + private static final List ACCESS_CONFIGURATIONS = ImmutableList.of(ACCESS_CONFIG); - private static final NetworkInterface NETWORK_INTERFACE = NetworkInterface.builder(NETWORK) - .name(NAME) - .networkIp(NETWORK_IP) + private static final NetworkInterface NETWORK_INTERFACE = NetworkInterface.newBuilder(NETWORK) + .setName(NAME) + .setNetworkIp(NETWORK_IP) + .setSubnetwork(SUBNETWORK) + .setAccessConfigurations(ACCESS_CONFIGURATIONS) + .build(); + private static final NetworkInterface DEPRECATED_NETWORK_INTERFACE = + NetworkInterface.builder(NETWORK) + .setName(NAME) + .setNetworkIp(NETWORK_IP) .subnetwork(SUBNETWORK) .accessConfigurations(ACCESS_CONFIGURATIONS) .build(); @Test public void testAccessConfigToBuilder() { - NetworkInterface.AccessConfig accessConfig = ACCESS_CONFIG.toBuilder().name("newName").build(); + AccessConfig accessConfig = + ACCESS_CONFIG.toBuilder().setName("newName").build(); + assertEquals("newName", accessConfig.getName()); + compareAccessConfig(ACCESS_CONFIG, accessConfig.toBuilder().setName("accessConfig").build()); + } + + @Test + public void testAccessConfigToBuilderDeprecated() { + AccessConfig accessConfig = + DEPRECATED_ACCESS_CONFIG.toBuilder().name("newName").build(); assertEquals("newName", accessConfig.name()); - compareAccessConfig(ACCESS_CONFIG, accessConfig.toBuilder().name("accessConfig").build()); + compareAccessConfig(DEPRECATED_ACCESS_CONFIG, + accessConfig.toBuilder().name("accessConfig").build()); } @Test public void testAccessConfigToBuilderIncomplete() { - NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.of(); + AccessConfig accessConfig = AccessConfig.of(); compareAccessConfig(accessConfig, accessConfig.toBuilder().build()); } @Test public void testToBuilder() { compareNetworkInterface(NETWORK_INTERFACE, NETWORK_INTERFACE.toBuilder().build()); - NetworkInterface networkInterface = NETWORK_INTERFACE.toBuilder().name("newInterface").build(); - assertEquals("newInterface", networkInterface.name()); - networkInterface = networkInterface.toBuilder().name(NAME).build(); + NetworkInterface networkInterface = + NETWORK_INTERFACE.toBuilder().setName("newInterface").build(); + assertEquals("newInterface", networkInterface.getName()); + networkInterface = networkInterface.toBuilder().setName(NAME).build(); compareNetworkInterface(NETWORK_INTERFACE, networkInterface); } @@ -72,27 +98,47 @@ public void testToBuilder() { public void testToBuilderIncomplete() { NetworkInterface networkInterface = NetworkInterface.of(NETWORK); assertEquals(networkInterface, networkInterface.toBuilder().build()); - networkInterface = NetworkInterface.of(NETWORK.network()); + networkInterface = NetworkInterface.of(NETWORK.getNetwork()); assertEquals(networkInterface, networkInterface.toBuilder().build()); } @Test public void testAccessConfigBuilder() { - assertEquals("accessConfig", ACCESS_CONFIG.name()); - assertEquals("192.168.1.1", ACCESS_CONFIG.natIp()); - Assert.assertEquals(NetworkInterface.AccessConfig.Type.ONE_TO_ONE_NAT, ACCESS_CONFIG.type()); + assertEquals("accessConfig", ACCESS_CONFIG.getName()); + assertEquals("192.168.1.1", ACCESS_CONFIG.getNatIp()); + assertEquals(AccessConfig.Type.ONE_TO_ONE_NAT, ACCESS_CONFIG.getType()); } @Test public void testBuilder() { - assertEquals(NAME, NETWORK_INTERFACE.name()); - assertEquals(NETWORK, NETWORK_INTERFACE.network()); - assertEquals(NETWORK_IP, NETWORK_INTERFACE.networkIp()); - assertEquals(SUBNETWORK, NETWORK_INTERFACE.subnetwork()); - assertEquals(ACCESS_CONFIGURATIONS, NETWORK_INTERFACE.accessConfigurations()); + assertEquals(NAME, NETWORK_INTERFACE.getName()); + assertEquals(NETWORK, NETWORK_INTERFACE.getNetwork()); + assertEquals(NETWORK_IP, NETWORK_INTERFACE.getNetworkIp()); + assertEquals(SUBNETWORK, NETWORK_INTERFACE.getSubnetwork()); + assertEquals(ACCESS_CONFIGURATIONS, NETWORK_INTERFACE.getAccessConfigurations()); + NetworkInterface networkInterface = NetworkInterface.newBuilder("network") + .setName(NAME) + .setNetworkIp(NETWORK_IP) + .setSubnetwork(SUBNETWORK) + .setAccessConfigurations(ACCESS_CONFIG) + .build(); + assertEquals(NAME, networkInterface.getName()); + assertEquals(NetworkId.of("network"), networkInterface.getNetwork()); + assertEquals(NETWORK_IP, networkInterface.getNetworkIp()); + assertEquals(SUBNETWORK, networkInterface.getSubnetwork()); + assertEquals(ACCESS_CONFIGURATIONS, networkInterface.getAccessConfigurations()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(NAME, DEPRECATED_NETWORK_INTERFACE.name()); + assertEquals(NETWORK, DEPRECATED_NETWORK_INTERFACE.network()); + assertEquals(NETWORK_IP, DEPRECATED_NETWORK_INTERFACE.networkIp()); + assertEquals(SUBNETWORK, DEPRECATED_NETWORK_INTERFACE.subnetwork()); + assertEquals(ACCESS_CONFIGURATIONS, DEPRECATED_NETWORK_INTERFACE.accessConfigurations()); NetworkInterface networkInterface = NetworkInterface.builder("network") - .name(NAME) - .networkIp(NETWORK_IP) + .setName(NAME) + .setNetworkIp(NETWORK_IP) .subnetwork(SUBNETWORK) .accessConfigurations(ACCESS_CONFIG) .build(); @@ -105,37 +151,38 @@ public void testBuilder() { @Test public void testAccessConfigOf() { - NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.of("192.168.1.1"); - assertNull(accessConfig.name()); - assertEquals("192.168.1.1", accessConfig.natIp()); - assertNull(accessConfig.type()); - accessConfig = NetworkInterface.AccessConfig.of(); - assertNull(accessConfig.name()); - assertNull(accessConfig.natIp()); - assertNull(accessConfig.type()); + AccessConfig accessConfig = AccessConfig.of("192.168.1.1"); + assertNull(accessConfig.getName()); + assertEquals("192.168.1.1", accessConfig.getNatIp()); + assertNull(accessConfig.getType()); + accessConfig = AccessConfig.of(); + assertNull(accessConfig.getName()); + assertNull(accessConfig.getNatIp()); + assertNull(accessConfig.getType()); } @Test public void testOf() { NetworkInterface networkInterface = NetworkInterface.of(NETWORK); - assertNull(networkInterface.name()); - assertEquals(NETWORK, networkInterface.network()); - assertNull(networkInterface.networkIp()); - assertNull(networkInterface.subnetwork()); - networkInterface = NetworkInterface.of(NETWORK.network()); - assertNull(networkInterface.name()); - assertNull(networkInterface.network().project()); - assertEquals(NETWORK.network(), networkInterface.network().network()); - assertNull(networkInterface.networkIp()); - assertNull(networkInterface.subnetwork()); + assertNull(networkInterface.getName()); + assertEquals(NETWORK, networkInterface.getNetwork()); + assertNull(networkInterface.getNetworkIp()); + assertNull(networkInterface.getSubnetwork()); + networkInterface = NetworkInterface.of(NETWORK.getNetwork()); + assertNull(networkInterface.getName()); + assertNull(networkInterface.getNetwork().getProject()); + assertEquals(NETWORK.getNetwork(), networkInterface.getNetwork().getNetwork()); + assertNull(networkInterface.getNetworkIp()); + assertNull(networkInterface.getSubnetwork()); } @Test public void testAccessConfigToAndFromPb() { - NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.fromPb(ACCESS_CONFIG.toPb()); + AccessConfig accessConfig = + AccessConfig.fromPb(ACCESS_CONFIG.toPb()); compareAccessConfig(ACCESS_CONFIG, accessConfig); - accessConfig = NetworkInterface.AccessConfig.of(); - compareAccessConfig(accessConfig, NetworkInterface.AccessConfig.fromPb(accessConfig.toPb())); + accessConfig = AccessConfig.of(); + compareAccessConfig(accessConfig, AccessConfig.fromPb(accessConfig.toPb())); } @Test @@ -152,27 +199,27 @@ public void testSetProjectId() { compareNetworkInterface(networkInterface, NetworkInterface.of(NetworkId.of("network")).setProjectId("project")); networkInterface = NETWORK_INTERFACE.toBuilder() - .network(NetworkId.of("network")) - .subnetwork(SubnetworkId.of("region", "subnetwork")) + .setNetwork(NetworkId.of("network")) + .setSubnetwork(SubnetworkId.of("region", "subnetwork")) .build(); compareNetworkInterface(NETWORK_INTERFACE, networkInterface.setProjectId("project")); } - public void compareAccessConfig(NetworkInterface.AccessConfig expected, NetworkInterface.AccessConfig value) { + public void compareAccessConfig(AccessConfig expected, AccessConfig value) { assertEquals(expected, value); - assertEquals(expected.name(), value.name()); - assertEquals(expected.natIp(), value.natIp()); - assertEquals(expected.type(), value.type()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getNatIp(), value.getNatIp()); + assertEquals(expected.getType(), value.getType()); assertEquals(expected.hashCode(), value.hashCode()); } public void compareNetworkInterface(NetworkInterface expected, NetworkInterface value) { assertEquals(expected, value); - assertEquals(expected.name(), value.name()); - assertEquals(expected.network(), value.network()); - assertEquals(expected.networkIp(), value.networkIp()); - assertEquals(expected.subnetwork(), value.subnetwork()); - assertEquals(expected.accessConfigurations(), value.accessConfigurations()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getNetwork(), value.getNetwork()); + assertEquals(expected.getNetworkIp(), value.getNetworkIp()); + assertEquals(expected.getSubnetwork(), value.getSubnetwork()); + assertEquals(expected.getAccessConfigurations(), value.getAccessConfigurations()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkTest.java index 5bc240fafddc..73ba3a346799 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkTest.java @@ -62,24 +62,24 @@ private void initializeExpectedNetwork(int optionsCalls) { replay(serviceMockReturnsOptions); standardNetwork = new Network.Builder(serviceMockReturnsOptions, NETWORK_ID, NETWORK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) .build(); subnetNetwork = new Network.Builder(serviceMockReturnsOptions, NETWORK_ID, SUBNET_NETWORK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) .build(); compute = createStrictMock(Compute.class); } private void initializeNetwork() { network = new Network.Builder(compute, NETWORK_ID, NETWORK_CONFIGURATION) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) .build(); } @@ -87,9 +87,9 @@ private void initializeNetwork() { public void testToBuilder() { initializeExpectedNetwork(9); compareNetwork(standardNetwork, standardNetwork.toBuilder().build()); - Network newNetwork = standardNetwork.toBuilder().description("newDescription").build(); - assertEquals("newDescription", newNetwork.description()); - newNetwork = newNetwork.toBuilder().description("description").build(); + Network newNetwork = standardNetwork.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", newNetwork.getDescription()); + newNetwork = newNetwork.toBuilder().setDescription("description").build(); compareNetwork(standardNetwork, newNetwork); } @@ -104,6 +104,23 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { + initializeExpectedNetwork(2); + assertEquals(GENERATED_ID, standardNetwork.getGeneratedId()); + assertEquals(NETWORK_ID, standardNetwork.getNetworkId()); + assertEquals(CREATION_TIMESTAMP, standardNetwork.getCreationTimestamp()); + assertEquals(DESCRIPTION, standardNetwork.getDescription()); + assertEquals(NETWORK_CONFIGURATION, standardNetwork.getConfiguration()); + assertSame(serviceMockReturnsOptions, standardNetwork.getCompute()); + assertEquals(GENERATED_ID, subnetNetwork.getGeneratedId()); + assertEquals(NETWORK_ID, subnetNetwork.getNetworkId()); + assertEquals(CREATION_TIMESTAMP, subnetNetwork.getCreationTimestamp()); + assertEquals(DESCRIPTION, subnetNetwork.getDescription()); + assertEquals(SUBNET_NETWORK_CONFIGURATION, subnetNetwork.getConfiguration()); + assertSame(serviceMockReturnsOptions, subnetNetwork.getCompute()); + } + + @Test + public void testBuilderDeprecated() { initializeExpectedNetwork(2); assertEquals(GENERATED_ID, standardNetwork.generatedId()); assertEquals(NETWORK_ID, standardNetwork.networkId()); @@ -136,9 +153,9 @@ public void testDeleteOperation() { initializeExpectedNetwork(3); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(GlobalOperationId.of("project", "op")) + .setOperationId(GlobalOperationId.of("project", "op")) .build(); - expect(compute.deleteNetwork(NETWORK_ID.network())).andReturn(operation); + expect(compute.deleteNetwork(NETWORK_ID.getNetwork())).andReturn(operation); replay(compute); initializeNetwork(); assertSame(operation, network.delete()); @@ -148,7 +165,7 @@ public void testDeleteOperation() { public void testDeleteNull() { initializeExpectedNetwork(2); expect(compute.options()).andReturn(mockOptions); - expect(compute.deleteNetwork(NETWORK_ID.network())).andReturn(null); + expect(compute.deleteNetwork(NETWORK_ID.getNetwork())).andReturn(null); replay(compute); initializeNetwork(); assertNull(network.delete()); @@ -159,7 +176,7 @@ public void testExists_True() throws Exception { initializeExpectedNetwork(2); Compute.NetworkOption[] expectedOptions = {Compute.NetworkOption.fields()}; expect(compute.options()).andReturn(mockOptions); - expect(compute.getNetwork(NETWORK_ID.network(), expectedOptions)) + expect(compute.getNetwork(NETWORK_ID.getNetwork(), expectedOptions)) .andReturn(standardNetwork); replay(compute); initializeNetwork(); @@ -172,7 +189,7 @@ public void testExists_False() throws Exception { initializeExpectedNetwork(2); Compute.NetworkOption[] expectedOptions = {Compute.NetworkOption.fields()}; expect(compute.options()).andReturn(mockOptions); - expect(compute.getNetwork(NETWORK_ID.network(), expectedOptions)).andReturn(null); + expect(compute.getNetwork(NETWORK_ID.getNetwork(), expectedOptions)).andReturn(null); replay(compute); initializeNetwork(); assertFalse(network.exists()); @@ -183,7 +200,7 @@ public void testExists_False() throws Exception { public void testReload() throws Exception { initializeExpectedNetwork(4); expect(compute.options()).andReturn(mockOptions); - expect(compute.getNetwork(NETWORK_ID.network())).andReturn(standardNetwork); + expect(compute.getNetwork(NETWORK_ID.getNetwork())).andReturn(standardNetwork); replay(compute); initializeNetwork(); Network updatedNetwork = network.reload(); @@ -195,7 +212,7 @@ public void testReload() throws Exception { public void testReloadNull() throws Exception { initializeExpectedNetwork(2); expect(compute.options()).andReturn(mockOptions); - expect(compute.getNetwork(NETWORK_ID.network())).andReturn(null); + expect(compute.getNetwork(NETWORK_ID.getNetwork())).andReturn(null); replay(compute); initializeNetwork(); assertNull(network.reload()); @@ -206,7 +223,7 @@ public void testReloadNull() throws Exception { public void testReloadWithOptions() throws Exception { initializeExpectedNetwork(4); expect(compute.options()).andReturn(mockOptions); - expect(compute.getNetwork(NETWORK_ID.network(), Compute.NetworkOption.fields())) + expect(compute.getNetwork(NETWORK_ID.getNetwork(), Compute.NetworkOption.fields())) .andReturn(standardNetwork); replay(compute); initializeNetwork(); @@ -219,7 +236,7 @@ public void testReloadWithOptions() throws Exception { public void testCreateSubnetwork() throws Exception { initializeExpectedNetwork(3); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(RegionOperationId.of(SUBNETWORK1.regionId(), "op")) + .setOperationId(RegionOperationId.of(SUBNETWORK1.getRegionId(), "op")) .build(); expect(compute.options()).andReturn(mockOptions); expect(compute.create(SubnetworkInfo.of(SUBNETWORK1, NETWORK_ID, IP_RANGE))) @@ -234,7 +251,7 @@ public void testCreateSubnetwork() throws Exception { public void testCreateSubnetworkWithOptions() throws Exception { initializeExpectedNetwork(3); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(RegionOperationId.of(SUBNETWORK1.regionId(), "op")) + .setOperationId(RegionOperationId.of(SUBNETWORK1.getRegionId(), "op")) .build(); expect(compute.options()).andReturn(mockOptions); expect(compute.create(SubnetworkInfo.of(SUBNETWORK1, NETWORK_ID, IP_RANGE), @@ -248,12 +265,12 @@ public void testCreateSubnetworkWithOptions() throws Exception { public void compareNetwork(Network expected, Network value) { assertEquals(expected, value); - assertEquals(expected.compute().options(), value.compute().options()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.networkId(), value.networkId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.configuration(), value.configuration()); + assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getNetworkId(), value.getNetworkId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getConfiguration(), value.getConfiguration()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/OperationIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/OperationIdTest.java index 9944a6fc7585..58ea548a67f9 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/OperationIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/OperationIdTest.java @@ -44,6 +44,51 @@ public class OperationIdTest { @Test public void testOf() { + GlobalOperationId operationId = GlobalOperationId.of(PROJECT, NAME); + assertEquals(OperationId.Type.GLOBAL, operationId.getType()); + assertEquals(PROJECT, operationId.getProject()); + assertEquals(NAME, operationId.getOperation()); + assertEquals(GLOBAL_URL, operationId.getSelfLink()); + operationId = GlobalOperationId.of(NAME); + assertEquals(OperationId.Type.GLOBAL, operationId.getType()); + assertNull(operationId.getProject()); + assertEquals(NAME, operationId.getOperation()); + ZoneOperationId zoneOperationId = ZoneOperationId.of(PROJECT, ZONE, NAME); + assertEquals(OperationId.Type.ZONE, zoneOperationId.getType()); + assertEquals(PROJECT, zoneOperationId.getProject()); + assertEquals(ZONE, zoneOperationId.getZone()); + assertEquals(NAME, zoneOperationId.getOperation()); + assertEquals(ZONE_URL, zoneOperationId.getSelfLink()); + zoneOperationId = ZoneOperationId.of(ZONE, NAME); + assertEquals(OperationId.Type.ZONE, zoneOperationId.getType()); + assertNull(zoneOperationId.getProject()); + assertEquals(ZONE, zoneOperationId.getZone()); + assertEquals(NAME, zoneOperationId.getOperation()); + zoneOperationId = ZoneOperationId.of(ZoneId.of(PROJECT, ZONE), NAME); + assertEquals(OperationId.Type.ZONE, zoneOperationId.getType()); + assertEquals(PROJECT, zoneOperationId.getProject()); + assertEquals(ZONE, zoneOperationId.getZone()); + assertEquals(NAME, zoneOperationId.getOperation()); + RegionOperationId regionOperationId = RegionOperationId.of(PROJECT, REGION, NAME); + assertEquals(OperationId.Type.REGION, regionOperationId.getType()); + assertEquals(PROJECT, regionOperationId.getProject()); + assertEquals(REGION, regionOperationId.getRegion()); + assertEquals(NAME, regionOperationId.getOperation()); + assertEquals(REGION_URL, regionOperationId.getSelfLink()); + regionOperationId = RegionOperationId.of(REGION, NAME); + assertEquals(OperationId.Type.REGION, regionOperationId.getType()); + assertNull(regionOperationId.getProject()); + assertEquals(REGION, regionOperationId.getRegion()); + assertEquals(NAME, regionOperationId.getOperation()); + regionOperationId = RegionOperationId.of(RegionId.of(PROJECT, REGION), NAME); + assertEquals(OperationId.Type.REGION, regionOperationId.getType()); + assertEquals(PROJECT, regionOperationId.getProject()); + assertEquals(REGION, regionOperationId.getRegion()); + assertEquals(NAME, regionOperationId.getOperation()); + } + + @Test + public void testOfDeprecated() { GlobalOperationId operationId = GlobalOperationId.of(PROJECT, NAME); assertEquals(OperationId.Type.GLOBAL, operationId.type()); assertEquals(PROJECT, operationId.project()); @@ -90,7 +135,7 @@ public void testOf() { @Test public void testToAndFromUrlGlobal() { GlobalOperationId operationId = GlobalOperationId.of(PROJECT, NAME); - compareOperationId(operationId, GlobalOperationId.fromUrl(operationId.selfLink())); + compareOperationId(operationId, GlobalOperationId.fromUrl(operationId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid global operation URL"); GlobalOperationId.fromUrl("notMatchingUrl"); @@ -100,7 +145,7 @@ public void testToAndFromUrlGlobal() { public void testToAndFromUrlRegion() { RegionOperationId regionOperationId = RegionOperationId.of(PROJECT, REGION, NAME); compareRegionOperationId(regionOperationId, - RegionOperationId.fromUrl(regionOperationId.selfLink())); + RegionOperationId.fromUrl(regionOperationId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid region operation URL"); RegionOperationId.fromUrl("notMatchingUrl"); @@ -109,7 +154,7 @@ public void testToAndFromUrlRegion() { @Test public void testToAndFromUrlZone() { ZoneOperationId zoneOperationId = ZoneOperationId.of(PROJECT, ZONE, NAME); - compareZoneOperationId(zoneOperationId, ZoneOperationId.fromUrl(zoneOperationId.selfLink())); + compareZoneOperationId(zoneOperationId, ZoneOperationId.fromUrl(zoneOperationId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid zone operation URL"); ZoneOperationId.fromUrl("notMatchingUrl"); @@ -131,39 +176,39 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(GlobalOperationId.matchesUrl(GlobalOperationId.of(PROJECT, NAME).selfLink())); + assertTrue(GlobalOperationId.matchesUrl(GlobalOperationId.of(PROJECT, NAME).getSelfLink())); assertFalse(GlobalOperationId.matchesUrl("notMatchingUrl")); assertTrue( - RegionOperationId.matchesUrl(RegionOperationId.of(PROJECT, REGION, NAME).selfLink())); + RegionOperationId.matchesUrl(RegionOperationId.of(PROJECT, REGION, NAME).getSelfLink())); assertFalse(RegionOperationId.matchesUrl("notMatchingUrl")); - assertTrue(ZoneOperationId.matchesUrl(ZoneOperationId.of(PROJECT, REGION, NAME).selfLink())); + assertTrue(ZoneOperationId.matchesUrl(ZoneOperationId.of(PROJECT, REGION, NAME).getSelfLink())); assertFalse(ZoneOperationId.matchesUrl("notMatchingUrl")); } private void compareOperationId(GlobalOperationId expected, GlobalOperationId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.operation(), expected.operation()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getOperation(), expected.getOperation()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } private void compareZoneOperationId(ZoneOperationId expected, ZoneOperationId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.zone(), expected.zone()); - assertEquals(expected.operation(), expected.operation()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getZone(), expected.getZone()); + assertEquals(expected.getOperation(), expected.getOperation()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } private void compareRegionOperationId(RegionOperationId expected, RegionOperationId value) { assertEquals(expected, value); - assertEquals(expected.type(), value.type()); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.region(), expected.region()); - assertEquals(expected.operation(), expected.operation()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getType(), value.getType()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getRegion(), expected.getRegion()); + assertEquals(expected.getOperation(), expected.getOperation()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/OperationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/OperationTest.java index 975610f93609..1a499b0f67ea 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/OperationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/OperationTest.java @@ -96,88 +96,88 @@ private void initializeExpectedOperation(int optionsCalls) { expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); globalOperation = new Operation.Builder(serviceMockReturnsOptions) - .generatedId(GENERATED_ID) - .operationId(GLOBAL_OPERATION_ID) - .clientOperationId(CLIENT_OPERATION_ID) - .operationType(OPERATION_TYPE) - .targetLink(TARGET_LINK) - .targetId(TARGET_ID) - .status(STATUS) - .statusMessage(STATUS_MESSAGE) - .user(USER) - .progress(PROGRESS) - .insertTime(INSERT_TIME) - .startTime(START_TIME) - .endTime(END_TIME) - .errors(ERRORS) - .warnings(WARNINGS) - .httpErrorStatusCode(HTTP_ERROR_STATUS_CODE) - .httpErrorMessage(HTTP_ERROR_MESSAGE) - .description(DESCRIPTION) + .getGeneratedId(GENERATED_ID) + .setOperationId(GLOBAL_OPERATION_ID) + .setClientOperationId(CLIENT_OPERATION_ID) + .setOperationType(OPERATION_TYPE) + .setTargetLink(TARGET_LINK) + .setTargetId(TARGET_ID) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) + .setUser(USER) + .setProgress(PROGRESS) + .setInsertTime(INSERT_TIME) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setErrors(ERRORS) + .setWarnings(WARNINGS) + .setHttpErrorStatusCode(HTTP_ERROR_STATUS_CODE) + .setHttpErrorMessage(HTTP_ERROR_MESSAGE) + .setDescription(DESCRIPTION) .build(); zoneOperation = new Operation.Builder(serviceMockReturnsOptions) - .generatedId(GENERATED_ID) - .operationId(ZONE_OPERATION_ID) - .clientOperationId(CLIENT_OPERATION_ID) - .operationType(OPERATION_TYPE) - .targetLink(TARGET_LINK) - .targetId(TARGET_ID) - .status(STATUS) - .statusMessage(STATUS_MESSAGE) - .user(USER) - .progress(PROGRESS) - .insertTime(INSERT_TIME) - .startTime(START_TIME) - .endTime(END_TIME) - .errors(ERRORS) - .warnings(WARNINGS) - .httpErrorStatusCode(HTTP_ERROR_STATUS_CODE) - .httpErrorMessage(HTTP_ERROR_MESSAGE) - .description(DESCRIPTION) + .getGeneratedId(GENERATED_ID) + .setOperationId(ZONE_OPERATION_ID) + .setClientOperationId(CLIENT_OPERATION_ID) + .setOperationType(OPERATION_TYPE) + .setTargetLink(TARGET_LINK) + .setTargetId(TARGET_ID) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) + .setUser(USER) + .setProgress(PROGRESS) + .setInsertTime(INSERT_TIME) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setErrors(ERRORS) + .setWarnings(WARNINGS) + .setHttpErrorStatusCode(HTTP_ERROR_STATUS_CODE) + .setHttpErrorMessage(HTTP_ERROR_MESSAGE) + .setDescription(DESCRIPTION) .build(); regionOperation = new Operation.Builder(serviceMockReturnsOptions) - .generatedId(GENERATED_ID) - .operationId(REGION_OPERATION_ID) - .clientOperationId(CLIENT_OPERATION_ID) - .operationType(OPERATION_TYPE) - .targetLink(TARGET_LINK) - .targetId(TARGET_ID) - .status(STATUS) - .statusMessage(STATUS_MESSAGE) - .user(USER) - .progress(PROGRESS) - .insertTime(INSERT_TIME) - .startTime(START_TIME) - .endTime(END_TIME) - .errors(ERRORS) - .warnings(WARNINGS) - .httpErrorStatusCode(HTTP_ERROR_STATUS_CODE) - .httpErrorMessage(HTTP_ERROR_MESSAGE) - .description(DESCRIPTION) + .getGeneratedId(GENERATED_ID) + .setOperationId(REGION_OPERATION_ID) + .setClientOperationId(CLIENT_OPERATION_ID) + .setOperationType(OPERATION_TYPE) + .setTargetLink(TARGET_LINK) + .setTargetId(TARGET_ID) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) + .setUser(USER) + .setProgress(PROGRESS) + .setInsertTime(INSERT_TIME) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setErrors(ERRORS) + .setWarnings(WARNINGS) + .setHttpErrorStatusCode(HTTP_ERROR_STATUS_CODE) + .setHttpErrorMessage(HTTP_ERROR_MESSAGE) + .setDescription(DESCRIPTION) .build(); compute = createStrictMock(Compute.class); } private void initializeOperation() { operation = new Operation.Builder(compute) - .generatedId(GENERATED_ID) - .operationId(GLOBAL_OPERATION_ID) - .clientOperationId(CLIENT_OPERATION_ID) - .operationType(OPERATION_TYPE) - .targetLink(TARGET_LINK) - .targetId(TARGET_ID) - .status(STATUS) - .statusMessage(STATUS_MESSAGE) - .user(USER) - .progress(PROGRESS) - .insertTime(INSERT_TIME) - .startTime(START_TIME) - .endTime(END_TIME) - .errors(ERRORS) - .warnings(WARNINGS) - .httpErrorStatusCode(HTTP_ERROR_STATUS_CODE) - .httpErrorMessage(HTTP_ERROR_MESSAGE) - .description(DESCRIPTION) + .getGeneratedId(GENERATED_ID) + .setOperationId(GLOBAL_OPERATION_ID) + .setClientOperationId(CLIENT_OPERATION_ID) + .setOperationType(OPERATION_TYPE) + .setTargetLink(TARGET_LINK) + .setTargetId(TARGET_ID) + .setStatus(STATUS) + .setStatusMessage(STATUS_MESSAGE) + .setUser(USER) + .setProgress(PROGRESS) + .setInsertTime(INSERT_TIME) + .setStartTime(START_TIME) + .setEndTime(END_TIME) + .setErrors(ERRORS) + .setWarnings(WARNINGS) + .setHttpErrorStatusCode(HTTP_ERROR_STATUS_CODE) + .setHttpErrorMessage(HTTP_ERROR_MESSAGE) + .setDescription(DESCRIPTION) .build(); } @@ -187,8 +187,29 @@ public void tearDown() throws Exception { } private void assertEqualsCommonFields(Operation operation) { + assertEquals(GENERATED_ID, operation.getGeneratedId()); + assertEquals(CLIENT_OPERATION_ID, operation.getClientOperationId()); + assertEquals(OPERATION_TYPE, operation.getOperationType()); + assertEquals(TARGET_LINK, operation.getTargetLink()); + assertEquals(TARGET_ID, operation.getTargetId()); + assertEquals(STATUS, operation.getStatus()); + assertEquals(STATUS_MESSAGE, operation.getStatusMessage()); + assertEquals(USER, operation.getUser()); + assertEquals(PROGRESS, operation.getProgress()); + assertEquals(INSERT_TIME, operation.getInsertTime()); + assertEquals(START_TIME, operation.getStartTime()); + assertEquals(END_TIME, operation.getEndTime()); + assertEquals(ERRORS, operation.getErrors()); + assertEquals(WARNINGS, operation.getWarnings()); + assertEquals(HTTP_ERROR_STATUS_CODE, globalOperation.getHttpErrorStatusCode()); + assertEquals(HTTP_ERROR_MESSAGE, globalOperation.getHttpErrorMessage()); + assertEquals(DESCRIPTION, globalOperation.getDescription()); + assertSame(serviceMockReturnsOptions, globalOperation.getCompute()); + } + + private void assertEqualsCommonFieldsDeprecated(Operation operation) { assertEquals(GENERATED_ID, operation.generatedId()); - assertEquals(CLIENT_OPERATION_ID, operation.clientOperationId()); + assertEquals(CLIENT_OPERATION_ID, operation.getClientOperationId()); assertEquals(OPERATION_TYPE, operation.operationType()); assertEquals(TARGET_LINK, operation.targetLink()); assertEquals(TARGET_ID, operation.targetId()); @@ -208,8 +229,29 @@ private void assertEqualsCommonFields(Operation operation) { } private void assertNullCommonFields(Operation operation) { + assertNull(operation.getGeneratedId()); + assertNull(operation.getClientOperationId()); + assertNull(operation.getOperationType()); + assertNull(operation.getTargetLink()); + assertNull(operation.getTargetId()); + assertNull(operation.getStatus()); + assertNull(operation.getStatusMessage()); + assertNull(operation.getUser()); + assertNull(operation.getProgress()); + assertNull(operation.getInsertTime()); + assertNull(operation.getStartTime()); + assertNull(operation.getEndTime()); + assertNull(operation.getErrors()); + assertNull(operation.getWarnings()); + assertNull(operation.getHttpErrorStatusCode()); + assertNull(operation.getHttpErrorMessage()); + assertNull(operation.getDescription()); + assertSame(serviceMockReturnsOptions, operation.getCompute()); + } + + private void assertNullCommonFieldsDeprecated(Operation operation) { assertNull(operation.generatedId()); - assertNull(operation.clientOperationId()); + assertNull(operation.getClientOperationId()); assertNull(operation.operationType()); assertNull(operation.targetLink()); assertNull(operation.targetId()); @@ -232,25 +274,51 @@ private void assertNullCommonFields(Operation operation) { public void testBuilder() { initializeExpectedOperation(6); assertEqualsCommonFields(globalOperation); - assertEquals(GLOBAL_OPERATION_ID, globalOperation.operationId()); + assertEquals(GLOBAL_OPERATION_ID, globalOperation.getOperationId()); assertEqualsCommonFields(regionOperation); - assertEquals(REGION_OPERATION_ID, regionOperation.operationId()); + assertEquals(REGION_OPERATION_ID, regionOperation.getOperationId()); assertEqualsCommonFields(zoneOperation); - assertEquals(ZONE_OPERATION_ID, zoneOperation.operationId()); + assertEquals(ZONE_OPERATION_ID, zoneOperation.getOperationId()); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(GLOBAL_OPERATION_ID) + .setOperationId(GLOBAL_OPERATION_ID) .build(); assertNullCommonFields(operation); - assertEquals(GLOBAL_OPERATION_ID, operation.operationId()); + assertEquals(GLOBAL_OPERATION_ID, operation.getOperationId()); operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZONE_OPERATION_ID) + .setOperationId(ZONE_OPERATION_ID) .build(); assertNullCommonFields(operation); - assertEquals(ZONE_OPERATION_ID, operation.operationId()); + assertEquals(ZONE_OPERATION_ID, operation.getOperationId()); operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(REGION_OPERATION_ID) + .setOperationId(REGION_OPERATION_ID) .build(); assertNullCommonFields(operation); + assertEquals(REGION_OPERATION_ID, operation.getOperationId()); + } + + @Test + public void testBuilderDeprecated() { + initializeExpectedOperation(6); + assertEqualsCommonFieldsDeprecated(globalOperation); + assertEquals(GLOBAL_OPERATION_ID, globalOperation.operationId()); + assertEqualsCommonFieldsDeprecated(regionOperation); + assertEquals(REGION_OPERATION_ID, regionOperation.operationId()); + assertEqualsCommonFieldsDeprecated(zoneOperation); + assertEquals(ZONE_OPERATION_ID, zoneOperation.operationId()); + Operation operation = new Operation.Builder(serviceMockReturnsOptions) + .setOperationId(GLOBAL_OPERATION_ID) + .build(); + assertNullCommonFieldsDeprecated(operation); + assertEquals(GLOBAL_OPERATION_ID, operation.operationId()); + operation = new Operation.Builder(serviceMockReturnsOptions) + .setOperationId(ZONE_OPERATION_ID) + .build(); + assertNullCommonFieldsDeprecated(operation); + assertEquals(ZONE_OPERATION_ID, operation.operationId()); + operation = new Operation.Builder(serviceMockReturnsOptions) + .setOperationId(REGION_OPERATION_ID) + .build(); + assertNullCommonFieldsDeprecated(operation); assertEquals(REGION_OPERATION_ID, operation.operationId()); } @@ -266,15 +334,15 @@ public void testToAndFromPb() { compareOperation(zoneOperation, Operation.fromPb(serviceMockReturnsOptions, zoneOperation.toPb())); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(GLOBAL_OPERATION_ID) + .setOperationId(GLOBAL_OPERATION_ID) .build(); compareOperation(operation, Operation.fromPb(serviceMockReturnsOptions, operation.toPb())); operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(ZONE_OPERATION_ID) + .setOperationId(ZONE_OPERATION_ID) .build(); compareOperation(operation, Operation.fromPb(serviceMockReturnsOptions, operation.toPb())); operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(REGION_OPERATION_ID) + .setOperationId(REGION_OPERATION_ID) .build(); compareOperation(operation, Operation.fromPb(serviceMockReturnsOptions, operation.toPb())); } @@ -505,24 +573,24 @@ public void testReloadWithOptions() throws Exception { private void compareOperation(Operation expected, Operation value) { assertEquals(expected, value); - assertEquals(expected.compute().options(), value.compute().options()); - assertEquals(expected.operationId(), value.operationId()); - assertEquals(expected.clientOperationId(), value.clientOperationId()); - assertEquals(expected.operationType(), value.operationType()); - assertEquals(expected.targetLink(), value.targetLink()); - assertEquals(expected.targetId(), value.targetId()); - assertEquals(expected.status(), value.status()); - assertEquals(expected.statusMessage(), value.statusMessage()); - assertEquals(expected.user(), value.user()); - assertEquals(expected.progress(), value.progress()); - assertEquals(expected.insertTime(), value.insertTime()); - assertEquals(expected.startTime(), value.startTime()); - assertEquals(expected.endTime(), value.endTime()); - assertEquals(expected.errors(), value.errors()); - assertEquals(expected.warnings(), value.warnings()); - assertEquals(expected.httpErrorStatusCode(), value.httpErrorStatusCode()); - assertEquals(expected.httpErrorMessage(), value.httpErrorMessage()); - assertEquals(expected.description(), value.description()); + assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getOperationId(), value.getOperationId()); + assertEquals(expected.getClientOperationId(), value.getClientOperationId()); + assertEquals(expected.getOperationType(), value.getOperationType()); + assertEquals(expected.getTargetLink(), value.getTargetLink()); + assertEquals(expected.getTargetId(), value.getTargetId()); + assertEquals(expected.getStatus(), value.getStatus()); + assertEquals(expected.getStatusMessage(), value.getStatusMessage()); + assertEquals(expected.getUser(), value.getUser()); + assertEquals(expected.getProgress(), value.getProgress()); + assertEquals(expected.getInsertTime(), value.getInsertTime()); + assertEquals(expected.getStartTime(), value.getStartTime()); + assertEquals(expected.getEndTime(), value.getEndTime()); + assertEquals(expected.getErrors(), value.getErrors()); + assertEquals(expected.getWarnings(), value.getWarnings()); + assertEquals(expected.getHttpErrorStatusCode(), value.getHttpErrorStatusCode()); + assertEquals(expected.getHttpErrorMessage(), value.getHttpErrorMessage()); + assertEquals(expected.getDescription(), value.getDescription()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/RegionIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/RegionIdTest.java index c6646db93acf..0e0a3ac9dce7 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/RegionIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/RegionIdTest.java @@ -38,6 +38,17 @@ public class RegionIdTest { @Test public void testOf() { + RegionId regionId = RegionId.of(PROJECT, REGION); + assertEquals(PROJECT, regionId.getProject()); + assertEquals(REGION, regionId.getRegion()); + assertEquals(URL, regionId.getSelfLink()); + regionId = RegionId.of(REGION); + assertNull(regionId.getProject()); + assertEquals(REGION, regionId.getRegion()); + } + + @Test + public void testOfDeprecated() { RegionId regionId = RegionId.of(PROJECT, REGION); assertEquals(PROJECT, regionId.project()); assertEquals(REGION, regionId.region()); @@ -50,7 +61,7 @@ public void testOf() { @Test public void testToAndFromUrl() { RegionId regionId = RegionId.of(PROJECT, REGION); - compareRegionId(regionId, RegionId.fromUrl(regionId.selfLink())); + compareRegionId(regionId, RegionId.fromUrl(regionId.getSelfLink())); } @Test @@ -65,15 +76,15 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(RegionId.matchesUrl(RegionId.of(PROJECT, REGION).selfLink())); + assertTrue(RegionId.matchesUrl(RegionId.of(PROJECT, REGION).getSelfLink())); assertFalse(RegionId.matchesUrl("notMatchingUrl")); } private void compareRegionId(RegionId expected, RegionId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.region(), expected.region()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getRegion(), expected.getRegion()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/RegionTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/RegionTest.java index 80e2fdc0b027..50c0fd1ce66d 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/RegionTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/RegionTest.java @@ -42,18 +42,30 @@ public class RegionTest { private static final DeprecationStatus DEPRECATION_STATUS = DeprecationStatus.of(DeprecationStatus.Status.DELETED, REGION_ID); private static final Region REGION = Region.builder() - .regionId(REGION_ID) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .zones(ZONES) - .quotas(QUOTAS) - .deprecationStatus(DEPRECATION_STATUS) + .setRegionId(REGION_ID) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setZones(ZONES) + .setQuotas(QUOTAS) + .setDeprecationStatus(DEPRECATION_STATUS) .build(); @Test public void testBuilder() { + assertEquals(REGION_ID, REGION.getRegionId()); + assertEquals(GENERATED_ID, REGION.getGeneratedId()); + assertEquals(CREATION_TIMESTAMP, REGION.getCreationTimestamp()); + assertEquals(DESCRIPTION, REGION.getDescription()); + assertEquals(STATUS, REGION.getStatus()); + assertEquals(ZONES, REGION.getZones()); + assertEquals(QUOTAS, REGION.getQuotas()); + assertEquals(DEPRECATION_STATUS, REGION.getDeprecationStatus()); + } + + @Test + public void testBuilderDeprecated() { assertEquals(REGION_ID, REGION.regionId()); assertEquals(GENERATED_ID, REGION.generatedId()); assertEquals(CREATION_TIMESTAMP, REGION.creationTimestamp()); @@ -68,22 +80,22 @@ public void testBuilder() { public void testToAndFromPb() { Region region = Region.fromPb(REGION.toPb()); compareRegions(REGION, region); - assertEquals(REGION_ID.project(), region.regionId().project()); - assertEquals(REGION_ID.region(), region.regionId().region()); - region = Region.builder().regionId(REGION_ID).build(); + assertEquals(REGION_ID.getProject(), region.getRegionId().getProject()); + assertEquals(REGION_ID.getRegion(), region.getRegionId().getRegion()); + region = Region.builder().setRegionId(REGION_ID).build(); compareRegions(region, Region.fromPb(region.toPb())); } private void compareRegions(Region expected, Region value) { assertEquals(expected, value); - assertEquals(expected.regionId(), value.regionId()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.status(), value.status()); - assertEquals(expected.zones(), value.zones()); - assertEquals(expected.quotas(), value.quotas()); - assertEquals(expected.deprecationStatus(), value.deprecationStatus()); + assertEquals(expected.getRegionId(), value.getRegionId()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getStatus(), value.getStatus()); + assertEquals(expected.getZones(), value.getZones()); + assertEquals(expected.getQuotas(), value.getQuotas()); + assertEquals(expected.getDeprecationStatus(), value.getDeprecationStatus()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SchedulingOptionsTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SchedulingOptionsTest.java index de2c66a5ff1e..52acaecdddd0 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SchedulingOptionsTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SchedulingOptionsTest.java @@ -28,6 +28,18 @@ public class SchedulingOptionsTest { @Test public void testFactoryMethods() { + assertTrue(SCHEDULING_OPTIONS.isPreemptible()); + assertFalse(SCHEDULING_OPTIONS.automaticRestart()); + assertEquals(SchedulingOptions.Maintenance.TERMINATE, SCHEDULING_OPTIONS.getMaintenance()); + SchedulingOptions schedulingOptions = + SchedulingOptions.standard(true, SchedulingOptions.Maintenance.MIGRATE); + assertFalse(schedulingOptions.isPreemptible()); + assertTrue(schedulingOptions.automaticRestart()); + assertEquals(SchedulingOptions.Maintenance.MIGRATE, schedulingOptions.getMaintenance()); + } + + @Test + public void testFactoryMethodsDeprecated() { assertTrue(SCHEDULING_OPTIONS.isPreemptible()); assertFalse(SCHEDULING_OPTIONS.automaticRestart()); assertEquals(SchedulingOptions.Maintenance.TERMINATE, SCHEDULING_OPTIONS.maintenance()); @@ -50,7 +62,7 @@ public void testToAndFromPb() { public void compareSchedulingOptions(SchedulingOptions expected, SchedulingOptions value) { assertEquals(expected, value); assertEquals(expected.isPreemptible(), value.isPreemptible()); - assertEquals(expected.maintenance(), value.maintenance()); + assertEquals(expected.getMaintenance(), value.getMaintenance()); assertEquals(expected.automaticRestart(), value.automaticRestart()); assertEquals(expected.hashCode(), value.hashCode()); } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java index 0ef68731183d..ea3b7be1e1c9 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java @@ -38,12 +38,12 @@ public class SerializationTest extends BaseSerializationTest { private static final String VALID_DISK_SIZE = "10GB-10TB"; private static final Long DEFAULT_DISK_SIZE_GB = 10L; private static final DiskTypeId DISK_TYPE_ID = DiskTypeId.of("project", "zone", "diskType"); - private static final DiskType DISK_TYPE = DiskType.builder() - .diskTypeId(DISK_TYPE_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .validDiskSize(VALID_DISK_SIZE) - .defaultDiskSizeGb(DEFAULT_DISK_SIZE_GB) + private static final DiskType DISK_TYPE = DiskType.newBuilder() + .setDiskTypeId(DISK_TYPE_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setValidDiskSize(VALID_DISK_SIZE) + .setDefaultDiskSizeGb(DEFAULT_DISK_SIZE_GB) .build(); private static final MachineTypeId MACHINE_TYPE_ID = MachineTypeId.of("project", "zone", "type"); private static final Integer GUEST_CPUS = 1; @@ -51,15 +51,15 @@ public class SerializationTest extends BaseSerializationTest { private static final List SCRATCH_DISKS = ImmutableList.of(3); private static final Integer MAXIMUM_PERSISTENT_DISKS = 4; private static final Long MAXIMUM_PERSISTENT_DISKS_SIZE_GB = 5L; - private static final MachineType MACHINE_TYPE = MachineType.builder() - .machineTypeId(MACHINE_TYPE_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .cpus(GUEST_CPUS) - .memoryMb(MEMORY_MB) - .scratchDisksSizeGb(SCRATCH_DISKS) - .maximumPersistentDisks(MAXIMUM_PERSISTENT_DISKS) - .maximumPersistentDisksSizeGb(MAXIMUM_PERSISTENT_DISKS_SIZE_GB) + private static final MachineType MACHINE_TYPE = MachineType.newBuilder() + .setMachineTypeId(MACHINE_TYPE_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setCpus(GUEST_CPUS) + .setMemoryMb(MEMORY_MB) + .setScratchDisksSizeGb(SCRATCH_DISKS) + .setMaximumPersistentDisks(MAXIMUM_PERSISTENT_DISKS) + .setMaximumPersistentDisksSizeGb(MAXIMUM_PERSISTENT_DISKS_SIZE_GB) .build(); private static final RegionId REGION_ID = RegionId.of("project", "region"); private static final Region.Status REGION_STATUS = Region.Status.DOWN; @@ -72,21 +72,21 @@ public class SerializationTest extends BaseSerializationTest { new Region.Quota("METRIC2", 4, 3); private static final List QUOTAS = ImmutableList.of(QUOTA1, QUOTA2); private static final Region REGION = Region.builder() - .regionId(REGION_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(REGION_STATUS) - .zones(ZONES) - .quotas(QUOTAS) + .setRegionId(REGION_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(REGION_STATUS) + .setZones(ZONES) + .setQuotas(QUOTAS) .build(); private static final ZoneId ZONE_ID = ZoneId.of("project", "zone"); private static final Zone.Status ZONE_STATUS = Zone.Status.DOWN; private static final Zone ZONE = Zone.builder() - .zoneId(ZONE_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(ZONE_STATUS) - .region(REGION_ID) + .setZoneId(ZONE_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(ZONE_STATUS) + .setRegion(REGION_ID) .build(); private static final DeprecationStatus DEPRECATION_STATUS = DeprecationStatus.of(DeprecationStatus.Status.DELETED, MACHINE_TYPE_ID); @@ -100,11 +100,11 @@ public class SerializationTest extends BaseSerializationTest { private static final RegionOperationId REGION_OPERATION_ID = RegionOperationId.of("project", "region", "op"); private static final Operation GLOBAL_OPERATION = - new Operation.Builder(COMPUTE).operationId(GLOBAL_OPERATION_ID).build(); + new Operation.Builder(COMPUTE).setOperationId(GLOBAL_OPERATION_ID).build(); private static final Operation ZONE_OPERATION = - new Operation.Builder(COMPUTE).operationId(ZONE_OPERATION_ID).build(); + new Operation.Builder(COMPUTE).setOperationId(ZONE_OPERATION_ID).build(); private static final Operation REGION_OPERATION = - new Operation.Builder(COMPUTE).operationId(REGION_OPERATION_ID).build(); + new Operation.Builder(COMPUTE).setOperationId(REGION_OPERATION_ID).build(); private static final InstanceId INSTANCE_ID = InstanceId.of("project", "zone", "instance"); private static final GlobalForwardingRuleId GLOBAL_FORWARDING_RULE_ID = GlobalForwardingRuleId.of("project", "rule"); @@ -119,10 +119,10 @@ public class SerializationTest extends BaseSerializationTest { new AddressInfo.GlobalForwardingUsage(ImmutableList.of(GLOBAL_FORWARDING_RULE_ID)); private static final AddressInfo.RegionForwardingUsage REGION_FORWARDING_USAGE = new AddressInfo.RegionForwardingUsage(ImmutableList.of(REGION_FORWARDING_RULE_ID)); - private static final AddressInfo ADDRESS_INFO = AddressInfo.builder(REGION_ADDRESS_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .usage(INSTANCE_USAGE) + private static final AddressInfo ADDRESS_INFO = AddressInfo.newBuilder(REGION_ADDRESS_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setUsage(INSTANCE_USAGE) .build(); private static final Address ADDRESS = new Address.Builder(COMPUTE, REGION_ADDRESS_ID).build(); private static final DiskId DISK_ID = DiskId.of("project", "zone", "disk"); @@ -163,8 +163,8 @@ public class SerializationTest extends BaseSerializationTest { private static final Network NETWORK = new Network.Builder(COMPUTE, NETWORK_ID, STANDARD_NETWORK_CONFIGURATION).build(); private static final AccessConfig ACCESS_CONFIG = AccessConfig.of("192.168.1.1"); - private static final NetworkInterface NETWORK_INTERFACE = NetworkInterface.builder(NETWORK_ID) - .accessConfigurations(ACCESS_CONFIG) + private static final NetworkInterface NETWORK_INTERFACE = NetworkInterface.newBuilder(NETWORK_ID) + .setAccessConfigurations(ACCESS_CONFIG) .build(); private static final CreateDiskConfiguration CREATE_DISK_CONFIGURATION = CreateDiskConfiguration.of(IMAGE_ID); diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/ServiceAccountTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/ServiceAccountTest.java index dd29589e5037..3634024718c3 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/ServiceAccountTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/ServiceAccountTest.java @@ -33,6 +33,12 @@ public void testOf() { compareServiceAccount(SERVICE_ACCOUNT, ServiceAccount.of("email", "scope1")); } + @Test + public void testOfDeprecated() { + assertEquals("email", SERVICE_ACCOUNT.email()); + assertEquals(ImmutableList.of("scope1"), SERVICE_ACCOUNT.scopes()); + } + @Test public void testToAndFromPb() { compareServiceAccount(SERVICE_ACCOUNT, ServiceAccount.fromPb(SERVICE_ACCOUNT.toPb())); @@ -40,8 +46,8 @@ public void testToAndFromPb() { public void compareServiceAccount(ServiceAccount expected, ServiceAccount value) { assertEquals(expected, value); - assertEquals(expected.email(), value.email()); - assertEquals(expected.scopes(), value.scopes()); + assertEquals(expected.getEmail(), value.getEmail()); + assertEquals(expected.getScopes(), value.getScopes()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotDiskConfigurationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotDiskConfigurationTest.java index 5f95891b3252..b397ba9625bd 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotDiskConfigurationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotDiskConfigurationTest.java @@ -31,10 +31,16 @@ public class SnapshotDiskConfigurationTest { private static final SnapshotId SNAPSHOT = SnapshotId.of("project", "snapshot"); private static final String SNAPSHOT_ID = "snapshotId"; private static final SnapshotDiskConfiguration DISK_CONFIGURATION = + SnapshotDiskConfiguration.newBuilder(SNAPSHOT) + .setSizeGb(SIZE) + .setDiskType(DISK_TYPE) + .setSourceSnapshotId(SNAPSHOT_ID) + .build(); + private static final SnapshotDiskConfiguration DEPRECATED_DISK_CONFIGURATION = SnapshotDiskConfiguration.builder(SNAPSHOT) .sizeGb(SIZE) .diskType(DISK_TYPE) - .sourceSnapshotId(SNAPSHOT_ID) + .setSourceSnapshotId(SNAPSHOT_ID) .build(); @Test @@ -42,17 +48,17 @@ public void testToBuilder() { compareSnapshotDiskConfiguration(DISK_CONFIGURATION, DISK_CONFIGURATION.toBuilder().build()); SnapshotId newSnapshot = SnapshotId.of("newProject", "newSnapshot"); SnapshotDiskConfiguration diskConfiguration = DISK_CONFIGURATION.toBuilder() - .sizeGb(24L) - .sourceSnapshot(newSnapshot) - .sourceSnapshotId("newSnapshotId") + .setSizeGb(24L) + .setSourceSnapshot(newSnapshot) + .setSourceSnapshotId("newSnapshotId") .build(); - assertEquals(24L, diskConfiguration.sizeGb().longValue()); - assertEquals(newSnapshot, diskConfiguration.sourceSnapshot()); - assertEquals("newSnapshotId", diskConfiguration.sourceSnapshotId()); + assertEquals(24L, diskConfiguration.getSizeGb().longValue()); + assertEquals(newSnapshot, diskConfiguration.getSourceSnapshot()); + assertEquals("newSnapshotId", diskConfiguration.getSourceSnapshotId()); diskConfiguration = diskConfiguration.toBuilder() - .sizeGb(SIZE) - .sourceSnapshot(SNAPSHOT) - .sourceSnapshotId(SNAPSHOT_ID) + .setSizeGb(SIZE) + .setSourceSnapshot(SNAPSHOT) + .setSourceSnapshotId(SNAPSHOT_ID) .build(); compareSnapshotDiskConfiguration(DISK_CONFIGURATION, diskConfiguration); } @@ -65,11 +71,20 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(DISK_TYPE, DISK_CONFIGURATION.diskType()); - assertEquals(SIZE, DISK_CONFIGURATION.sizeGb()); - assertEquals(SNAPSHOT, DISK_CONFIGURATION.sourceSnapshot()); - assertEquals(SNAPSHOT_ID, DISK_CONFIGURATION.sourceSnapshotId()); - assertEquals(Type.SNAPSHOT, DISK_CONFIGURATION.type()); + assertEquals(DISK_TYPE, DISK_CONFIGURATION.getDiskType()); + assertEquals(SIZE, DISK_CONFIGURATION.getSizeGb()); + assertEquals(SNAPSHOT, DISK_CONFIGURATION.getSourceSnapshot()); + assertEquals(SNAPSHOT_ID, DISK_CONFIGURATION.getSourceSnapshotId()); + assertEquals(Type.SNAPSHOT, DISK_CONFIGURATION.getType()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(DISK_TYPE, DEPRECATED_DISK_CONFIGURATION.diskType()); + assertEquals(SIZE, DEPRECATED_DISK_CONFIGURATION.sizeGb()); + assertEquals(SNAPSHOT, DEPRECATED_DISK_CONFIGURATION.sourceSnapshot()); + assertEquals(SNAPSHOT_ID, DEPRECATED_DISK_CONFIGURATION.sourceSnapshotId()); + assertEquals(Type.SNAPSHOT, DEPRECATED_DISK_CONFIGURATION.type()); } @Test @@ -83,18 +98,18 @@ public void testToAndFromPb() { @Test public void testOf() { SnapshotDiskConfiguration configuration = SnapshotDiskConfiguration.of(SNAPSHOT); - assertNull(configuration.diskType()); - assertNull(configuration.sizeGb()); - assertNull(configuration.sourceSnapshotId()); - assertEquals(SNAPSHOT, configuration.sourceSnapshot()); - assertEquals(Type.SNAPSHOT, configuration.type()); + assertNull(configuration.getDiskType()); + assertNull(configuration.getSizeGb()); + assertNull(configuration.getSourceSnapshotId()); + assertEquals(SNAPSHOT, configuration.getSourceSnapshot()); + assertEquals(Type.SNAPSHOT, configuration.getType()); } @Test public void testSetProjectId() { SnapshotDiskConfiguration configuration = DISK_CONFIGURATION.toBuilder() - .diskType(DiskTypeId.of(DISK_TYPE.zone(), DISK_TYPE.type())) - .sourceSnapshot(SnapshotId.of(SNAPSHOT.snapshot())) + .setDiskType(DiskTypeId.of(DISK_TYPE.getZone(), DISK_TYPE.getType())) + .setSourceSnapshot(SnapshotId.of(SNAPSHOT.getSnapshot())) .build(); compareSnapshotDiskConfiguration(DISK_CONFIGURATION, configuration.setProjectId("project")); } @@ -102,11 +117,11 @@ public void testSetProjectId() { private void compareSnapshotDiskConfiguration(SnapshotDiskConfiguration expected, SnapshotDiskConfiguration value) { assertEquals(expected, value); - assertEquals(expected.diskType(), value.diskType()); - assertEquals(expected.sizeGb(), value.sizeGb()); - assertEquals(expected.sourceSnapshot(), value.sourceSnapshot()); - assertEquals(expected.sourceSnapshotId(), value.sourceSnapshotId()); - assertEquals(expected.type(), value.type()); + assertEquals(expected.getDiskType(), value.getDiskType()); + assertEquals(expected.getSizeGb(), value.getSizeGb()); + assertEquals(expected.getSourceSnapshot(), value.getSourceSnapshot()); + assertEquals(expected.getSourceSnapshotId(), value.getSourceSnapshotId()); + assertEquals(expected.getType(), value.getType()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotIdTest.java index b723832dbbac..fbeff0650c62 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotIdTest.java @@ -38,6 +38,17 @@ public class SnapshotIdTest { @Test public void testOf() { + SnapshotId snapshotId = SnapshotId.of(PROJECT, NAME); + assertEquals(PROJECT, snapshotId.getProject()); + assertEquals(NAME, snapshotId.getSnapshot()); + assertEquals(URL, snapshotId.getSelfLink()); + snapshotId = SnapshotId.of(NAME); + assertNull(snapshotId.getProject()); + assertEquals(NAME, snapshotId.getSnapshot()); + } + + @Test + public void testOfDeprecated() { SnapshotId snapshotId = SnapshotId.of(PROJECT, NAME); assertEquals(PROJECT, snapshotId.project()); assertEquals(NAME, snapshotId.snapshot()); @@ -50,7 +61,7 @@ public void testOf() { @Test public void testToAndFromUrl() { SnapshotId snapshotId = SnapshotId.of(PROJECT, NAME); - compareSnapshotId(snapshotId, SnapshotId.fromUrl(snapshotId.selfLink())); + compareSnapshotId(snapshotId, SnapshotId.fromUrl(snapshotId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid snapshot URL"); SnapshotId.fromUrl("notMatchingUrl"); @@ -65,15 +76,15 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(SnapshotId.matchesUrl(SnapshotId.of(PROJECT, NAME).selfLink())); + assertTrue(SnapshotId.matchesUrl(SnapshotId.of(PROJECT, NAME).getSelfLink())); assertFalse(SnapshotId.matchesUrl("notMatchingUrl")); } private void compareSnapshotId(SnapshotId expected, SnapshotId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.snapshot(), expected.snapshot()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getSnapshot(), expected.getSnapshot()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotInfoTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotInfoTest.java index 38d295184ae6..9eff5b7a8141 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotInfoTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotInfoTest.java @@ -41,24 +41,37 @@ public class SnapshotInfoTest { private static final String SOURCE_DISK_ID = "diskId"; private static final Long STORAGE_BYTES = 24L; private static final StorageBytesStatus STORAGE_BYTES_STATUS = StorageBytesStatus.UP_TO_DATE; - private static final SnapshotInfo SNAPSHOT_INFO = SnapshotInfo.builder(SNAPSHOT_ID, SOURCE_DISK) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .diskSizeGb(DISK_SIZE_GB) - .licenses(LICENSES) - .sourceDiskId(SOURCE_DISK_ID) - .storageBytes(STORAGE_BYTES) - .storageBytesStatus(STORAGE_BYTES_STATUS) - .build(); + private static final SnapshotInfo SNAPSHOT_INFO = + SnapshotInfo.newBuilder(SNAPSHOT_ID, SOURCE_DISK) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setDiskSizeGb(DISK_SIZE_GB) + .setLicenses(LICENSES) + .setSourceDiskId(SOURCE_DISK_ID) + .setStorageBytes(STORAGE_BYTES) + .setStorageBytesStatus(STORAGE_BYTES_STATUS) + .build(); + private static final SnapshotInfo DEPRECATED_SNAPSHOT_INFO = + SnapshotInfo.builder(SNAPSHOT_ID, SOURCE_DISK) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .description(DESCRIPTION) + .setStatus(STATUS) + .setDiskSizeGb(DISK_SIZE_GB) + .setLicenses(LICENSES) + .setSourceDiskId(SOURCE_DISK_ID) + .setStorageBytes(STORAGE_BYTES) + .setStorageBytesStatus(STORAGE_BYTES_STATUS) + .build(); @Test public void testToBuilder() { compareSnapshotInfo(SNAPSHOT_INFO, SNAPSHOT_INFO.toBuilder().build()); - SnapshotInfo snapshotInfo = SNAPSHOT_INFO.toBuilder().description("newDescription").build(); - assertEquals("newDescription", snapshotInfo.description()); - snapshotInfo = snapshotInfo.toBuilder().description("description").build(); + SnapshotInfo snapshotInfo = SNAPSHOT_INFO.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", snapshotInfo.getDescription()); + snapshotInfo = snapshotInfo.toBuilder().setDescription("description").build(); compareSnapshotInfo(SNAPSHOT_INFO, snapshotInfo); } @@ -70,33 +83,48 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(GENERATED_ID, SNAPSHOT_INFO.generatedId()); - assertEquals(SNAPSHOT_ID, SNAPSHOT_INFO.snapshotId()); - assertEquals(CREATION_TIMESTAMP, SNAPSHOT_INFO.creationTimestamp()); - assertEquals(DESCRIPTION, SNAPSHOT_INFO.description()); - assertEquals(STATUS, SNAPSHOT_INFO.status()); - assertEquals(DISK_SIZE_GB, SNAPSHOT_INFO.diskSizeGb()); - assertEquals(LICENSES, SNAPSHOT_INFO.licenses()); - assertEquals(SOURCE_DISK, SNAPSHOT_INFO.sourceDisk()); - assertEquals(SOURCE_DISK_ID, SNAPSHOT_INFO.sourceDiskId()); - assertEquals(STORAGE_BYTES, SNAPSHOT_INFO.storageBytes()); - assertEquals(STORAGE_BYTES_STATUS, SNAPSHOT_INFO.storageBytesStatus()); + assertEquals(GENERATED_ID, SNAPSHOT_INFO.getGeneratedId()); + assertEquals(SNAPSHOT_ID, SNAPSHOT_INFO.getSnapshotId()); + assertEquals(CREATION_TIMESTAMP, SNAPSHOT_INFO.getCreationTimestamp()); + assertEquals(DESCRIPTION, SNAPSHOT_INFO.getDescription()); + assertEquals(STATUS, SNAPSHOT_INFO.getStatus()); + assertEquals(DISK_SIZE_GB, SNAPSHOT_INFO.getDiskSizeGb()); + assertEquals(LICENSES, SNAPSHOT_INFO.getLicenses()); + assertEquals(SOURCE_DISK, SNAPSHOT_INFO.getSourceDisk()); + assertEquals(SOURCE_DISK_ID, SNAPSHOT_INFO.getSourceDiskId()); + assertEquals(STORAGE_BYTES, SNAPSHOT_INFO.getStorageBytes()); + assertEquals(STORAGE_BYTES_STATUS, SNAPSHOT_INFO.getStorageBytesStatus()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(GENERATED_ID, DEPRECATED_SNAPSHOT_INFO.generatedId()); + assertEquals(SNAPSHOT_ID, DEPRECATED_SNAPSHOT_INFO.snapshotId()); + assertEquals(CREATION_TIMESTAMP, DEPRECATED_SNAPSHOT_INFO.creationTimestamp()); + assertEquals(DESCRIPTION, DEPRECATED_SNAPSHOT_INFO.description()); + assertEquals(STATUS, DEPRECATED_SNAPSHOT_INFO.status()); + assertEquals(DISK_SIZE_GB, DEPRECATED_SNAPSHOT_INFO.diskSizeGb()); + assertEquals(LICENSES, DEPRECATED_SNAPSHOT_INFO.licenses()); + assertEquals(SOURCE_DISK, DEPRECATED_SNAPSHOT_INFO.sourceDisk()); + assertEquals(SOURCE_DISK_ID, DEPRECATED_SNAPSHOT_INFO.sourceDiskId()); + assertEquals(STORAGE_BYTES, DEPRECATED_SNAPSHOT_INFO.storageBytes()); + assertEquals(STORAGE_BYTES_STATUS, DEPRECATED_SNAPSHOT_INFO.storageBytesStatus()); } @Test public void testOf() { SnapshotInfo snapshotInfo = SnapshotInfo.of(SNAPSHOT_ID, SOURCE_DISK); - assertNull(snapshotInfo.generatedId()); - assertEquals(SNAPSHOT_ID, snapshotInfo.snapshotId()); - assertNull(snapshotInfo.creationTimestamp()); - assertNull(snapshotInfo.description()); - assertNull(snapshotInfo.status()); - assertNull(snapshotInfo.diskSizeGb()); - assertNull(snapshotInfo.licenses()); - assertEquals(SOURCE_DISK, snapshotInfo.sourceDisk()); - assertNull(snapshotInfo.sourceDiskId()); - assertNull(snapshotInfo.storageBytes()); - assertNull(snapshotInfo.storageBytesStatus()); + assertNull(snapshotInfo.getGeneratedId()); + assertEquals(SNAPSHOT_ID, snapshotInfo.getSnapshotId()); + assertNull(snapshotInfo.getCreationTimestamp()); + assertNull(snapshotInfo.getDescription()); + assertNull(snapshotInfo.getStatus()); + assertNull(snapshotInfo.getDiskSizeGb()); + assertNull(snapshotInfo.getLicenses()); + assertEquals(SOURCE_DISK, snapshotInfo.getSourceDisk()); + assertNull(snapshotInfo.getSourceDiskId()); + assertNull(snapshotInfo.getStorageBytes()); + assertNull(snapshotInfo.getStorageBytesStatus()); } @Test @@ -104,32 +132,32 @@ public void testToAndFromPb() { compareSnapshotInfo(SNAPSHOT_INFO, SnapshotInfo.fromPb(SNAPSHOT_INFO.toPb())); SnapshotInfo snapshotInfo = SnapshotInfo.of(SNAPSHOT_ID, SOURCE_DISK); compareSnapshotInfo(snapshotInfo, SnapshotInfo.fromPb(snapshotInfo.toPb())); - snapshotInfo = new SnapshotInfo.BuilderImpl().snapshotId(SNAPSHOT_ID).build(); + snapshotInfo = new SnapshotInfo.BuilderImpl().setSnapshotId(SNAPSHOT_ID).build(); compareSnapshotInfo(snapshotInfo, SnapshotInfo.fromPb(snapshotInfo.toPb())); } @Test public void testSetProjectId() { SnapshotInfo snapshotInfo = SNAPSHOT_INFO.toBuilder() - .snapshotId(SnapshotId.of("snapshot")) - .sourceDisk(DiskId.of("zone", "disk")) + .setSnapshotId(SnapshotId.of("snapshot")) + .setSourceDisk(DiskId.of("zone", "disk")) .build(); compareSnapshotInfo(SNAPSHOT_INFO, snapshotInfo.setProjectId("project")); } public void compareSnapshotInfo(SnapshotInfo expected, SnapshotInfo value) { assertEquals(expected, value); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.snapshotId(), value.snapshotId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.status(), value.status()); - assertEquals(expected.diskSizeGb(), value.diskSizeGb()); - assertEquals(expected.licenses(), value.licenses()); - assertEquals(expected.sourceDisk(), value.sourceDisk()); - assertEquals(expected.sourceDiskId(), value.sourceDiskId()); - assertEquals(expected.storageBytes(), value.storageBytes()); - assertEquals(expected.storageBytesStatus(), value.storageBytesStatus()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getSnapshotId(), value.getSnapshotId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getStatus(), value.getStatus()); + assertEquals(expected.getDiskSizeGb(), value.getDiskSizeGb()); + assertEquals(expected.getLicenses(), value.getLicenses()); + assertEquals(expected.getSourceDisk(), value.getSourceDisk()); + assertEquals(expected.getSourceDiskId(), value.getSourceDiskId()); + assertEquals(expected.getStorageBytes(), value.getStorageBytes()); + assertEquals(expected.getStorageBytesStatus(), value.getStorageBytesStatus()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotTest.java index d74cdf988f8c..22620bba8df1 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotTest.java @@ -59,30 +59,30 @@ private void initializeExpectedSnapshot(int optionsCalls) { expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); expectedSnapshot = new Snapshot.Builder(serviceMockReturnsOptions, SNAPSHOT_ID, SOURCE_DISK) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .diskSizeGb(DISK_SIZE_GB) - .licenses(LICENSES) - .sourceDiskId(SOURCE_DISK_ID) - .storageBytes(STORAGE_BYTES) - .storageBytesStatus(STORAGE_BYTES_STATUS) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setDiskSizeGb(DISK_SIZE_GB) + .setLicenses(LICENSES) + .setSourceDiskId(SOURCE_DISK_ID) + .setStorageBytes(STORAGE_BYTES) + .setStorageBytesStatus(STORAGE_BYTES_STATUS) .build(); compute = createStrictMock(Compute.class); } private void initializeSnapshot() { snapshot = new Snapshot.Builder(compute, SNAPSHOT_ID, SOURCE_DISK) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .diskSizeGb(DISK_SIZE_GB) - .licenses(LICENSES) - .sourceDiskId(SOURCE_DISK_ID) - .storageBytes(STORAGE_BYTES) - .storageBytesStatus(STORAGE_BYTES_STATUS) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setDiskSizeGb(DISK_SIZE_GB) + .setLicenses(LICENSES) + .setSourceDiskId(SOURCE_DISK_ID) + .setStorageBytes(STORAGE_BYTES) + .setStorageBytesStatus(STORAGE_BYTES_STATUS) .build(); } @@ -90,9 +90,9 @@ private void initializeSnapshot() { public void testToBuilder() { initializeExpectedSnapshot(8); compareSnapshot(expectedSnapshot, expectedSnapshot.toBuilder().build()); - Snapshot newSnapshot = expectedSnapshot.toBuilder().description("newDescription").build(); - assertEquals("newDescription", newSnapshot.description()); - newSnapshot = newSnapshot.toBuilder().description("description").build(); + Snapshot newSnapshot = expectedSnapshot.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", newSnapshot.getDescription()); + newSnapshot = newSnapshot.toBuilder().setDescription("description").build(); compareSnapshot(expectedSnapshot, newSnapshot); } @@ -140,6 +140,41 @@ public void testBuilder() { assertSame(serviceMockReturnsOptions, snapshot.compute()); } + @Test + public void testBuilderDeprecated() { + initializeExpectedSnapshot(2); + assertEquals(GENERATED_ID, expectedSnapshot.getGeneratedId()); + assertEquals(SNAPSHOT_ID, expectedSnapshot.getSnapshotId()); + assertEquals(CREATION_TIMESTAMP, expectedSnapshot.getCreationTimestamp()); + assertEquals(DESCRIPTION, expectedSnapshot.getDescription()); + assertEquals(STATUS, expectedSnapshot.getStatus()); + assertEquals(DISK_SIZE_GB, expectedSnapshot.getDiskSizeGb()); + assertEquals(LICENSES, expectedSnapshot.getLicenses()); + assertEquals(SOURCE_DISK, expectedSnapshot.getSourceDisk()); + assertEquals(SOURCE_DISK_ID, expectedSnapshot.getSourceDiskId()); + assertEquals(STORAGE_BYTES, expectedSnapshot.getStorageBytes()); + assertEquals(STORAGE_BYTES_STATUS, expectedSnapshot.getStorageBytesStatus()); + assertSame(serviceMockReturnsOptions, expectedSnapshot.getCompute()); + SnapshotId otherSnapshotId = SnapshotId.of("otherSnapshot"); + DiskId otherSourceDisk = DiskId.of("zone", "otherDisk"); + Snapshot snapshot = new Snapshot.Builder(serviceMockReturnsOptions, SNAPSHOT_ID, SOURCE_DISK) + .setSnapshotId(otherSnapshotId) + .setSourceDisk(otherSourceDisk) + .build(); + assertNull(snapshot.getGeneratedId()); + assertEquals(otherSnapshotId, snapshot.getSnapshotId()); + assertNull(snapshot.getCreationTimestamp()); + assertNull(snapshot.getDescription()); + assertNull(snapshot.getStatus()); + assertNull(snapshot.getDiskSizeGb()); + assertNull(snapshot.getLicenses()); + assertEquals(otherSourceDisk, snapshot.getSourceDisk()); + assertNull(snapshot.getSourceDiskId()); + assertNull(snapshot.getStorageBytes()); + assertNull(snapshot.getStorageBytesStatus()); + assertSame(serviceMockReturnsOptions, snapshot.getCompute()); + } + @Test public void testToAndFromPb() { initializeExpectedSnapshot(8); @@ -155,7 +190,7 @@ public void testDeleteOperation() { initializeExpectedSnapshot(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(GlobalOperationId.of("project", "op")) + .setOperationId(GlobalOperationId.of("project", "op")) .build(); expect(compute.deleteSnapshot(SNAPSHOT_ID)).andReturn(operation); replay(compute); @@ -178,7 +213,7 @@ public void testExists_True() throws Exception { initializeExpectedSnapshot(1); Compute.SnapshotOption[] expectedOptions = {Compute.SnapshotOption.fields()}; expect(compute.options()).andReturn(mockOptions); - expect(compute.getSnapshot(SNAPSHOT_ID.snapshot(), expectedOptions)) + expect(compute.getSnapshot(SNAPSHOT_ID.getSnapshot(), expectedOptions)) .andReturn(expectedSnapshot); replay(compute); initializeSnapshot(); @@ -191,7 +226,7 @@ public void testExists_False() throws Exception { initializeExpectedSnapshot(1); Compute.SnapshotOption[] expectedOptions = {Compute.SnapshotOption.fields()}; expect(compute.options()).andReturn(mockOptions); - expect(compute.getSnapshot(SNAPSHOT_ID.snapshot(), expectedOptions)).andReturn(null); + expect(compute.getSnapshot(SNAPSHOT_ID.getSnapshot(), expectedOptions)).andReturn(null); replay(compute); initializeSnapshot(); assertFalse(snapshot.exists()); @@ -202,7 +237,7 @@ public void testExists_False() throws Exception { public void testReload() throws Exception { initializeExpectedSnapshot(3); expect(compute.options()).andReturn(mockOptions); - expect(compute.getSnapshot(SNAPSHOT_ID.snapshot())).andReturn(expectedSnapshot); + expect(compute.getSnapshot(SNAPSHOT_ID.getSnapshot())).andReturn(expectedSnapshot); replay(compute); initializeSnapshot(); Snapshot updatedSnapshot = snapshot.reload(); @@ -214,7 +249,7 @@ public void testReload() throws Exception { public void testReloadNull() throws Exception { initializeExpectedSnapshot(1); expect(compute.options()).andReturn(mockOptions); - expect(compute.getSnapshot(SNAPSHOT_ID.snapshot())).andReturn(null); + expect(compute.getSnapshot(SNAPSHOT_ID.getSnapshot())).andReturn(null); replay(compute); initializeSnapshot(); assertNull(snapshot.reload()); @@ -225,7 +260,7 @@ public void testReloadNull() throws Exception { public void testReloadWithOptions() throws Exception { initializeExpectedSnapshot(3); expect(compute.options()).andReturn(mockOptions); - expect(compute.getSnapshot(SNAPSHOT_ID.snapshot(), Compute.SnapshotOption.fields())) + expect(compute.getSnapshot(SNAPSHOT_ID.getSnapshot(), Compute.SnapshotOption.fields())) .andReturn(expectedSnapshot); replay(compute); initializeSnapshot(); @@ -236,18 +271,18 @@ public void testReloadWithOptions() throws Exception { public void compareSnapshot(Snapshot expected, Snapshot value) { assertEquals(expected, value); - assertEquals(expected.compute().options(), value.compute().options()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.snapshotId(), value.snapshotId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.status(), value.status()); - assertEquals(expected.diskSizeGb(), value.diskSizeGb()); - assertEquals(expected.licenses(), value.licenses()); - assertEquals(expected.sourceDisk(), value.sourceDisk()); - assertEquals(expected.sourceDiskId(), value.sourceDiskId()); - assertEquals(expected.storageBytes(), value.storageBytes()); - assertEquals(expected.storageBytesStatus(), value.storageBytesStatus()); + assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getSnapshotId(), value.getSnapshotId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getStatus(), value.getStatus()); + assertEquals(expected.getDiskSizeGb(), value.getDiskSizeGb()); + assertEquals(expected.getLicenses(), value.getLicenses()); + assertEquals(expected.getSourceDisk(), value.getSourceDisk()); + assertEquals(expected.getSourceDiskId(), value.getSourceDiskId()); + assertEquals(expected.getStorageBytes(), value.getStorageBytes()); + assertEquals(expected.getStorageBytesStatus(), value.getStorageBytesStatus()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/StandardDiskConfigurationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/StandardDiskConfigurationTest.java index 3651eef2ad99..f0616e5d833d 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/StandardDiskConfigurationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/StandardDiskConfigurationTest.java @@ -29,6 +29,11 @@ public class StandardDiskConfigurationTest { private static final Long SIZE = 42L; private static final DiskTypeId DISK_TYPE = DiskTypeId.of("project", "zone", "type"); private static final StandardDiskConfiguration DISK_CONFIGURATION = + StandardDiskConfiguration.newBuilder() + .setSizeGb(SIZE) + .setDiskType(DISK_TYPE) + .build(); + private static final StandardDiskConfiguration DEPRECATED_DISK_CONFIGURATION = StandardDiskConfiguration.builder() .sizeGb(SIZE) .diskType(DISK_TYPE) @@ -38,11 +43,11 @@ public class StandardDiskConfigurationTest { public void testToBuilder() { compareStandardDiskConfiguration(DISK_CONFIGURATION, DISK_CONFIGURATION.toBuilder().build()); StandardDiskConfiguration diskConfiguration = DISK_CONFIGURATION.toBuilder() - .sizeGb(24L) + .setSizeGb(24L) .build(); - assertEquals(24L, diskConfiguration.sizeGb().longValue()); + assertEquals(24L, diskConfiguration.getSizeGb().longValue()); diskConfiguration = diskConfiguration.toBuilder() - .sizeGb(SIZE) + .setSizeGb(SIZE) .build(); compareStandardDiskConfiguration(DISK_CONFIGURATION, diskConfiguration); } @@ -55,9 +60,16 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(DISK_TYPE, DISK_CONFIGURATION.diskType()); - assertEquals(SIZE, DISK_CONFIGURATION.sizeGb()); - assertEquals(Type.STANDARD, DISK_CONFIGURATION.type()); + assertEquals(DISK_TYPE, DISK_CONFIGURATION.getDiskType()); + assertEquals(SIZE, DISK_CONFIGURATION.getSizeGb()); + assertEquals(Type.STANDARD, DISK_CONFIGURATION.getType()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(DISK_TYPE, DEPRECATED_DISK_CONFIGURATION.diskType()); + assertEquals(SIZE, DEPRECATED_DISK_CONFIGURATION.sizeGb()); + assertEquals(Type.STANDARD, DEPRECATED_DISK_CONFIGURATION.type()); } @Test @@ -71,23 +83,23 @@ public void testToAndFromPb() { @Test public void testOf() { StandardDiskConfiguration configuration = StandardDiskConfiguration.of(DISK_TYPE); - assertEquals(DISK_TYPE, configuration.diskType()); - assertNull(configuration.sizeGb()); - assertEquals(Type.STANDARD, configuration.type()); + assertEquals(DISK_TYPE, configuration.getDiskType()); + assertNull(configuration.getSizeGb()); + assertEquals(Type.STANDARD, configuration.getType()); configuration = StandardDiskConfiguration.of(DISK_TYPE, SIZE); - assertEquals(DISK_TYPE, configuration.diskType()); - assertEquals(SIZE, configuration.sizeGb()); - assertEquals(Type.STANDARD, configuration.type()); + assertEquals(DISK_TYPE, configuration.getDiskType()); + assertEquals(SIZE, configuration.getSizeGb()); + assertEquals(Type.STANDARD, configuration.getType()); configuration = StandardDiskConfiguration.of(SIZE); - assertNull(configuration.diskType()); - assertEquals(SIZE, configuration.sizeGb()); - assertEquals(Type.STANDARD, configuration.type()); + assertNull(configuration.getDiskType()); + assertEquals(SIZE, configuration.getSizeGb()); + assertEquals(Type.STANDARD, configuration.getType()); } @Test public void testSetProjectId() { StandardDiskConfiguration configuration = DISK_CONFIGURATION.toBuilder() - .diskType(DiskTypeId.of(DISK_TYPE.zone(), DISK_TYPE.type())) + .setDiskType(DiskTypeId.of(DISK_TYPE.getZone(), DISK_TYPE.getType())) .build(); compareStandardDiskConfiguration(DISK_CONFIGURATION, configuration.setProjectId("project")); } @@ -95,9 +107,9 @@ public void testSetProjectId() { private void compareStandardDiskConfiguration(StandardDiskConfiguration expected, StandardDiskConfiguration value) { assertEquals(expected, value); - assertEquals(expected.diskType(), value.diskType()); - assertEquals(expected.sizeGb(), value.sizeGb()); - assertEquals(expected.type(), value.type()); + assertEquals(expected.getDiskType(), value.getDiskType()); + assertEquals(expected.getSizeGb(), value.getSizeGb()); + assertEquals(expected.getType(), value.getType()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/StandardNetworkConfigurationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/StandardNetworkConfigurationTest.java index 4949327415f0..1fa7954444f2 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/StandardNetworkConfigurationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/StandardNetworkConfigurationTest.java @@ -33,6 +33,18 @@ public class StandardNetworkConfigurationTest { @Test public void testConstructor() { + assertEquals(Type.STANDARD, NETWORK_CONFIGURATION.getType()); + assertEquals(IP_RANGE, NETWORK_CONFIGURATION.getIpRange()); + assertEquals(GATEWAY_ADDRESS, NETWORK_CONFIGURATION.getGatewayAddress()); + StandardNetworkConfiguration networkConfiguration = + new StandardNetworkConfiguration(IP_RANGE, null); + assertEquals(Type.STANDARD, networkConfiguration.getType()); + assertEquals(IP_RANGE, networkConfiguration.getIpRange()); + assertNull(networkConfiguration.getGatewayAddress()); + } + + @Test + public void testConstructorDeprecated() { assertEquals(Type.STANDARD, NETWORK_CONFIGURATION.type()); assertEquals(IP_RANGE, NETWORK_CONFIGURATION.ipRange()); assertEquals(GATEWAY_ADDRESS, NETWORK_CONFIGURATION.gatewayAddress()); @@ -60,17 +72,17 @@ public void testToAndFromPb() { @Test public void testOf() { StandardNetworkConfiguration configuration = StandardNetworkConfiguration.of(IP_RANGE); - assertEquals(Type.STANDARD, configuration.type()); - assertEquals(IP_RANGE, configuration.ipRange()); - assertNull(configuration.gatewayAddress()); + assertEquals(Type.STANDARD, configuration.getType()); + assertEquals(IP_RANGE, configuration.getIpRange()); + assertNull(configuration.getGatewayAddress()); } private void compareNetworkConfiguration(StandardNetworkConfiguration expected, StandardNetworkConfiguration value) { assertEquals(expected, value); - assertEquals(expected.ipRange(), value.ipRange()); - assertEquals(expected.gatewayAddress(), value.gatewayAddress()); - assertEquals(expected.type(), value.type()); + assertEquals(expected.getIpRange(), value.getIpRange()); + assertEquals(expected.getGatewayAddress(), value.getGatewayAddress()); + assertEquals(expected.getType(), value.getType()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/StorageImageConfigurationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/StorageImageConfigurationTest.java index 3ecd80c66097..5d819ae58562 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/StorageImageConfigurationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/StorageImageConfigurationTest.java @@ -21,7 +21,6 @@ import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; -import org.junit.Assert; import org.junit.Test; public class StorageImageConfigurationTest { @@ -32,10 +31,17 @@ public class StorageImageConfigurationTest { private static final Long ARCHIVE_SIZE_BYTES = 42L; private static final String SHA1 = "sha1"; private static final StorageImageConfiguration CONFIGURATION = + StorageImageConfiguration.newBuilder(SOURCE) + .setSourceType(SOURCE_TYPE) + .setContainerType(CONTAINER_TYPE) + .setArchiveSizeBytes(ARCHIVE_SIZE_BYTES) + .setSha1(SHA1) + .build(); + private static final StorageImageConfiguration DEPRECATED_CONFIGURATION = StorageImageConfiguration.builder(SOURCE) - .sourceType(SOURCE_TYPE) + .setSourceType(SOURCE_TYPE) .containerType(CONTAINER_TYPE) - .archiveSizeBytes(ARCHIVE_SIZE_BYTES) + .setArchiveSizeBytes(ARCHIVE_SIZE_BYTES) .sha1(SHA1) .build(); @@ -43,9 +49,9 @@ public class StorageImageConfigurationTest { public void testToBuilder() { compareRawImageConfiguration(CONFIGURATION, CONFIGURATION.toBuilder().build()); String newSource = "newSource"; - StorageImageConfiguration configuration = CONFIGURATION.toBuilder().source(newSource).build(); - assertEquals(newSource, configuration.source()); - configuration = configuration.toBuilder().source(SOURCE).build(); + StorageImageConfiguration configuration = CONFIGURATION.toBuilder().setSource(newSource).build(); + assertEquals(newSource, configuration.getSource()); + configuration = configuration.toBuilder().setSource(SOURCE).build(); compareRawImageConfiguration(CONFIGURATION, configuration); } @@ -57,12 +63,22 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(SOURCE_TYPE, CONFIGURATION.sourceType()); - assertEquals(SOURCE, CONFIGURATION.source()); - assertEquals(CONTAINER_TYPE, CONFIGURATION.containerType()); - assertEquals(ARCHIVE_SIZE_BYTES, CONFIGURATION.archiveSizeBytes()); - assertEquals(SHA1, CONFIGURATION.sha1()); - Assert.assertEquals(ImageConfiguration.Type.STORAGE, CONFIGURATION.type()); + assertEquals(SOURCE_TYPE, CONFIGURATION.getSourceType()); + assertEquals(SOURCE, CONFIGURATION.getSource()); + assertEquals(CONTAINER_TYPE, CONFIGURATION.getContainerType()); + assertEquals(ARCHIVE_SIZE_BYTES, CONFIGURATION.getArchiveSizeBytes()); + assertEquals(SHA1, CONFIGURATION.getSha1()); + assertEquals(ImageConfiguration.Type.STORAGE, CONFIGURATION.getType()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(SOURCE_TYPE, DEPRECATED_CONFIGURATION.sourceType()); + assertEquals(SOURCE, DEPRECATED_CONFIGURATION.source()); + assertEquals(CONTAINER_TYPE, DEPRECATED_CONFIGURATION.containerType()); + assertEquals(ARCHIVE_SIZE_BYTES, DEPRECATED_CONFIGURATION.archiveSizeBytes()); + assertEquals(SHA1, DEPRECATED_CONFIGURATION.sha1()); + assertEquals(ImageConfiguration.Type.STORAGE, DEPRECATED_CONFIGURATION.type()); } @Test @@ -78,12 +94,12 @@ public void testToAndFromPb() { @Test public void testOf() { StorageImageConfiguration configuration = StorageImageConfiguration.of(SOURCE); - Assert.assertEquals(ImageConfiguration.Type.STORAGE, configuration.type()); - assertNull(configuration.sourceType()); - assertEquals(SOURCE, configuration.source()); - assertNull(configuration.containerType()); - assertNull(configuration.archiveSizeBytes()); - assertNull(configuration.sha1()); + assertEquals(ImageConfiguration.Type.STORAGE, configuration.getType()); + assertNull(configuration.getSourceType()); + assertEquals(SOURCE, configuration.getSource()); + assertNull(configuration.getContainerType()); + assertNull(configuration.getArchiveSizeBytes()); + assertNull(configuration.getSha1()); } @Test @@ -94,12 +110,12 @@ public void testSetProjectId() { private void compareRawImageConfiguration(StorageImageConfiguration expected, StorageImageConfiguration value) { assertEquals(expected, value); - assertEquals(expected.type(), value.type()); - assertEquals(expected.source(), value.source()); - assertEquals(expected.sourceType(), value.sourceType()); - assertEquals(expected.containerType(), value.containerType()); - assertEquals(expected.archiveSizeBytes(), value.archiveSizeBytes()); - assertEquals(expected.sha1(), value.sha1()); + assertEquals(expected.getType(), value.getType()); + assertEquals(expected.getSource(), value.getSource()); + assertEquals(expected.getSourceType(), value.getSourceType()); + assertEquals(expected.getContainerType(), value.getContainerType()); + assertEquals(expected.getArchiveSizeBytes(), value.getArchiveSizeBytes()); + assertEquals(expected.getSha1(), value.getSha1()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetNetworkConfigurationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetNetworkConfigurationTest.java index 5fbec3e99c93..6b88317c4273 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetNetworkConfigurationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetNetworkConfigurationTest.java @@ -22,7 +22,6 @@ import com.google.common.collect.ImmutableList; -import org.junit.Assert; import org.junit.Test; import java.util.List; @@ -39,12 +38,25 @@ public class SubnetNetworkConfigurationTest { @Test public void testConstructor() { assertEquals(AUTO_CREATE_SUBNETWORKS, NETWORK_CONFIGURATION.autoCreateSubnetworks()); - Assert.assertEquals(NetworkConfiguration.Type.SUBNET, NETWORK_CONFIGURATION.type()); + assertEquals(NetworkConfiguration.Type.SUBNET, NETWORK_CONFIGURATION.getType()); + assertEquals(SUBNETWORKS, NETWORK_CONFIGURATION.getSubnetworks()); + assertEquals(NetworkConfiguration.Type.SUBNET, NETWORK_CONFIGURATION.getType()); + SubnetNetworkConfiguration networkConfiguration = + new SubnetNetworkConfiguration(AUTO_CREATE_SUBNETWORKS, null); + assertEquals(NetworkConfiguration.Type.SUBNET, networkConfiguration.getType()); + assertEquals(AUTO_CREATE_SUBNETWORKS, networkConfiguration.autoCreateSubnetworks()); + assertNull(networkConfiguration.getSubnetworks()); + } + + @Test + public void testConstructorDeprecated() { + assertEquals(AUTO_CREATE_SUBNETWORKS, NETWORK_CONFIGURATION.autoCreateSubnetworks()); + assertEquals(NetworkConfiguration.Type.SUBNET, NETWORK_CONFIGURATION.type()); assertEquals(SUBNETWORKS, NETWORK_CONFIGURATION.subnetworks()); - Assert.assertEquals(NetworkConfiguration.Type.SUBNET, NETWORK_CONFIGURATION.type()); + assertEquals(NetworkConfiguration.Type.SUBNET, NETWORK_CONFIGURATION.type()); SubnetNetworkConfiguration networkConfiguration = new SubnetNetworkConfiguration(AUTO_CREATE_SUBNETWORKS, null); - Assert.assertEquals(NetworkConfiguration.Type.SUBNET, networkConfiguration.type()); + assertEquals(NetworkConfiguration.Type.SUBNET, networkConfiguration.type()); assertEquals(AUTO_CREATE_SUBNETWORKS, networkConfiguration.autoCreateSubnetworks()); assertNull(networkConfiguration.subnetworks()); } @@ -68,16 +80,16 @@ public void testOf() { SubnetNetworkConfiguration configuration = SubnetNetworkConfiguration.of(AUTO_CREATE_SUBNETWORKS); assertEquals(AUTO_CREATE_SUBNETWORKS, configuration.autoCreateSubnetworks()); - assertNull(configuration.subnetworks()); - Assert.assertEquals(NetworkConfiguration.Type.SUBNET, configuration.type()); + assertNull(configuration.getSubnetworks()); + assertEquals(NetworkConfiguration.Type.SUBNET, configuration.getType()); } private void compareNetworkConfiguration(SubnetNetworkConfiguration expected, SubnetNetworkConfiguration value) { assertEquals(expected, value); assertEquals(expected.autoCreateSubnetworks(), value.autoCreateSubnetworks()); - assertEquals(expected.subnetworks(), value.subnetworks()); - assertEquals(expected.type(), value.type()); + assertEquals(expected.getSubnetworks(), value.getSubnetworks()); + assertEquals(expected.getType(), value.getType()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkIdTest.java index 972c0d5f1d13..0670e6d69604 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkIdTest.java @@ -39,6 +39,23 @@ public class SubnetworkIdTest { @Test public void testOf() { + SubnetworkId subnetworkId = SubnetworkId.of(PROJECT, REGION, NAME); + assertEquals(PROJECT, subnetworkId.getProject()); + assertEquals(REGION, subnetworkId.getRegion()); + assertEquals(NAME, subnetworkId.getSubnetwork()); + assertEquals(URL, subnetworkId.getSelfLink()); + subnetworkId = SubnetworkId.of(REGION, NAME); + assertNull(subnetworkId.getProject()); + assertEquals(REGION, subnetworkId.getRegion()); + assertEquals(NAME, subnetworkId.getSubnetwork()); + subnetworkId = SubnetworkId.of(RegionId.of(PROJECT, REGION), NAME); + assertEquals(PROJECT, subnetworkId.getProject()); + assertEquals(REGION, subnetworkId.getRegion()); + assertEquals(NAME, subnetworkId.getSubnetwork()); + } + + @Test + public void testOfDeprecated() { SubnetworkId subnetworkId = SubnetworkId.of(PROJECT, REGION, NAME); assertEquals(PROJECT, subnetworkId.project()); assertEquals(REGION, subnetworkId.region()); @@ -57,7 +74,7 @@ public void testOf() { @Test public void testToAndFromUrl() { SubnetworkId subnetworkId = SubnetworkId.of(PROJECT, REGION, NAME); - compareSubnetworkId(subnetworkId, SubnetworkId.fromUrl(subnetworkId.selfLink())); + compareSubnetworkId(subnetworkId, SubnetworkId.fromUrl(subnetworkId.getSelfLink())); thrown.expect(IllegalArgumentException.class); thrown.expectMessage("notMatchingUrl is not a valid subnetwork URL"); SubnetworkId.fromUrl("notMatchingUrl"); @@ -72,16 +89,16 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(SubnetworkId.matchesUrl(SubnetworkId.of(PROJECT, REGION, NAME).selfLink())); + assertTrue(SubnetworkId.matchesUrl(SubnetworkId.of(PROJECT, REGION, NAME).getSelfLink())); assertFalse(SubnetworkId.matchesUrl("notMatchingUrl")); } private void compareSubnetworkId(SubnetworkId expected, SubnetworkId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.region(), expected.region()); - assertEquals(expected.subnetwork(), expected.subnetwork()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getRegion(), expected.getRegion()); + assertEquals(expected.getSubnetwork(), expected.getSubnetwork()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkInfoTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkInfoTest.java index 17907ea2ac3a..04c92e4aa546 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkInfoTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkInfoTest.java @@ -32,20 +32,27 @@ public class SubnetworkInfoTest { private static final NetworkId NETWORK_ID = NetworkId.of("project", "network"); private static final String IP_RANGE = "192.168.0.0/16"; private static final SubnetworkInfo SUBNETWORK_INFO = + SubnetworkInfo.newBuilder(SUBNETWORK_ID, NETWORK_ID, IP_RANGE) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setGatewayAddress(GATEWAY_ADDRESS) + .build(); + private static final SubnetworkInfo DEPRECATED_SUBNETWORK_INFO = SubnetworkInfo.builder(SUBNETWORK_ID, NETWORK_ID, IP_RANGE) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) .description(DESCRIPTION) - .gatewayAddress(GATEWAY_ADDRESS) + .setGatewayAddress(GATEWAY_ADDRESS) .build(); @Test public void testToBuilder() { compareSubnetworkInfo(SUBNETWORK_INFO, SUBNETWORK_INFO.toBuilder().build()); SubnetworkInfo subnetworkInfo = - SUBNETWORK_INFO.toBuilder().description("newDescription").build(); - assertEquals("newDescription", subnetworkInfo.description()); - subnetworkInfo = subnetworkInfo.toBuilder().description("description").build(); + SUBNETWORK_INFO.toBuilder().setDescription("newDescription").build(); + assertEquals("newDescription", subnetworkInfo.getDescription()); + subnetworkInfo = subnetworkInfo.toBuilder().setDescription("description").build(); compareSubnetworkInfo(SUBNETWORK_INFO, subnetworkInfo); } @@ -57,25 +64,36 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { - assertEquals(GENERATED_ID, SUBNETWORK_INFO.generatedId()); - assertEquals(SUBNETWORK_ID, SUBNETWORK_INFO.subnetworkId()); - assertEquals(CREATION_TIMESTAMP, SUBNETWORK_INFO.creationTimestamp()); - assertEquals(DESCRIPTION, SUBNETWORK_INFO.description()); - assertEquals(GATEWAY_ADDRESS, SUBNETWORK_INFO.gatewayAddress()); - assertEquals(NETWORK_ID, SUBNETWORK_INFO.network()); - assertEquals(IP_RANGE, SUBNETWORK_INFO.ipRange()); + assertEquals(GENERATED_ID, SUBNETWORK_INFO.getGeneratedId()); + assertEquals(SUBNETWORK_ID, SUBNETWORK_INFO.getSubnetworkId()); + assertEquals(CREATION_TIMESTAMP, SUBNETWORK_INFO.getCreationTimestamp()); + assertEquals(DESCRIPTION, SUBNETWORK_INFO.getDescription()); + assertEquals(GATEWAY_ADDRESS, SUBNETWORK_INFO.getGatewayAddress()); + assertEquals(NETWORK_ID, SUBNETWORK_INFO.getNetwork()); + assertEquals(IP_RANGE, SUBNETWORK_INFO.getIpRange()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(GENERATED_ID, DEPRECATED_SUBNETWORK_INFO.generatedId()); + assertEquals(SUBNETWORK_ID, DEPRECATED_SUBNETWORK_INFO.subnetworkId()); + assertEquals(CREATION_TIMESTAMP, DEPRECATED_SUBNETWORK_INFO.creationTimestamp()); + assertEquals(DESCRIPTION, DEPRECATED_SUBNETWORK_INFO.description()); + assertEquals(GATEWAY_ADDRESS, DEPRECATED_SUBNETWORK_INFO.gatewayAddress()); + assertEquals(NETWORK_ID, DEPRECATED_SUBNETWORK_INFO.network()); + assertEquals(IP_RANGE, DEPRECATED_SUBNETWORK_INFO.ipRange()); } @Test public void testOf() { SubnetworkInfo subnetworkInfo = SubnetworkInfo.of(SUBNETWORK_ID, NETWORK_ID, IP_RANGE); - assertNull(subnetworkInfo.generatedId()); - assertEquals(SUBNETWORK_ID, subnetworkInfo.subnetworkId()); - assertNull(subnetworkInfo.creationTimestamp()); - assertNull(subnetworkInfo.description()); - assertNull(subnetworkInfo.gatewayAddress()); - assertEquals(NETWORK_ID, subnetworkInfo.network()); - assertEquals(IP_RANGE, subnetworkInfo.ipRange()); + assertNull(subnetworkInfo.getGeneratedId()); + assertEquals(SUBNETWORK_ID, subnetworkInfo.getSubnetworkId()); + assertNull(subnetworkInfo.getCreationTimestamp()); + assertNull(subnetworkInfo.getDescription()); + assertNull(subnetworkInfo.getGatewayAddress()); + assertEquals(NETWORK_ID, subnetworkInfo.getNetwork()); + assertEquals(IP_RANGE, subnetworkInfo.getIpRange()); } @Test @@ -88,21 +106,21 @@ public void testToAndFromPb() { @Test public void testSetProjectId() { SubnetworkInfo subnetworkInfo = SUBNETWORK_INFO.toBuilder() - .subnetworkId(SubnetworkId.of("region", "subnetwork")) - .network(NetworkId.of("network")) + .setSubnetworkId(SubnetworkId.of("region", "subnetwork")) + .setNetwork(NetworkId.of("network")) .build(); compareSubnetworkInfo(SUBNETWORK_INFO, subnetworkInfo.setProjectId("project")); } public void compareSubnetworkInfo(SubnetworkInfo expected, SubnetworkInfo value) { assertEquals(expected, value); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.subnetworkId(), value.subnetworkId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.gatewayAddress(), value.gatewayAddress()); - assertEquals(expected.network(), value.network()); - assertEquals(expected.ipRange(), value.ipRange()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getSubnetworkId(), value.getSubnetworkId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getGatewayAddress(), value.getGatewayAddress()); + assertEquals(expected.getNetwork(), value.getNetwork()); + assertEquals(expected.getIpRange(), value.getIpRange()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkTest.java index 6a710738b935..cb52b74522eb 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkTest.java @@ -50,10 +50,10 @@ private void initializeExpectedSubnetwork(int optionsCalls) { replay(serviceMockReturnsOptions); expectedSubnetwork = new Subnetwork.Builder(serviceMockReturnsOptions, SUBNETWORK_ID, NETWORK_ID, IP_RANGE) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) .description(DESCRIPTION) - .gatewayAddress(GATEWAY_ADDRESS) + .setGatewayAddress(GATEWAY_ADDRESS) .build(); compute = createStrictMock(Compute.class); } @@ -61,10 +61,10 @@ private void initializeExpectedSubnetwork(int optionsCalls) { private void initializeSubnetwork() { subnetwork = new Subnetwork.Builder(compute, SUBNETWORK_ID, NETWORK_ID, IP_RANGE) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) .description(DESCRIPTION) - .gatewayAddress(GATEWAY_ADDRESS) + .setGatewayAddress(GATEWAY_ADDRESS) .build(); } @@ -73,7 +73,7 @@ public void testToBuilder() { initializeExpectedSubnetwork(8); compareSubnetwork(expectedSubnetwork, expectedSubnetwork.toBuilder().build()); Subnetwork newSubnetwork = expectedSubnetwork.toBuilder().description("newDescription").build(); - assertEquals("newDescription", newSubnetwork.description()); + assertEquals("newDescription", newSubnetwork.getDescription()); newSubnetwork = newSubnetwork.toBuilder().description("description").build(); compareSubnetwork(expectedSubnetwork, newSubnetwork); } @@ -89,6 +89,19 @@ public void testToBuilderIncomplete() { @Test public void testBuilder() { + initializeExpectedSubnetwork(1); + assertEquals(GENERATED_ID, expectedSubnetwork.getGeneratedId()); + assertEquals(SUBNETWORK_ID, expectedSubnetwork.getSubnetworkId()); + assertEquals(CREATION_TIMESTAMP, expectedSubnetwork.getCreationTimestamp()); + assertEquals(DESCRIPTION, expectedSubnetwork.getDescription()); + assertEquals(GATEWAY_ADDRESS, expectedSubnetwork.getGatewayAddress()); + assertEquals(NETWORK_ID, expectedSubnetwork.getNetwork()); + assertEquals(IP_RANGE, expectedSubnetwork.getIpRange()); + assertSame(serviceMockReturnsOptions, expectedSubnetwork.getCompute()); + } + + @Test + public void testBuilderDeprecated() { initializeExpectedSubnetwork(1); assertEquals(GENERATED_ID, expectedSubnetwork.generatedId()); assertEquals(SUBNETWORK_ID, expectedSubnetwork.subnetworkId()); @@ -116,7 +129,7 @@ public void testDeleteOperation() { initializeExpectedSubnetwork(2); expect(compute.options()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) - .operationId(GlobalOperationId.of("project", "op")) + .setOperationId(GlobalOperationId.of("project", "op")) .build(); expect(compute.deleteSubnetwork(SUBNETWORK_ID)).andReturn(operation); replay(compute); @@ -197,14 +210,14 @@ public void testReloadWithOptions() throws Exception { public void compareSubnetwork(Subnetwork expected, Subnetwork value) { assertEquals(expected, value); - assertEquals(expected.compute().options(), value.compute().options()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.subnetworkId(), value.subnetworkId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.gatewayAddress(), value.gatewayAddress()); - assertEquals(expected.network(), value.network()); - assertEquals(expected.ipRange(), value.ipRange()); + assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getSubnetworkId(), value.getSubnetworkId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getGatewayAddress(), value.getGatewayAddress()); + assertEquals(expected.getNetwork(), value.getNetwork()); + assertEquals(expected.getIpRange(), value.getIpRange()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/TagsTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/TagsTest.java index f626a418fefd..d06433371fd8 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/TagsTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/TagsTest.java @@ -29,13 +29,26 @@ public class TagsTest { @Test public void testToBuilder() { - Tags tags = TAGS.toBuilder().values("tag1").build(); - assertEquals(ImmutableList.of("tag1"), tags.values()); - compareTags(TAGS, tags.toBuilder().values("tag1", "tag2").build()); + Tags tags = TAGS.toBuilder().setValues("tag1").build(); + assertEquals(ImmutableList.of("tag1"), tags.getValues()); + compareTags(TAGS, tags.toBuilder().setValues("tag1", "tag2").build()); } @Test public void testBuilder() { + Tags tags = Tags.newBuilder().setValues(ImmutableList.of("tag1", "tag2")).build(); + assertEquals(ImmutableList.of("tag1", "tag2"), tags.getValues()); + assertNull(tags.getFingerprint()); + tags = Tags.newBuilder().add("tag1").add("tag2").build(); + assertEquals(ImmutableList.of("tag1", "tag2"), tags.getValues()); + assertNull(tags.getFingerprint()); + tags = Tags.newBuilder().add("tag1").add("tag2").setFingerprint("fingerprint").build(); + assertEquals(ImmutableList.of("tag1", "tag2"), tags.getValues()); + assertEquals("fingerprint", tags.getFingerprint()); + } + + @Test + public void testBuilderDeprecated() { Tags tags = Tags.builder().values(ImmutableList.of("tag1", "tag2")).build(); assertEquals(ImmutableList.of("tag1", "tag2"), tags.values()); assertNull(tags.fingerprint()); @@ -56,14 +69,14 @@ public void testOf() { @Test public void testToAndFromPb() { compareTags(TAGS, Tags.fromPb(TAGS.toPb())); - Tags tags = Tags.builder().add("tag1").add("tag2").fingerprint("fingerprint").build(); + Tags tags = Tags.newBuilder().add("tag1").add("tag2").setFingerprint("fingerprint").build(); compareTags(tags, Tags.fromPb(tags.toPb())); } public void compareTags(Tags expected, Tags value) { assertEquals(expected, value); - assertEquals(expected.fingerprint(), value.fingerprint()); - assertEquals(expected.values(), value.values()); + assertEquals(expected.getFingerprint(), value.getFingerprint()); + assertEquals(expected.getValues(), value.getValues()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/ZoneIdTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/ZoneIdTest.java index 90bdc6de2bf3..7629a567cb83 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/ZoneIdTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/ZoneIdTest.java @@ -38,6 +38,17 @@ public class ZoneIdTest { @Test public void testOf() { + ZoneId zoneId = ZoneId.of(PROJECT, ZONE); + assertEquals(PROJECT, zoneId.getProject()); + assertEquals(ZONE, zoneId.getZone()); + assertEquals(URL, zoneId.getSelfLink()); + zoneId = ZoneId.of(ZONE); + assertNull(zoneId.getProject()); + assertEquals(ZONE, zoneId.getZone()); + } + + @Test + public void testOfDeprecated() { ZoneId zoneId = ZoneId.of(PROJECT, ZONE); assertEquals(PROJECT, zoneId.project()); assertEquals(ZONE, zoneId.zone()); @@ -50,7 +61,7 @@ public void testOf() { @Test public void testToAndFromUrl() { ZoneId zoneId = ZoneId.of(PROJECT, ZONE); - compareZoneId(zoneId, ZoneId.fromUrl(zoneId.selfLink())); + compareZoneId(zoneId, ZoneId.fromUrl(zoneId.getSelfLink())); } @Test @@ -65,15 +76,15 @@ public void testSetProjectId() { @Test public void testMatchesUrl() { - assertTrue(ZoneId.matchesUrl(ZoneId.of(PROJECT, ZONE).selfLink())); + assertTrue(ZoneId.matchesUrl(ZoneId.of(PROJECT, ZONE).getSelfLink())); assertFalse(ZoneId.matchesUrl("notMatchingUrl")); } private void compareZoneId(ZoneId expected, ZoneId value) { assertEquals(expected, value); - assertEquals(expected.project(), expected.project()); - assertEquals(expected.zone(), expected.zone()); - assertEquals(expected.selfLink(), expected.selfLink()); + assertEquals(expected.getProject(), expected.getProject()); + assertEquals(expected.getZone(), expected.getZone()); + assertEquals(expected.getSelfLink(), expected.getSelfLink()); assertEquals(expected.hashCode(), expected.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/ZoneTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/ZoneTest.java index b03aabc5b34e..64f05049c74b 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/ZoneTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/ZoneTest.java @@ -31,17 +31,28 @@ public class ZoneTest { private static final DeprecationStatus DEPRECATION_STATUS = DeprecationStatus.of(DeprecationStatus.Status.DELETED, ZONE_ID); private static final Zone ZONE = Zone.builder() - .zoneId(ZONE_ID) - .generatedId(GENERATED_ID) - .creationTimestamp(CREATION_TIMESTAMP) - .description(DESCRIPTION) - .status(STATUS) - .deprecationStatus(DEPRECATION_STATUS) - .region(REGION_ID) + .setZoneId(ZONE_ID) + .setGeneratedId(GENERATED_ID) + .setCreationTimestamp(CREATION_TIMESTAMP) + .setDescription(DESCRIPTION) + .setStatus(STATUS) + .setDeprecationStatus(DEPRECATION_STATUS) + .setRegion(REGION_ID) .build(); @Test public void testBuilder() { + assertEquals(REGION_ID, ZONE.getRegion()); + assertEquals(GENERATED_ID, ZONE.getGeneratedId()); + assertEquals(CREATION_TIMESTAMP, ZONE.getCreationTimestamp()); + assertEquals(DESCRIPTION, ZONE.getDescription()); + assertEquals(STATUS, ZONE.getStatus()); + assertEquals(REGION_ID, ZONE.getRegion()); + assertEquals(DEPRECATION_STATUS, ZONE.getDeprecationStatus()); + } + + @Test + public void testBuilderDeprecated() { assertEquals(REGION_ID, ZONE.region()); assertEquals(GENERATED_ID, ZONE.generatedId()); assertEquals(CREATION_TIMESTAMP, ZONE.creationTimestamp()); @@ -54,24 +65,24 @@ public void testBuilder() { @Test public void testToAndFromPb() { com.google.api.services.compute.model.Zone zonePb = ZONE.toPb(); - assertEquals(REGION_ID.selfLink(), zonePb.getRegion()); + assertEquals(REGION_ID.getSelfLink(), zonePb.getRegion()); Zone zone = Zone.fromPb(zonePb); compareZones(ZONE, zone); - assertEquals(ZONE_ID.project(), zone.zoneId().project()); - assertEquals(ZONE_ID.zone(), zone.zoneId().zone()); - zone = Zone.builder().zoneId(ZONE_ID).build(); + assertEquals(ZONE_ID.getProject(), zone.getZoneId().getProject()); + assertEquals(ZONE_ID.getZone(), zone.getZoneId().getZone()); + zone = Zone.builder().setZoneId(ZONE_ID).build(); compareZones(zone, Zone.fromPb(zone.toPb())); } private void compareZones(Zone expected, Zone value) { assertEquals(expected, value); - assertEquals(expected.zoneId(), value.zoneId()); - assertEquals(expected.generatedId(), value.generatedId()); - assertEquals(expected.creationTimestamp(), value.creationTimestamp()); - assertEquals(expected.description(), value.description()); - assertEquals(expected.status(), value.status()); - assertEquals(expected.region(), value.region()); - assertEquals(expected.deprecationStatus(), value.deprecationStatus()); + assertEquals(expected.getZoneId(), value.getZoneId()); + assertEquals(expected.getGeneratedId(), value.getGeneratedId()); + assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); + assertEquals(expected.getDescription(), value.getDescription()); + assertEquals(expected.getStatus(), value.getStatus()); + assertEquals(expected.getRegion(), value.getRegion()); + assertEquals(expected.getDeprecationStatus(), value.getDeprecationStatus()); assertEquals(expected.hashCode(), value.hashCode()); } } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/it/ITComputeTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/it/ITComputeTest.java index 5ee58c6bfda4..9f7d234cdccb 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/it/ITComputeTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/it/ITComputeTest.java @@ -78,7 +78,6 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; -import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; @@ -109,32 +108,32 @@ public class ITComputeTest { @BeforeClass public static void beforeClass() { RemoteComputeHelper computeHelper = RemoteComputeHelper.create(); - compute = computeHelper.options().service(); + compute = computeHelper.getOptions().service(); } @Test public void testGetDiskType() { DiskType diskType = compute.getDiskType(ZONE, DISK_TYPE); - // assertNotNull(diskType.generatedId()); - assertEquals(ZONE, diskType.diskTypeId().zone()); - assertEquals(DISK_TYPE, diskType.diskTypeId().type()); - assertNotNull(diskType.creationTimestamp()); - assertNotNull(diskType.description()); - assertNotNull(diskType.validDiskSize()); - assertNotNull(diskType.defaultDiskSizeGb()); + // assertNotNull(diskType.getGeneratedId()); + assertEquals(ZONE, diskType.getDiskTypeId().getZone()); + assertEquals(DISK_TYPE, diskType.getDiskTypeId().getType()); + assertNotNull(diskType.getCreationTimestamp()); + assertNotNull(diskType.getDescription()); + assertNotNull(diskType.getValidDiskSize()); + assertNotNull(diskType.getDefaultDiskSizeGb()); } @Test public void testGetDiskTypeWithSelectedFields() { DiskType diskType = compute.getDiskType(ZONE, DISK_TYPE, Compute.DiskTypeOption.fields(Compute.DiskTypeField.CREATION_TIMESTAMP)); - // assertNotNull(diskType.generatedId()); - assertEquals(ZONE, diskType.diskTypeId().zone()); - assertEquals(DISK_TYPE, diskType.diskTypeId().type()); - assertNotNull(diskType.creationTimestamp()); - assertNull(diskType.description()); - assertNull(diskType.validDiskSize()); - assertNull(diskType.defaultDiskSizeGb()); + // assertNotNull(diskType.getGeneratedId()); + assertEquals(ZONE, diskType.getDiskTypeId().getZone()); + assertEquals(DISK_TYPE, diskType.getDiskTypeId().getType()); + assertNotNull(diskType.getCreationTimestamp()); + assertNull(diskType.getDescription()); + assertNull(diskType.getValidDiskSize()); + assertNull(diskType.getDefaultDiskSizeGb()); } @Test @@ -144,13 +143,13 @@ public void testListDiskTypes() { assertTrue(diskTypeIterator.hasNext()); while (diskTypeIterator.hasNext()) { DiskType diskType = diskTypeIterator.next(); - // assertNotNull(diskType.generatedId()); - assertNotNull(diskType.diskTypeId()); - assertEquals(ZONE, diskType.diskTypeId().zone()); - assertNotNull(diskType.creationTimestamp()); - assertNotNull(diskType.description()); - assertNotNull(diskType.validDiskSize()); - assertNotNull(diskType.defaultDiskSizeGb()); + // assertNotNull(diskType.getGeneratedId()); + assertNotNull(diskType.getDiskTypeId()); + assertEquals(ZONE, diskType.getDiskTypeId().getZone()); + assertNotNull(diskType.getCreationTimestamp()); + assertNotNull(diskType.getDescription()); + assertNotNull(diskType.getValidDiskSize()); + assertNotNull(diskType.getDefaultDiskSizeGb()); } } @@ -162,13 +161,13 @@ public void testListDiskTypesWithSelectedFields() { assertTrue(diskTypeIterator.hasNext()); while (diskTypeIterator.hasNext()) { DiskType diskType = diskTypeIterator.next(); - assertNull(diskType.generatedId()); - assertNotNull(diskType.diskTypeId()); - assertEquals(ZONE, diskType.diskTypeId().zone()); - assertNotNull(diskType.creationTimestamp()); - assertNull(diskType.description()); - assertNull(diskType.validDiskSize()); - assertNull(diskType.defaultDiskSizeGb()); + assertNull(diskType.getGeneratedId()); + assertNotNull(diskType.getDiskTypeId()); + assertEquals(ZONE, diskType.getDiskTypeId().getZone()); + assertNotNull(diskType.getCreationTimestamp()); + assertNull(diskType.getDescription()); + assertNull(diskType.getValidDiskSize()); + assertNull(diskType.getDefaultDiskSizeGb()); } } @@ -181,13 +180,13 @@ public void testListDiskTypesWithFilter() { while (diskTypeIterator.hasNext()) { DiskType diskType = diskTypeIterator.next(); // todo(mziccard): uncomment or remove once #695 is closed - // assertNotNull(diskType.generatedId()); - assertNotNull(diskType.diskTypeId()); - assertEquals(ZONE, diskType.diskTypeId().zone()); - assertNotNull(diskType.creationTimestamp()); - assertNotNull(diskType.description()); - assertNotNull(diskType.validDiskSize()); - assertEquals(375, (long) diskType.defaultDiskSizeGb()); + // assertNotNull(diskType.getGeneratedId()); + assertNotNull(diskType.getDiskTypeId()); + assertEquals(ZONE, diskType.getDiskTypeId().getZone()); + assertNotNull(diskType.getCreationTimestamp()); + assertNotNull(diskType.getDescription()); + assertNotNull(diskType.getValidDiskSize()); + assertEquals(375, (long) diskType.getDefaultDiskSizeGb()); } } @@ -198,12 +197,12 @@ public void testAggregatedListDiskTypes() { assertTrue(diskTypeIterator.hasNext()); while (diskTypeIterator.hasNext()) { DiskType diskType = diskTypeIterator.next(); - // assertNotNull(diskType.generatedId()); - assertNotNull(diskType.diskTypeId()); - assertNotNull(diskType.creationTimestamp()); - assertNotNull(diskType.description()); - assertNotNull(diskType.validDiskSize()); - assertNotNull(diskType.defaultDiskSizeGb()); + // assertNotNull(diskType.getGeneratedId()); + assertNotNull(diskType.getDiskTypeId()); + assertNotNull(diskType.getCreationTimestamp()); + assertNotNull(diskType.getDescription()); + assertNotNull(diskType.getValidDiskSize()); + assertNotNull(diskType.getDefaultDiskSizeGb()); } } @@ -216,42 +215,42 @@ public void testAggregatedListDiskTypesWithFilter() { while (diskTypeIterator.hasNext()) { DiskType diskType = diskTypeIterator.next(); // todo(mziccard): uncomment or remove once #695 is closed - // assertNotNull(diskType.generatedId()); - assertNotNull(diskType.diskTypeId()); - assertNotNull(diskType.creationTimestamp()); - assertNotNull(diskType.description()); - assertNotNull(diskType.validDiskSize()); - assertNotEquals(375, (long) diskType.defaultDiskSizeGb()); + // assertNotNull(diskType.getGeneratedId()); + assertNotNull(diskType.getDiskTypeId()); + assertNotNull(diskType.getCreationTimestamp()); + assertNotNull(diskType.getDescription()); + assertNotNull(diskType.getValidDiskSize()); + assertNotEquals(375, (long) diskType.getDefaultDiskSizeGb()); } } @Test public void testGetMachineType() { MachineType machineType = compute.getMachineType(ZONE, MACHINE_TYPE); - assertEquals(ZONE, machineType.machineTypeId().zone()); - assertEquals(MACHINE_TYPE, machineType.machineTypeId().type()); - assertNotNull(machineType.generatedId()); - assertNotNull(machineType.creationTimestamp()); - assertNotNull(machineType.description()); - assertNotNull(machineType.cpus()); - assertNotNull(machineType.memoryMb()); - assertNotNull(machineType.maximumPersistentDisks()); - assertNotNull(machineType.maximumPersistentDisksSizeGb()); + assertEquals(ZONE, machineType.getMachineTypeId().getZone()); + assertEquals(MACHINE_TYPE, machineType.getMachineTypeId().getType()); + assertNotNull(machineType.getGeneratedId()); + assertNotNull(machineType.getCreationTimestamp()); + assertNotNull(machineType.getDescription()); + assertNotNull(machineType.getCpus()); + assertNotNull(machineType.getMemoryMb()); + assertNotNull(machineType.getMaximumPersistentDisks()); + assertNotNull(machineType.getMaximumPersistentDisksSizeGb()); } @Test public void testGetMachineTypeWithSelectedFields() { MachineType machineType = compute.getMachineType(ZONE, MACHINE_TYPE, Compute.MachineTypeOption.fields(Compute.MachineTypeField.ID)); - assertEquals(ZONE, machineType.machineTypeId().zone()); - assertEquals(MACHINE_TYPE, machineType.machineTypeId().type()); - assertNotNull(machineType.generatedId()); - assertNull(machineType.creationTimestamp()); - assertNull(machineType.description()); - assertNull(machineType.cpus()); - assertNull(machineType.memoryMb()); - assertNull(machineType.maximumPersistentDisks()); - assertNull(machineType.maximumPersistentDisksSizeGb()); + assertEquals(ZONE, machineType.getMachineTypeId().getZone()); + assertEquals(MACHINE_TYPE, machineType.getMachineTypeId().getType()); + assertNotNull(machineType.getGeneratedId()); + assertNull(machineType.getCreationTimestamp()); + assertNull(machineType.getDescription()); + assertNull(machineType.getCpus()); + assertNull(machineType.getMemoryMb()); + assertNull(machineType.getMaximumPersistentDisks()); + assertNull(machineType.getMaximumPersistentDisksSizeGb()); } @Test @@ -261,15 +260,15 @@ public void testListMachineTypes() { assertTrue(machineTypeIterator.hasNext()); while (machineTypeIterator.hasNext()) { MachineType machineType = machineTypeIterator.next(); - assertNotNull(machineType.machineTypeId()); - assertEquals(ZONE, machineType.machineTypeId().zone()); - assertNotNull(machineType.generatedId()); - assertNotNull(machineType.creationTimestamp()); - assertNotNull(machineType.description()); - assertNotNull(machineType.cpus()); - assertNotNull(machineType.memoryMb()); - assertNotNull(machineType.maximumPersistentDisks()); - assertNotNull(machineType.maximumPersistentDisksSizeGb()); + assertNotNull(machineType.getMachineTypeId()); + assertEquals(ZONE, machineType.getMachineTypeId().getZone()); + assertNotNull(machineType.getGeneratedId()); + assertNotNull(machineType.getCreationTimestamp()); + assertNotNull(machineType.getDescription()); + assertNotNull(machineType.getCpus()); + assertNotNull(machineType.getMemoryMb()); + assertNotNull(machineType.getMaximumPersistentDisks()); + assertNotNull(machineType.getMaximumPersistentDisksSizeGb()); } } @@ -281,15 +280,15 @@ public void testListMachineTypesWithSelectedFields() { assertTrue(machineTypeIterator.hasNext()); while (machineTypeIterator.hasNext()) { MachineType machineType = machineTypeIterator.next(); - assertNotNull(machineType.machineTypeId()); - assertEquals(ZONE, machineType.machineTypeId().zone()); - assertNull(machineType.generatedId()); - assertNotNull(machineType.creationTimestamp()); - assertNull(machineType.description()); - assertNull(machineType.cpus()); - assertNull(machineType.memoryMb()); - assertNull(machineType.maximumPersistentDisks()); - assertNull(machineType.maximumPersistentDisksSizeGb()); + assertNotNull(machineType.getMachineTypeId()); + assertEquals(ZONE, machineType.getMachineTypeId().getZone()); + assertNull(machineType.getGeneratedId()); + assertNotNull(machineType.getCreationTimestamp()); + assertNull(machineType.getDescription()); + assertNull(machineType.getCpus()); + assertNull(machineType.getMemoryMb()); + assertNull(machineType.getMaximumPersistentDisks()); + assertNull(machineType.getMaximumPersistentDisksSizeGb()); } } @@ -302,16 +301,16 @@ public void testListMachineTypesWithFilter() { assertTrue(machineTypeIterator.hasNext()); while (machineTypeIterator.hasNext()) { MachineType machineType = machineTypeIterator.next(); - assertNotNull(machineType.machineTypeId()); - assertEquals(ZONE, machineType.machineTypeId().zone()); - assertNotNull(machineType.generatedId()); - assertNotNull(machineType.creationTimestamp()); - assertNotNull(machineType.description()); - assertNotNull(machineType.cpus()); - assertEquals(2, (long) machineType.cpus()); - assertNotNull(machineType.memoryMb()); - assertNotNull(machineType.maximumPersistentDisks()); - assertNotNull(machineType.maximumPersistentDisksSizeGb()); + assertNotNull(machineType.getMachineTypeId()); + assertEquals(ZONE, machineType.getMachineTypeId().getZone()); + assertNotNull(machineType.getGeneratedId()); + assertNotNull(machineType.getCreationTimestamp()); + assertNotNull(machineType.getDescription()); + assertNotNull(machineType.getCpus()); + assertEquals(2, (long) machineType.getCpus()); + assertNotNull(machineType.getMemoryMb()); + assertNotNull(machineType.getMaximumPersistentDisks()); + assertNotNull(machineType.getMaximumPersistentDisksSizeGb()); } } @@ -322,14 +321,14 @@ public void testAggregatedListMachineTypes() { assertTrue(machineTypeIterator.hasNext()); while (machineTypeIterator.hasNext()) { MachineType machineType = machineTypeIterator.next(); - assertNotNull(machineType.machineTypeId()); - assertNotNull(machineType.generatedId()); - assertNotNull(machineType.creationTimestamp()); - assertNotNull(machineType.description()); - assertNotNull(machineType.cpus()); - assertNotNull(machineType.memoryMb()); - assertNotNull(machineType.maximumPersistentDisks()); - assertNotNull(machineType.maximumPersistentDisksSizeGb()); + assertNotNull(machineType.getMachineTypeId()); + assertNotNull(machineType.getGeneratedId()); + assertNotNull(machineType.getCreationTimestamp()); + assertNotNull(machineType.getDescription()); + assertNotNull(machineType.getCpus()); + assertNotNull(machineType.getMemoryMb()); + assertNotNull(machineType.getMaximumPersistentDisks()); + assertNotNull(machineType.getMaximumPersistentDisksSizeGb()); } } @@ -342,54 +341,54 @@ public void testAggregatedListMachineTypesWithFilter() { assertTrue(machineTypeIterator.hasNext()); while (machineTypeIterator.hasNext()) { MachineType machineType = machineTypeIterator.next(); - assertNotNull(machineType.machineTypeId()); - assertNotNull(machineType.generatedId()); - assertNotNull(machineType.creationTimestamp()); - assertNotNull(machineType.description()); - assertNotNull(machineType.cpus()); - assertNotEquals(2, (long) machineType.cpus()); - assertNotNull(machineType.memoryMb()); - assertNotNull(machineType.maximumPersistentDisks()); - assertNotNull(machineType.maximumPersistentDisksSizeGb()); + assertNotNull(machineType.getMachineTypeId()); + assertNotNull(machineType.getGeneratedId()); + assertNotNull(machineType.getCreationTimestamp()); + assertNotNull(machineType.getDescription()); + assertNotNull(machineType.getCpus()); + assertNotEquals(2, (long) machineType.getCpus()); + assertNotNull(machineType.getMemoryMb()); + assertNotNull(machineType.getMaximumPersistentDisks()); + assertNotNull(machineType.getMaximumPersistentDisksSizeGb()); } } @Test public void testGetLicense() { License license = compute.getLicense(LICENSE_ID); - assertEquals(LICENSE_ID, license.licenseId()); + assertEquals(LICENSE_ID, license.getLicenseId()); assertNotNull(license.chargesUseFee()); } @Test public void testGetLicenseWithSelectedFields() { License license = compute.getLicense(LICENSE_ID, Compute.LicenseOption.fields()); - assertEquals(LICENSE_ID, license.licenseId()); + assertEquals(LICENSE_ID, license.getLicenseId()); assertNull(license.chargesUseFee()); } @Test public void testGetRegion() { Region region = compute.getRegion(REGION); - assertEquals(REGION, region.regionId().region()); - assertNotNull(region.description()); - assertNotNull(region.creationTimestamp()); - assertNotNull(region.generatedId()); - assertNotNull(region.quotas()); - assertNotNull(region.status()); - assertNotNull(region.zones()); + assertEquals(REGION, region.getRegionId().getRegion()); + assertNotNull(region.getDescription()); + assertNotNull(region.getCreationTimestamp()); + assertNotNull(region.getGeneratedId()); + assertNotNull(region.getQuotas()); + assertNotNull(region.getStatus()); + assertNotNull(region.getZones()); } @Test public void testGetRegionWithSelectedFields() { Region region = compute.getRegion(REGION, Compute.RegionOption.fields(Compute.RegionField.ID)); - assertEquals(REGION, region.regionId().region()); - assertNotNull(region.generatedId()); - assertNull(region.description()); - assertNull(region.creationTimestamp()); - assertNull(region.quotas()); - assertNull(region.status()); - assertNull(region.zones()); + assertEquals(REGION, region.getRegionId().getRegion()); + assertNotNull(region.getGeneratedId()); + assertNull(region.getDescription()); + assertNull(region.getCreationTimestamp()); + assertNull(region.getQuotas()); + assertNull(region.getStatus()); + assertNull(region.getZones()); } @Test @@ -398,13 +397,13 @@ public void testListRegions() { Iterator regionIterator = regionPage.iterateAll(); while (regionIterator.hasNext()) { Region region = regionIterator.next(); - assertNotNull(region.regionId()); - assertNotNull(region.description()); - assertNotNull(region.creationTimestamp()); - assertNotNull(region.generatedId()); - assertNotNull(region.quotas()); - assertNotNull(region.status()); - assertNotNull(region.zones()); + assertNotNull(region.getRegionId()); + assertNotNull(region.getDescription()); + assertNotNull(region.getCreationTimestamp()); + assertNotNull(region.getGeneratedId()); + assertNotNull(region.getQuotas()); + assertNotNull(region.getStatus()); + assertNotNull(region.getZones()); } } @@ -415,13 +414,13 @@ public void testListRegionsWithSelectedFields() { Iterator regionIterator = regionPage.iterateAll(); while (regionIterator.hasNext()) { Region region = regionIterator.next(); - assertNotNull(region.regionId()); - assertNull(region.description()); - assertNull(region.creationTimestamp()); - assertNotNull(region.generatedId()); - assertNull(region.quotas()); - assertNull(region.status()); - assertNull(region.zones()); + assertNotNull(region.getRegionId()); + assertNull(region.getDescription()); + assertNull(region.getCreationTimestamp()); + assertNotNull(region.getGeneratedId()); + assertNull(region.getQuotas()); + assertNull(region.getStatus()); + assertNull(region.getZones()); } } @@ -430,30 +429,30 @@ public void testListRegionsWithFilter() { Page regionPage = compute.listRegions(Compute.RegionListOption.filter( Compute.RegionFilter.equals(Compute.RegionField.NAME, REGION))); Iterator regionIterator = regionPage.iterateAll(); - assertEquals(REGION, regionIterator.next().regionId().region()); + assertEquals(REGION, regionIterator.next().getRegionId().getRegion()); assertFalse(regionIterator.hasNext()); } @Test public void testGetZone() { Zone zone = compute.getZone(ZONE); - assertEquals(ZONE, zone.zoneId().zone()); - assertNotNull(zone.generatedId()); - assertNotNull(zone.creationTimestamp()); - assertNotNull(zone.description()); - assertNotNull(zone.status()); - assertNotNull(zone.region()); + assertEquals(ZONE, zone.getZoneId().getZone()); + assertNotNull(zone.getGeneratedId()); + assertNotNull(zone.getCreationTimestamp()); + assertNotNull(zone.getDescription()); + assertNotNull(zone.getStatus()); + assertNotNull(zone.getRegion()); } @Test public void testGetZoneWithSelectedFields() { Zone zone = compute.getZone(ZONE, Compute.ZoneOption.fields(Compute.ZoneField.ID)); - assertEquals(ZONE, zone.zoneId().zone()); - assertNotNull(zone.generatedId()); - assertNull(zone.creationTimestamp()); - assertNull(zone.description()); - assertNull(zone.status()); - assertNull(zone.region()); + assertEquals(ZONE, zone.getZoneId().getZone()); + assertNotNull(zone.getGeneratedId()); + assertNull(zone.getCreationTimestamp()); + assertNull(zone.getDescription()); + assertNull(zone.getStatus()); + assertNull(zone.getRegion()); } @Test @@ -462,12 +461,12 @@ public void testListZones() { Iterator zoneIterator = zonePage.iterateAll(); while (zoneIterator.hasNext()) { Zone zone = zoneIterator.next(); - assertNotNull(zone.zoneId()); - assertNotNull(zone.generatedId()); - assertNotNull(zone.creationTimestamp()); - assertNotNull(zone.description()); - assertNotNull(zone.status()); - assertNotNull(zone.region()); + assertNotNull(zone.getZoneId()); + assertNotNull(zone.getGeneratedId()); + assertNotNull(zone.getCreationTimestamp()); + assertNotNull(zone.getDescription()); + assertNotNull(zone.getStatus()); + assertNotNull(zone.getRegion()); } } @@ -478,12 +477,12 @@ public void testListZonesWithSelectedFields() { Iterator zoneIterator = zonePage.iterateAll(); while (zoneIterator.hasNext()) { Zone zone = zoneIterator.next(); - assertNotNull(zone.zoneId()); - assertNull(zone.generatedId()); - assertNotNull(zone.creationTimestamp()); - assertNull(zone.description()); - assertNull(zone.status()); - assertNull(zone.region()); + assertNotNull(zone.getZoneId()); + assertNull(zone.getGeneratedId()); + assertNotNull(zone.getCreationTimestamp()); + assertNull(zone.getDescription()); + assertNull(zone.getStatus()); + assertNull(zone.getRegion()); } } @@ -492,7 +491,7 @@ public void testListZonesWithFilter() { Page zonePage = compute.listZones( Compute.ZoneListOption.filter(Compute.ZoneFilter.equals(Compute.ZoneField.NAME, ZONE))); Iterator zoneIterator = zonePage.iterateAll(); - assertEquals(ZONE, zoneIterator.next().zoneId().zone()); + assertEquals(ZONE, zoneIterator.next().getZoneId().getZone()); assertFalse(zoneIterator.hasNext()); } @@ -502,13 +501,13 @@ public void testListGlobalOperations() { Iterator operationIterator = operationPage.iterateAll(); while (operationIterator.hasNext()) { Operation operation = operationIterator.next(); - assertNotNull(operation.generatedId()); - assertNotNull(operation.operationId()); + assertNotNull(operation.getGeneratedId()); + assertNotNull(operation.getOperationId()); // todo(mziccard): uncomment or remove once #727 is closed - // assertNotNull(operation.creationTimestamp()); - assertNotNull(operation.operationType()); - assertNotNull(operation.status()); - assertNotNull(operation.user()); + // assertNotNull(operation.getCreationTimestamp()); + assertNotNull(operation.getOperationType()); + assertNotNull(operation.getStatus()); + assertNotNull(operation.getUser()); } } @@ -519,22 +518,22 @@ public void testListGlobalOperationsWithSelectedFields() { Iterator operationIterator = operationPage.iterateAll(); while (operationIterator.hasNext()) { Operation operation = operationIterator.next(); - assertNotNull(operation.generatedId()); - assertNotNull(operation.operationId()); - assertNull(operation.operationType()); - assertNull(operation.targetLink()); - assertNull(operation.targetId()); - assertNull(operation.operationType()); - assertNull(operation.status()); - assertNull(operation.statusMessage()); - assertNull(operation.user()); - assertNull(operation.progress()); - assertNull(operation.description()); - assertNull(operation.insertTime()); - assertNull(operation.startTime()); - assertNull(operation.endTime()); - assertNull(operation.warnings()); - assertNull(operation.httpErrorMessage()); + assertNotNull(operation.getGeneratedId()); + assertNotNull(operation.getOperationId()); + assertNull(operation.getOperationType()); + assertNull(operation.getTargetLink()); + assertNull(operation.getTargetId()); + assertNull(operation.getOperationType()); + assertNull(operation.getStatus()); + assertNull(operation.getStatusMessage()); + assertNull(operation.getUser()); + assertNull(operation.getProgress()); + assertNull(operation.getDescription()); + assertNull(operation.getInsertTime()); + assertNull(operation.getStartTime()); + assertNull(operation.getEndTime()); + assertNull(operation.getWarnings()); + assertNull(operation.getHttpErrorMessage()); } } @@ -545,13 +544,13 @@ public void testListGlobalOperationsWithFilter() { Iterator operationIterator = operationPage.iterateAll(); while (operationIterator.hasNext()) { Operation operation = operationIterator.next(); - assertNotNull(operation.generatedId()); - assertNotNull(operation.operationId()); + assertNotNull(operation.getGeneratedId()); + assertNotNull(operation.getOperationId()); // todo(mziccard): uncomment or remove once #727 is closed - // assertNotNull(operation.creationTimestamp()); - assertNotNull(operation.operationType()); - assertEquals(Operation.Status.DONE, operation.status()); - assertNotNull(operation.user()); + // assertNotNull(operation.getCreationTimestamp()); + assertNotNull(operation.getOperationType()); + assertEquals(Operation.Status.DONE, operation.getStatus()); + assertNotNull(operation.getUser()); } } @@ -561,14 +560,14 @@ public void testListRegionOperations() { Iterator operationIterator = operationPage.iterateAll(); while (operationIterator.hasNext()) { Operation operation = operationIterator.next(); - assertNotNull(operation.generatedId()); - assertNotNull(operation.operationId()); - assertEquals(REGION, operation.operationId().region()); + assertNotNull(operation.getGeneratedId()); + assertNotNull(operation.getOperationId()); + assertEquals(REGION, operation.getOperationId().getRegion()); // todo(mziccard): uncomment or remove once #727 is closed - // assertNotNull(operation.creationTimestamp()); - assertNotNull(operation.operationType()); - assertNotNull(operation.status()); - assertNotNull(operation.user()); + // assertNotNull(operation.getCreationTimestamp()); + assertNotNull(operation.getOperationType()); + assertNotNull(operation.getStatus()); + assertNotNull(operation.getUser()); } } @@ -579,23 +578,23 @@ public void testListRegionOperationsWithSelectedFields() { Iterator operationIterator = operationPage.iterateAll(); while (operationIterator.hasNext()) { Operation operation = operationIterator.next(); - assertNotNull(operation.generatedId()); - assertNotNull(operation.operationId()); - assertEquals(REGION, operation.operationId().region()); - assertNull(operation.operationType()); - assertNull(operation.targetLink()); - assertNull(operation.targetId()); - assertNull(operation.operationType()); - assertNull(operation.status()); - assertNull(operation.statusMessage()); - assertNull(operation.user()); - assertNull(operation.progress()); - assertNull(operation.description()); - assertNull(operation.insertTime()); - assertNull(operation.startTime()); - assertNull(operation.endTime()); - assertNull(operation.warnings()); - assertNull(operation.httpErrorMessage()); + assertNotNull(operation.getGeneratedId()); + assertNotNull(operation.getOperationId()); + assertEquals(REGION, operation.getOperationId().getRegion()); + assertNull(operation.getOperationType()); + assertNull(operation.getTargetLink()); + assertNull(operation.getTargetId()); + assertNull(operation.getOperationType()); + assertNull(operation.getStatus()); + assertNull(operation.getStatusMessage()); + assertNull(operation.getUser()); + assertNull(operation.getProgress()); + assertNull(operation.getDescription()); + assertNull(operation.getInsertTime()); + assertNull(operation.getStartTime()); + assertNull(operation.getEndTime()); + assertNull(operation.getWarnings()); + assertNull(operation.getHttpErrorMessage()); } } @@ -607,14 +606,14 @@ public void testListRegionOperationsWithFilter() { Iterator operationIterator = operationPage.iterateAll(); while (operationIterator.hasNext()) { Operation operation = operationIterator.next(); - assertNotNull(operation.generatedId()); - assertNotNull(operation.operationId()); - assertEquals(REGION, operation.operationId().region()); + assertNotNull(operation.getGeneratedId()); + assertNotNull(operation.getOperationId()); + assertEquals(REGION, operation.getOperationId().getRegion()); // todo(mziccard): uncomment or remove once #727 is closed - // assertNotNull(operation.creationTimestamp()); - assertNotNull(operation.operationType()); - assertEquals(Operation.Status.DONE, operation.status()); - assertNotNull(operation.user()); + // assertNotNull(operation.getCreationTimestamp()); + assertNotNull(operation.getOperationType()); + assertEquals(Operation.Status.DONE, operation.getStatus()); + assertNotNull(operation.getUser()); } } @@ -624,14 +623,14 @@ public void testListZoneOperations() { Iterator operationIterator = operationPage.iterateAll(); while (operationIterator.hasNext()) { Operation operation = operationIterator.next(); - assertNotNull(operation.generatedId()); - assertNotNull(operation.operationId()); - Assert.assertEquals(ZONE, operation.operationId().zone()); + assertNotNull(operation.getGeneratedId()); + assertNotNull(operation.getOperationId()); + assertEquals(ZONE, operation.getOperationId().getZone()); // todo(mziccard): uncomment or remove once #727 is closed - // assertNotNull(operation.creationTimestamp()); - assertNotNull(operation.operationType()); - assertNotNull(operation.status()); - assertNotNull(operation.user()); + // assertNotNull(operation.getCreationTimestamp()); + assertNotNull(operation.getOperationType()); + assertNotNull(operation.getStatus()); + assertNotNull(operation.getUser()); } } @@ -642,23 +641,23 @@ public void testListZoneOperationsWithSelectedFields() { Iterator operationIterator = operationPage.iterateAll(); while (operationIterator.hasNext()) { Operation operation = operationIterator.next(); - assertNotNull(operation.generatedId()); - assertNotNull(operation.operationId()); - assertEquals(ZONE, operation.operationId().zone()); - assertNull(operation.operationType()); - assertNull(operation.targetLink()); - assertNull(operation.targetId()); - assertNull(operation.operationType()); - assertNull(operation.status()); - assertNull(operation.statusMessage()); - assertNull(operation.user()); - assertNull(operation.progress()); - assertNull(operation.description()); - assertNull(operation.insertTime()); - assertNull(operation.startTime()); - assertNull(operation.endTime()); - assertNull(operation.warnings()); - assertNull(operation.httpErrorMessage()); + assertNotNull(operation.getGeneratedId()); + assertNotNull(operation.getOperationId()); + assertEquals(ZONE, operation.getOperationId().getZone()); + assertNull(operation.getOperationType()); + assertNull(operation.getTargetLink()); + assertNull(operation.getTargetId()); + assertNull(operation.getOperationType()); + assertNull(operation.getStatus()); + assertNull(operation.getStatusMessage()); + assertNull(operation.getUser()); + assertNull(operation.getProgress()); + assertNull(operation.getDescription()); + assertNull(operation.getInsertTime()); + assertNull(operation.getStartTime()); + assertNull(operation.getEndTime()); + assertNull(operation.getWarnings()); + assertNull(operation.getHttpErrorMessage()); } } @@ -670,14 +669,14 @@ public void testListZoneOperationsWithFilter() { Iterator operationIterator = operationPage.iterateAll(); while (operationIterator.hasNext()) { Operation operation = operationIterator.next(); - assertNotNull(operation.generatedId()); - assertNotNull(operation.operationId()); - assertEquals(ZONE, operation.operationId().zone()); + assertNotNull(operation.getGeneratedId()); + assertNotNull(operation.getOperationId()); + assertEquals(ZONE, operation.getOperationId().getZone()); // todo(mziccard): uncomment or remove once #727 is closed - // assertNotNull(operation.creationTimestamp()); - assertNotNull(operation.operationType()); - assertEquals(Operation.Status.DONE, operation.status()); - assertNotNull(operation.user()); + // assertNotNull(operation.getCreationTimestamp()); + assertNotNull(operation.getOperationType()); + assertEquals(Operation.Status.DONE, operation.getStatus()); + assertNotNull(operation.getUser()); } } @@ -691,22 +690,22 @@ public void testCreateGetAndDeleteRegionAddress() throws InterruptedException, T // test get Address remoteAddress = compute.getAddress(addressId); assertNotNull(remoteAddress); - assertTrue(remoteAddress.addressId() instanceof RegionAddressId); - assertEquals(REGION, remoteAddress.addressId().region()); - assertEquals(addressId.address(), remoteAddress.addressId().address()); - assertNotNull(remoteAddress.address()); - assertNotNull(remoteAddress.creationTimestamp()); - assertNotNull(remoteAddress.generatedId()); - assertNotNull(remoteAddress.status()); + assertTrue(remoteAddress.getAddressId() instanceof RegionAddressId); + assertEquals(REGION, remoteAddress.getAddressId().getRegion()); + assertEquals(addressId.getAddress(), remoteAddress.getAddressId().getAddress()); + assertNotNull(remoteAddress.getAddress()); + assertNotNull(remoteAddress.getCreationTimestamp()); + assertNotNull(remoteAddress.getGeneratedId()); + assertNotNull(remoteAddress.getStatus()); // test get with selected fields remoteAddress = compute.getAddress(addressId, Compute.AddressOption.fields()); assertNotNull(remoteAddress); - assertTrue(remoteAddress.addressId() instanceof RegionAddressId); - assertEquals(REGION, remoteAddress.addressId().region()); - assertEquals(addressId.address(), remoteAddress.addressId().address()); - assertNull(remoteAddress.address()); - assertNull(remoteAddress.creationTimestamp()); - assertNull(remoteAddress.generatedId()); + assertTrue(remoteAddress.getAddressId() instanceof RegionAddressId); + assertEquals(REGION, remoteAddress.getAddressId().getRegion()); + assertEquals(addressId.getAddress(), remoteAddress.getAddressId().getAddress()); + assertNull(remoteAddress.getAddress()); + assertNull(remoteAddress.getCreationTimestamp()); + assertNull(remoteAddress.getGeneratedId()); operation = remoteAddress.delete(); operation.waitFor(); assertNull(compute.getAddress(addressId)); @@ -732,13 +731,13 @@ public void testListRegionAddresses() throws InterruptedException, TimeoutExcept int count = 0; while (addressIterator.hasNext()) { Address address = addressIterator.next(); - assertNotNull(address.addressId()); - assertTrue(address.addressId() instanceof RegionAddressId); - assertEquals(REGION, address.addressId().region()); - assertTrue(addressSet.contains(address.addressId().address())); - assertNotNull(address.address()); - assertNotNull(address.creationTimestamp()); - assertNotNull(address.generatedId()); + assertNotNull(address.getAddressId()); + assertTrue(address.getAddressId() instanceof RegionAddressId); + assertEquals(REGION, address.getAddressId().getRegion()); + assertTrue(addressSet.contains(address.getAddressId().getAddress())); + assertNotNull(address.getAddress()); + assertNotNull(address.getCreationTimestamp()); + assertNotNull(address.getGeneratedId()); count++; } assertEquals(2, count); @@ -749,14 +748,14 @@ public void testListRegionAddresses() throws InterruptedException, TimeoutExcept addressIterator = addressPage.iterateAll(); while (addressIterator.hasNext()) { Address address = addressIterator.next(); - assertTrue(address.addressId() instanceof RegionAddressId); - assertEquals(REGION, address.addressId().region()); - assertTrue(addressSet.contains(address.addressId().address())); - assertNotNull(address.address()); - assertNull(address.creationTimestamp()); - assertNull(address.generatedId()); - assertNull(address.status()); - assertNull(address.usage()); + assertTrue(address.getAddressId() instanceof RegionAddressId); + assertEquals(REGION, address.getAddressId().getRegion()); + assertTrue(addressSet.contains(address.getAddressId().getAddress())); + assertNotNull(address.getAddress()); + assertNull(address.getCreationTimestamp()); + assertNull(address.getGeneratedId()); + assertNull(address.getStatus()); + assertNull(address.getUsage()); count++; } assertEquals(2, count); @@ -783,11 +782,11 @@ public void testAggregatedListAddresses() throws InterruptedException, TimeoutEx int count = 0; while (addressIterator.hasNext()) { Address address = addressIterator.next(); - assertNotNull(address.addressId()); - assertTrue(addressSet.contains(address.addressId().address())); - assertNotNull(address.address()); - assertNotNull(address.creationTimestamp()); - assertNotNull(address.generatedId()); + assertNotNull(address.getAddressId()); + assertTrue(addressSet.contains(address.getAddressId().getAddress())); + assertNotNull(address.getAddress()); + assertNotNull(address.getCreationTimestamp()); + assertNotNull(address.getGeneratedId()); count++; } assertEquals(2, count); @@ -805,20 +804,20 @@ public void testCreateGetAndDeleteGlobalAddress() throws InterruptedException, T // test get Address remoteAddress = compute.getAddress(addressId); assertNotNull(remoteAddress); - assertTrue(remoteAddress.addressId() instanceof GlobalAddressId); - assertEquals(addressId.address(), remoteAddress.addressId().address()); - assertNotNull(remoteAddress.address()); - assertNotNull(remoteAddress.creationTimestamp()); - assertNotNull(remoteAddress.generatedId()); - assertNotNull(remoteAddress.status()); + assertTrue(remoteAddress.getAddressId() instanceof GlobalAddressId); + assertEquals(addressId.getAddress(), remoteAddress.getAddressId().getAddress()); + assertNotNull(remoteAddress.getAddress()); + assertNotNull(remoteAddress.getCreationTimestamp()); + assertNotNull(remoteAddress.getGeneratedId()); + assertNotNull(remoteAddress.getStatus()); // test get with selected fields remoteAddress = compute.getAddress(addressId, Compute.AddressOption.fields()); assertNotNull(remoteAddress); - assertTrue(remoteAddress.addressId() instanceof GlobalAddressId); - assertEquals(addressId.address(), remoteAddress.addressId().address()); - assertNull(remoteAddress.address()); - assertNull(remoteAddress.creationTimestamp()); - assertNull(remoteAddress.generatedId()); + assertTrue(remoteAddress.getAddressId() instanceof GlobalAddressId); + assertEquals(addressId.getAddress(), remoteAddress.getAddressId().getAddress()); + assertNull(remoteAddress.getAddress()); + assertNull(remoteAddress.getCreationTimestamp()); + assertNull(remoteAddress.getGeneratedId()); operation = remoteAddress.delete(); operation.waitFor(); assertNull(compute.getAddress(addressId)); @@ -844,12 +843,12 @@ public void testListGlobalAddresses() throws InterruptedException, TimeoutExcept int count = 0; while (addressIterator.hasNext()) { Address address = addressIterator.next(); - assertNotNull(address.addressId()); - assertTrue(address.addressId() instanceof GlobalAddressId); - assertTrue(addressSet.contains(address.addressId().address())); - assertNotNull(address.address()); - assertNotNull(address.creationTimestamp()); - assertNotNull(address.generatedId()); + assertNotNull(address.getAddressId()); + assertTrue(address.getAddressId() instanceof GlobalAddressId); + assertTrue(addressSet.contains(address.getAddressId().getAddress())); + assertNotNull(address.getAddress()); + assertNotNull(address.getCreationTimestamp()); + assertNotNull(address.getGeneratedId()); count++; } assertEquals(2, count); @@ -860,13 +859,13 @@ public void testListGlobalAddresses() throws InterruptedException, TimeoutExcept addressIterator = addressPage.iterateAll(); while (addressIterator.hasNext()) { Address address = addressIterator.next(); - assertTrue(address.addressId() instanceof GlobalAddressId); - assertTrue(addressSet.contains(address.addressId().address())); - assertNotNull(address.address()); - assertNull(address.creationTimestamp()); - assertNull(address.generatedId()); - assertNull(address.status()); - assertNull(address.usage()); + assertTrue(address.getAddressId() instanceof GlobalAddressId); + assertTrue(addressSet.contains(address.getAddressId().getAddress())); + assertNotNull(address.getAddress()); + assertNull(address.getCreationTimestamp()); + assertNull(address.getGeneratedId()); + assertNull(address.getStatus()); + assertNull(address.getUsage()); count++; } assertEquals(2, count); @@ -875,7 +874,8 @@ public void testListGlobalAddresses() throws InterruptedException, TimeoutExcept } @Test - public void testCreateGetResizeAndDeleteStandardDisk() throws InterruptedException, TimeoutException { + public void testCreateGetResizeAndDeleteStandardDisk() + throws InterruptedException, TimeoutException { String name = BASE_RESOURCE_NAME + "create-and-get-standard-disk"; DiskId diskId = DiskId.of(ZONE, name); DiskInfo diskInfo = @@ -885,33 +885,33 @@ public void testCreateGetResizeAndDeleteStandardDisk() throws InterruptedExcepti // test get Disk remoteDisk = compute.getDisk(diskId); assertNotNull(remoteDisk); - assertEquals(ZONE, remoteDisk.diskId().zone()); - assertEquals(diskId.disk(), remoteDisk.diskId().disk()); - assertNotNull(remoteDisk.creationTimestamp()); - assertNotNull(remoteDisk.generatedId()); - assertTrue(remoteDisk.configuration() instanceof StandardDiskConfiguration); - StandardDiskConfiguration remoteConfiguration = remoteDisk.configuration(); - assertEquals(100L, (long) remoteConfiguration.sizeGb()); - assertEquals("pd-ssd", remoteConfiguration.diskType().type()); - assertEquals(DiskConfiguration.Type.STANDARD, remoteConfiguration.type()); - assertNull(remoteDisk.lastAttachTimestamp()); - assertNull(remoteDisk.lastDetachTimestamp()); + assertEquals(ZONE, remoteDisk.getDiskId().getZone()); + assertEquals(diskId.getDisk(), remoteDisk.getDiskId().getDisk()); + assertNotNull(remoteDisk.getCreationTimestamp()); + assertNotNull(remoteDisk.getGeneratedId()); + assertTrue(remoteDisk.getConfiguration() instanceof StandardDiskConfiguration); + StandardDiskConfiguration remoteConfiguration = remoteDisk.getConfiguration(); + assertEquals(100L, (long) remoteConfiguration.getSizeGb()); + assertEquals("pd-ssd", remoteConfiguration.getDiskType().getType()); + assertEquals(DiskConfiguration.Type.STANDARD, remoteConfiguration.getType()); + assertNull(remoteDisk.getLastAttachTimestamp()); + assertNull(remoteDisk.getLastDetachTimestamp()); operation = remoteDisk.resize(200L); operation.waitFor(); // test resize and get with selected fields remoteDisk = compute.getDisk(diskId, Compute.DiskOption.fields(Compute.DiskField.SIZE_GB)); assertNotNull(remoteDisk); - assertEquals(ZONE, remoteDisk.diskId().zone()); - assertEquals(diskId.disk(), remoteDisk.diskId().disk()); - assertNull(remoteDisk.creationTimestamp()); - assertNull(remoteDisk.generatedId()); - assertTrue(remoteDisk.configuration() instanceof StandardDiskConfiguration); - remoteConfiguration = remoteDisk.configuration(); - assertEquals(200L, (long) remoteConfiguration.sizeGb()); - assertEquals("pd-ssd", remoteConfiguration.diskType().type()); - assertEquals(DiskConfiguration.Type.STANDARD, remoteConfiguration.type()); - assertNull(remoteDisk.lastAttachTimestamp()); - assertNull(remoteDisk.lastDetachTimestamp()); + assertEquals(ZONE, remoteDisk.getDiskId().getZone()); + assertEquals(diskId.getDisk(), remoteDisk.getDiskId().getDisk()); + assertNull(remoteDisk.getCreationTimestamp()); + assertNull(remoteDisk.getGeneratedId()); + assertTrue(remoteDisk.getConfiguration() instanceof StandardDiskConfiguration); + remoteConfiguration = remoteDisk.getConfiguration(); + assertEquals(200L, (long) remoteConfiguration.getSizeGb()); + assertEquals("pd-ssd", remoteConfiguration.getDiskType().getType()); + assertEquals(DiskConfiguration.Type.STANDARD, remoteConfiguration.getType()); + assertNull(remoteDisk.getLastAttachTimestamp()); + assertNull(remoteDisk.getLastDetachTimestamp()); operation = remoteDisk.delete(); operation.waitFor(); assertNull(compute.getDisk(diskId)); @@ -927,43 +927,44 @@ public void testCreateGetAndDeleteImageDisk() throws InterruptedException, Timeo // test get Disk remoteDisk = compute.getDisk(diskId); assertNotNull(remoteDisk); - assertEquals(ZONE, remoteDisk.diskId().zone()); - assertEquals(diskId.disk(), remoteDisk.diskId().disk()); - assertEquals(DiskInfo.CreationStatus.READY, remoteDisk.creationStatus()); - assertNotNull(remoteDisk.creationTimestamp()); - assertNotNull(remoteDisk.generatedId()); - assertTrue(remoteDisk.configuration() instanceof ImageDiskConfiguration); - ImageDiskConfiguration remoteConfiguration = remoteDisk.configuration(); - assertEquals(IMAGE_ID, remoteConfiguration.sourceImage()); - assertNotNull(remoteConfiguration.sourceImageId()); - assertEquals(DiskConfiguration.Type.IMAGE, remoteConfiguration.type()); - assertNotNull(remoteConfiguration.sizeGb()); - assertEquals("pd-standard", remoteConfiguration.diskType().type()); - assertNull(remoteDisk.lastAttachTimestamp()); - assertNull(remoteDisk.lastDetachTimestamp()); + assertEquals(ZONE, remoteDisk.getDiskId().getZone()); + assertEquals(diskId.getDisk(), remoteDisk.getDiskId().getDisk()); + assertEquals(DiskInfo.CreationStatus.READY, remoteDisk.getCreationStatus()); + assertNotNull(remoteDisk.getCreationTimestamp()); + assertNotNull(remoteDisk.getGeneratedId()); + assertTrue(remoteDisk.getConfiguration() instanceof ImageDiskConfiguration); + ImageDiskConfiguration remoteConfiguration = remoteDisk.getConfiguration(); + assertEquals(IMAGE_ID, remoteConfiguration.getSourceImage()); + assertNotNull(remoteConfiguration.getSourceImageId()); + assertEquals(DiskConfiguration.Type.IMAGE, remoteConfiguration.getType()); + assertNotNull(remoteConfiguration.getSizeGb()); + assertEquals("pd-standard", remoteConfiguration.getDiskType().getType()); + assertNull(remoteDisk.getLastAttachTimestamp()); + assertNull(remoteDisk.getLastDetachTimestamp()); // test get with selected fields remoteDisk = compute.getDisk(diskId, Compute.DiskOption.fields()); assertNotNull(remoteDisk); - assertEquals(ZONE, remoteDisk.diskId().zone()); - assertEquals(diskId.disk(), remoteDisk.diskId().disk()); - assertNull(remoteDisk.creationTimestamp()); - assertNull(remoteDisk.generatedId()); - assertTrue(remoteDisk.configuration() instanceof ImageDiskConfiguration); - remoteConfiguration = remoteDisk.configuration(); - assertEquals(IMAGE_ID, remoteConfiguration.sourceImage()); - assertNull(remoteConfiguration.sourceImageId()); - assertEquals(DiskConfiguration.Type.IMAGE, remoteConfiguration.type()); - assertNull(remoteConfiguration.sizeGb()); - assertEquals("pd-standard", remoteConfiguration.diskType().type()); - assertNull(remoteDisk.lastAttachTimestamp()); - assertNull(remoteDisk.lastDetachTimestamp()); + assertEquals(ZONE, remoteDisk.getDiskId().getZone()); + assertEquals(diskId.getDisk(), remoteDisk.getDiskId().getDisk()); + assertNull(remoteDisk.getCreationTimestamp()); + assertNull(remoteDisk.getGeneratedId()); + assertTrue(remoteDisk.getConfiguration() instanceof ImageDiskConfiguration); + remoteConfiguration = remoteDisk.getConfiguration(); + assertEquals(IMAGE_ID, remoteConfiguration.getSourceImage()); + assertNull(remoteConfiguration.getSourceImageId()); + assertEquals(DiskConfiguration.Type.IMAGE, remoteConfiguration.getType()); + assertNull(remoteConfiguration.getSizeGb()); + assertEquals("pd-standard", remoteConfiguration.getDiskType().getType()); + assertNull(remoteDisk.getLastAttachTimestamp()); + assertNull(remoteDisk.getLastDetachTimestamp()); operation = remoteDisk.delete(); operation.waitFor(); assertNull(compute.getDisk(diskId)); } @Test - public void testCreateGetAndDeleteSnapshotAndSnapshotDisk() throws InterruptedException, TimeoutException { + public void testCreateGetAndDeleteSnapshotAndSnapshotDisk() + throws InterruptedException, TimeoutException { String diskName = BASE_RESOURCE_NAME + "create-and-get-snapshot-disk1"; String snapshotDiskName = BASE_RESOURCE_NAME + "create-and-get-snapshot-disk2"; DiskId diskId = DiskId.of(ZONE, diskName); @@ -979,28 +980,28 @@ public void testCreateGetAndDeleteSnapshotAndSnapshotDisk() throws InterruptedEx // test get snapshot with selected fields Snapshot snapshot = compute.getSnapshot(snapshotName, Compute.SnapshotOption.fields(Compute.SnapshotField.CREATION_TIMESTAMP)); - assertNull(snapshot.generatedId()); - assertNotNull(snapshot.snapshotId()); - assertNotNull(snapshot.creationTimestamp()); - assertNull(snapshot.description()); - assertNull(snapshot.status()); - assertNull(snapshot.diskSizeGb()); - assertNull(snapshot.licenses()); - assertNull(snapshot.sourceDisk()); - assertNull(snapshot.sourceDiskId()); - assertNull(snapshot.storageBytes()); - assertNull(snapshot.storageBytesStatus()); + assertNull(snapshot.getGeneratedId()); + assertNotNull(snapshot.getSnapshotId()); + assertNotNull(snapshot.getCreationTimestamp()); + assertNull(snapshot.getDescription()); + assertNull(snapshot.getStatus()); + assertNull(snapshot.getDiskSizeGb()); + assertNull(snapshot.getLicenses()); + assertNull(snapshot.getSourceDisk()); + assertNull(snapshot.getSourceDiskId()); + assertNull(snapshot.getStorageBytes()); + assertNull(snapshot.getStorageBytesStatus()); // test get snapshot snapshot = compute.getSnapshot(snapshotName); - assertNotNull(snapshot.generatedId()); - assertNotNull(snapshot.snapshotId()); - assertNotNull(snapshot.creationTimestamp()); - assertNotNull(snapshot.status()); - assertEquals(100L, (long) snapshot.diskSizeGb()); - assertEquals(diskName, snapshot.sourceDisk().disk()); - assertNotNull(snapshot.sourceDiskId()); - assertNotNull(snapshot.storageBytes()); - assertNotNull(snapshot.storageBytesStatus()); + assertNotNull(snapshot.getGeneratedId()); + assertNotNull(snapshot.getSnapshotId()); + assertNotNull(snapshot.getCreationTimestamp()); + assertNotNull(snapshot.getStatus()); + assertEquals(100L, (long) snapshot.getDiskSizeGb()); + assertEquals(diskName, snapshot.getSourceDisk().getDisk()); + assertNotNull(snapshot.getSourceDiskId()); + assertNotNull(snapshot.getStorageBytes()); + assertNotNull(snapshot.getStorageBytesStatus()); remoteDisk.delete(); diskInfo = DiskInfo.of(snapshotDiskId, SnapshotDiskConfiguration.of(SnapshotId.of(snapshotName))); @@ -1009,37 +1010,37 @@ public void testCreateGetAndDeleteSnapshotAndSnapshotDisk() throws InterruptedEx // test get disk remoteDisk = compute.getDisk(snapshotDiskId); assertNotNull(remoteDisk); - assertEquals(ZONE, remoteDisk.diskId().zone()); - assertEquals(snapshotDiskId.disk(), remoteDisk.diskId().disk()); - assertEquals(DiskInfo.CreationStatus.READY, remoteDisk.creationStatus()); - assertNotNull(remoteDisk.creationTimestamp()); - assertNotNull(remoteDisk.generatedId()); - assertTrue(remoteDisk.configuration() instanceof SnapshotDiskConfiguration); - SnapshotDiskConfiguration remoteConfiguration = remoteDisk.configuration(); - assertEquals(DiskConfiguration.Type.SNAPSHOT, remoteConfiguration.type()); - assertEquals(snapshotName, remoteConfiguration.sourceSnapshot().snapshot()); - assertEquals(100L, (long) remoteConfiguration.sizeGb()); - assertEquals("pd-standard", remoteConfiguration.diskType().type()); - assertNotNull(remoteConfiguration.sourceSnapshotId()); - assertNull(remoteDisk.lastAttachTimestamp()); - assertNull(remoteDisk.lastDetachTimestamp()); + assertEquals(ZONE, remoteDisk.getDiskId().getZone()); + assertEquals(snapshotDiskId.getDisk(), remoteDisk.getDiskId().getDisk()); + assertEquals(DiskInfo.CreationStatus.READY, remoteDisk.getCreationStatus()); + assertNotNull(remoteDisk.getCreationTimestamp()); + assertNotNull(remoteDisk.getGeneratedId()); + assertTrue(remoteDisk.getConfiguration() instanceof SnapshotDiskConfiguration); + SnapshotDiskConfiguration remoteConfiguration = remoteDisk.getConfiguration(); + assertEquals(DiskConfiguration.Type.SNAPSHOT, remoteConfiguration.getType()); + assertEquals(snapshotName, remoteConfiguration.getSourceSnapshot().getSnapshot()); + assertEquals(100L, (long) remoteConfiguration.getSizeGb()); + assertEquals("pd-standard", remoteConfiguration.getDiskType().getType()); + assertNotNull(remoteConfiguration.getSourceSnapshotId()); + assertNull(remoteDisk.getLastAttachTimestamp()); + assertNull(remoteDisk.getLastDetachTimestamp()); // test get disk with selected fields remoteDisk = compute.getDisk(snapshotDiskId, Compute.DiskOption.fields()); assertNotNull(remoteDisk); - assertEquals(ZONE, remoteDisk.diskId().zone()); - assertEquals(snapshotDiskId.disk(), remoteDisk.diskId().disk()); - assertNull(remoteDisk.creationStatus()); - assertNull(remoteDisk.creationTimestamp()); - assertNull(remoteDisk.generatedId()); - assertTrue(remoteDisk.configuration() instanceof SnapshotDiskConfiguration); - remoteConfiguration = remoteDisk.configuration(); - assertEquals(DiskConfiguration.Type.SNAPSHOT, remoteConfiguration.type()); - assertEquals(snapshotName, remoteConfiguration.sourceSnapshot().snapshot()); - assertNull(remoteConfiguration.sizeGb()); - assertEquals("pd-standard", remoteConfiguration.diskType().type()); - assertNull(remoteDisk.configuration().sourceSnapshotId()); - assertNull(remoteDisk.lastAttachTimestamp()); - assertNull(remoteDisk.lastDetachTimestamp()); + assertEquals(ZONE, remoteDisk.getDiskId().getZone()); + assertEquals(snapshotDiskId.getDisk(), remoteDisk.getDiskId().getDisk()); + assertNull(remoteDisk.getCreationStatus()); + assertNull(remoteDisk.getCreationTimestamp()); + assertNull(remoteDisk.getGeneratedId()); + assertTrue(remoteDisk.getConfiguration() instanceof SnapshotDiskConfiguration); + remoteConfiguration = remoteDisk.getConfiguration(); + assertEquals(DiskConfiguration.Type.SNAPSHOT, remoteConfiguration.getType()); + assertEquals(snapshotName, remoteConfiguration.getSourceSnapshot().getSnapshot()); + assertNull(remoteConfiguration.getSizeGb()); + assertEquals("pd-standard", remoteConfiguration.getDiskType().getType()); + assertNull(remoteDisk.getConfiguration().getSourceSnapshotId()); + assertNull(remoteDisk.getLastAttachTimestamp()); + assertNull(remoteDisk.getLastDetachTimestamp()); operation = remoteDisk.delete(); operation.waitFor(); assertNull(compute.getDisk(snapshotDiskId)); @@ -1069,18 +1070,18 @@ public void testListDisksAndSnapshots() throws InterruptedException, TimeoutExce int count = 0; while (diskIterator.hasNext()) { Disk remoteDisk = diskIterator.next(); - assertEquals(ZONE, remoteDisk.diskId().zone()); - assertTrue(diskSet.contains(remoteDisk.diskId().disk())); - assertEquals(DiskInfo.CreationStatus.READY, remoteDisk.creationStatus()); - assertNotNull(remoteDisk.creationTimestamp()); - assertNotNull(remoteDisk.generatedId()); - assertTrue(remoteDisk.configuration() instanceof StandardDiskConfiguration); - StandardDiskConfiguration remoteConfiguration = remoteDisk.configuration(); - assertEquals(100L, (long) remoteConfiguration.sizeGb()); - assertEquals("pd-ssd", remoteConfiguration.diskType().type()); - assertEquals(DiskConfiguration.Type.STANDARD, remoteConfiguration.type()); - assertNull(remoteDisk.lastAttachTimestamp()); - assertNull(remoteDisk.lastDetachTimestamp()); + assertEquals(ZONE, remoteDisk.getDiskId().getZone()); + assertTrue(diskSet.contains(remoteDisk.getDiskId().getDisk())); + assertEquals(DiskInfo.CreationStatus.READY, remoteDisk.getCreationStatus()); + assertNotNull(remoteDisk.getCreationTimestamp()); + assertNotNull(remoteDisk.getGeneratedId()); + assertTrue(remoteDisk.getConfiguration() instanceof StandardDiskConfiguration); + StandardDiskConfiguration remoteConfiguration = remoteDisk.getConfiguration(); + assertEquals(100L, (long) remoteConfiguration.getSizeGb()); + assertEquals("pd-ssd", remoteConfiguration.getDiskType().getType()); + assertEquals(DiskConfiguration.Type.STANDARD, remoteConfiguration.getType()); + assertNull(remoteDisk.getLastAttachTimestamp()); + assertNull(remoteDisk.getLastDetachTimestamp()); count++; } assertEquals(2, count); @@ -1091,18 +1092,18 @@ public void testListDisksAndSnapshots() throws InterruptedException, TimeoutExce diskIterator = diskPage.iterateAll(); while (diskIterator.hasNext()) { Disk remoteDisk = diskIterator.next(); - assertEquals(ZONE, remoteDisk.diskId().zone()); - assertTrue(diskSet.contains(remoteDisk.diskId().disk())); - assertEquals(DiskInfo.CreationStatus.READY, remoteDisk.creationStatus()); - assertNull(remoteDisk.creationTimestamp()); - assertNull(remoteDisk.generatedId()); - assertTrue(remoteDisk.configuration() instanceof StandardDiskConfiguration); - StandardDiskConfiguration remoteConfiguration = remoteDisk.configuration(); - assertNull(remoteConfiguration.sizeGb()); - assertEquals("pd-ssd", remoteConfiguration.diskType().type()); - assertEquals(DiskConfiguration.Type.STANDARD, remoteConfiguration.type()); - assertNull(remoteDisk.lastAttachTimestamp()); - assertNull(remoteDisk.lastDetachTimestamp()); + assertEquals(ZONE, remoteDisk.getDiskId().getZone()); + assertTrue(diskSet.contains(remoteDisk.getDiskId().getDisk())); + assertEquals(DiskInfo.CreationStatus.READY, remoteDisk.getCreationStatus()); + assertNull(remoteDisk.getCreationTimestamp()); + assertNull(remoteDisk.getGeneratedId()); + assertTrue(remoteDisk.getConfiguration() instanceof StandardDiskConfiguration); + StandardDiskConfiguration remoteConfiguration = remoteDisk.getConfiguration(); + assertNull(remoteConfiguration.getSizeGb()); + assertEquals("pd-ssd", remoteConfiguration.getDiskType().getType()); + assertEquals(DiskConfiguration.Type.STANDARD, remoteConfiguration.getType()); + assertNull(remoteDisk.getLastAttachTimestamp()); + assertNull(remoteDisk.getLastDetachTimestamp()); count++; } assertEquals(2, count); @@ -1122,15 +1123,15 @@ public void testListDisksAndSnapshots() throws InterruptedException, TimeoutExce count = 0; while (snapshotIterator.hasNext()) { Snapshot remoteSnapshot = snapshotIterator.next(); - assertNotNull(remoteSnapshot.generatedId()); - assertTrue(diskSet.contains(remoteSnapshot.snapshotId().snapshot())); - assertNotNull(remoteSnapshot.creationTimestamp()); - assertNotNull(remoteSnapshot.status()); - assertEquals(100L, (long) remoteSnapshot.diskSizeGb()); - assertTrue(diskSet.contains(remoteSnapshot.sourceDisk().disk())); - assertNotNull(remoteSnapshot.sourceDiskId()); - assertNotNull(remoteSnapshot.storageBytes()); - assertNotNull(remoteSnapshot.storageBytesStatus()); + assertNotNull(remoteSnapshot.getGeneratedId()); + assertTrue(diskSet.contains(remoteSnapshot.getSnapshotId().getSnapshot())); + assertNotNull(remoteSnapshot.getCreationTimestamp()); + assertNotNull(remoteSnapshot.getStatus()); + assertEquals(100L, (long) remoteSnapshot.getDiskSizeGb()); + assertTrue(diskSet.contains(remoteSnapshot.getSourceDisk().getDisk())); + assertNotNull(remoteSnapshot.getSourceDiskId()); + assertNotNull(remoteSnapshot.getStorageBytes()); + assertNotNull(remoteSnapshot.getStorageBytesStatus()); count++; } assertEquals(2, count); @@ -1141,15 +1142,15 @@ public void testListDisksAndSnapshots() throws InterruptedException, TimeoutExce count = 0; while (snapshotIterator.hasNext()) { Snapshot remoteSnapshot = snapshotIterator.next(); - assertNull(remoteSnapshot.generatedId()); - assertTrue(diskSet.contains(remoteSnapshot.snapshotId().snapshot())); - assertNotNull(remoteSnapshot.creationTimestamp()); - assertNull(remoteSnapshot.status()); - assertNull(remoteSnapshot.diskSizeGb()); - assertNull(remoteSnapshot.sourceDisk()); - assertNull(remoteSnapshot.sourceDiskId()); - assertNull(remoteSnapshot.storageBytes()); - assertNull(remoteSnapshot.storageBytesStatus()); + assertNull(remoteSnapshot.getGeneratedId()); + assertTrue(diskSet.contains(remoteSnapshot.getSnapshotId().getSnapshot())); + assertNotNull(remoteSnapshot.getCreationTimestamp()); + assertNull(remoteSnapshot.getStatus()); + assertNull(remoteSnapshot.getDiskSizeGb()); + assertNull(remoteSnapshot.getSourceDisk()); + assertNull(remoteSnapshot.getSourceDiskId()); + assertNull(remoteSnapshot.getStorageBytes()); + assertNull(remoteSnapshot.getStorageBytesStatus()); count++; } assertEquals(2, count); @@ -1181,16 +1182,16 @@ public void testAggregatedListDisks() throws InterruptedException, TimeoutExcept int count = 0; while (diskIterator.hasNext()) { Disk remoteDisk = diskIterator.next(); - assertTrue(zoneSet.contains(remoteDisk.diskId().zone())); - assertTrue(diskSet.contains(remoteDisk.diskId().disk())); - assertEquals(DiskInfo.CreationStatus.READY, remoteDisk.creationStatus()); - assertNotNull(remoteDisk.creationTimestamp()); - assertNotNull(remoteDisk.generatedId()); - assertTrue(remoteDisk.configuration() instanceof StandardDiskConfiguration); - StandardDiskConfiguration remoteConfiguration = remoteDisk.configuration(); - assertEquals(100L, (long) remoteConfiguration.sizeGb()); - assertEquals("pd-ssd", remoteConfiguration.diskType().type()); - assertEquals(DiskConfiguration.Type.STANDARD, remoteConfiguration.type()); + assertTrue(zoneSet.contains(remoteDisk.getDiskId().getZone())); + assertTrue(diskSet.contains(remoteDisk.getDiskId().getDisk())); + assertEquals(DiskInfo.CreationStatus.READY, remoteDisk.getCreationStatus()); + assertNotNull(remoteDisk.getCreationTimestamp()); + assertNotNull(remoteDisk.getGeneratedId()); + assertTrue(remoteDisk.getConfiguration() instanceof StandardDiskConfiguration); + StandardDiskConfiguration remoteConfiguration = remoteDisk.getConfiguration(); + assertEquals(100L, (long) remoteConfiguration.getSizeGb()); + assertEquals("pd-ssd", remoteConfiguration.getDiskType().getType()); + assertEquals(DiskConfiguration.Type.STANDARD, remoteConfiguration.getType()); count++; } assertEquals(2, count); @@ -1215,41 +1216,41 @@ public void testCreateGetAndDeprecateImage() throws InterruptedException, Timeou // test get image with selected fields Image image = compute.getImage(imageId, Compute.ImageOption.fields(Compute.ImageField.CREATION_TIMESTAMP)); - assertNull(image.generatedId()); - assertNotNull(image.imageId()); - assertNotNull(image.creationTimestamp()); - assertNull(image.description()); - assertNotNull(image.configuration()); - assertTrue(image.configuration() instanceof DiskImageConfiguration); - DiskImageConfiguration remoteConfiguration = image.configuration(); - Assert.assertEquals(ImageConfiguration.Type.DISK, remoteConfiguration.type()); - assertEquals(diskName, remoteConfiguration.sourceDisk().disk()); - assertNull(image.status()); - assertNull(image.diskSizeGb()); - assertNull(image.licenses()); - assertNull(image.deprecationStatus()); + assertNull(image.getGeneratedId()); + assertNotNull(image.getImageId()); + assertNotNull(image.getCreationTimestamp()); + assertNull(image.getDescription()); + assertNotNull(image.getConfiguration()); + assertTrue(image.getConfiguration() instanceof DiskImageConfiguration); + DiskImageConfiguration remoteConfiguration = image.getConfiguration(); + assertEquals(ImageConfiguration.Type.DISK, remoteConfiguration.getType()); + assertEquals(diskName, remoteConfiguration.getSourceDisk().getDisk()); + assertNull(image.getStatus()); + assertNull(image.getDiskSizeGb()); + assertNull(image.getLicenses()); + assertNull(image.getDeprecationStatus()); // test get image image = compute.getImage(imageId); - assertNotNull(image.generatedId()); - assertNotNull(image.imageId()); - assertNotNull(image.creationTimestamp()); - assertNotNull(image.configuration()); - assertTrue(image.configuration() instanceof DiskImageConfiguration); - remoteConfiguration = image.configuration(); - assertEquals(ImageConfiguration.Type.DISK, remoteConfiguration.type()); - assertEquals(diskName, remoteConfiguration.sourceDisk().disk()); - assertEquals(100L, (long) image.diskSizeGb()); - assertNotNull(image.status()); - assertNull(image.deprecationStatus()); + assertNotNull(image.getGeneratedId()); + assertNotNull(image.getImageId()); + assertNotNull(image.getCreationTimestamp()); + assertNotNull(image.getConfiguration()); + assertTrue(image.getConfiguration() instanceof DiskImageConfiguration); + remoteConfiguration = image.getConfiguration(); + assertEquals(ImageConfiguration.Type.DISK, remoteConfiguration.getType()); + assertEquals(diskName, remoteConfiguration.getSourceDisk().getDisk()); + assertEquals(100L, (long) image.getDiskSizeGb()); + assertNotNull(image.getStatus()); + assertNull(image.getDeprecationStatus()); // test deprecate image DeprecationStatus deprecationStatus = - DeprecationStatus.builder(DeprecationStatus.Status.DEPRECATED, imageId) - .deprecated(System.currentTimeMillis()) + DeprecationStatus.newBuilder(DeprecationStatus.Status.DEPRECATED, imageId) + .setDeprecated(System.currentTimeMillis()) .build(); operation = image.deprecate(deprecationStatus); operation.waitFor(); image = compute.getImage(imageId); - assertEquals(deprecationStatus, image.deprecationStatus()); + assertEquals(deprecationStatus, image.getDeprecationStatus()); remoteDisk.delete(); operation = image.delete(); operation.waitFor(); @@ -1264,12 +1265,12 @@ public void testListImages() { while (imageIterator.hasNext()) { count++; Image image = imageIterator.next(); - assertNotNull(image.generatedId()); - assertNotNull(image.imageId()); - assertNotNull(image.creationTimestamp()); - assertNotNull(image.configuration()); - assertNotNull(image.status()); - assertNotNull(image.diskSizeGb()); + assertNotNull(image.getGeneratedId()); + assertNotNull(image.getImageId()); + assertNotNull(image.getCreationTimestamp()); + assertNotNull(image.getConfiguration()); + assertNotNull(image.getStatus()); + assertNotNull(image.getDiskSizeGb()); } assertTrue(count > 0); } @@ -1283,14 +1284,14 @@ public void testListImagesWithSelectedFields() { while (imageIterator.hasNext()) { count++; Image image = imageIterator.next(); - assertNotNull(image.generatedId()); - assertNotNull(image.imageId()); - assertNull(image.creationTimestamp()); - assertNotNull(image.configuration()); - assertNull(image.status()); - assertNull(image.diskSizeGb()); - assertNull(image.licenses()); - assertNull(image.deprecationStatus()); + assertNotNull(image.getGeneratedId()); + assertNotNull(image.getImageId()); + assertNull(image.getCreationTimestamp()); + assertNotNull(image.getConfiguration()); + assertNull(image.getStatus()); + assertNull(image.getDiskSizeGb()); + assertNull(image.getLicenses()); + assertNull(image.getDeprecationStatus()); } assertTrue(count > 0); } @@ -1304,14 +1305,14 @@ public void testListImagesWithFilter() { while (imageIterator.hasNext()) { count++; Image image = imageIterator.next(); - assertNotNull(image.generatedId()); - assertNotNull(image.imageId()); - assertNotNull(image.creationTimestamp()); - assertNotNull(image.configuration()); - assertNotNull(image.status()); - assertNotNull(image.diskSizeGb()); + assertNotNull(image.getGeneratedId()); + assertNotNull(image.getImageId()); + assertNotNull(image.getCreationTimestamp()); + assertNotNull(image.getConfiguration()); + assertNotNull(image.getStatus()); + assertNotNull(image.getDiskSizeGb()); assertEquals(365056004L, - (long) image.configuration().archiveSizeBytes()); + (long) image.getConfiguration().getArchiveSizeBytes()); } assertTrue(count > 0); } @@ -1325,23 +1326,23 @@ public void testCreateAndGetNetwork() throws InterruptedException, TimeoutExcept Operation operation = compute.create(networkInfo); operation.waitFor(); // test get network with selected fields - Network network = compute.getNetwork(networkId.network(), + Network network = compute.getNetwork(networkId.getNetwork(), Compute.NetworkOption.fields(Compute.NetworkField.CREATION_TIMESTAMP)); - assertEquals(networkId.network(), network.networkId().network()); - assertNull(network.generatedId()); - assertNotNull(network.creationTimestamp()); - assertNull(network.description()); - assertEquals(NetworkConfiguration.Type.STANDARD, network.configuration().type()); - StandardNetworkConfiguration remoteConfiguration = network.configuration(); - assertEquals("192.168.0.0/16", remoteConfiguration.ipRange()); + assertEquals(networkId.getNetwork(), network.getNetworkId().getNetwork()); + assertNull(network.getGeneratedId()); + assertNotNull(network.getCreationTimestamp()); + assertNull(network.getDescription()); + assertEquals(NetworkConfiguration.Type.STANDARD, network.getConfiguration().getType()); + StandardNetworkConfiguration remoteConfiguration = network.getConfiguration(); + assertEquals("192.168.0.0/16", remoteConfiguration.getIpRange()); // test get network - network = compute.getNetwork(networkId.network()); - assertEquals(networkId.network(), network.networkId().network()); - assertNotNull(network.generatedId()); - assertNotNull(network.creationTimestamp()); - assertEquals(NetworkConfiguration.Type.STANDARD, network.configuration().type()); - remoteConfiguration = network.configuration(); - assertEquals("192.168.0.0/16", remoteConfiguration.ipRange()); + network = compute.getNetwork(networkId.getNetwork()); + assertEquals(networkId.getNetwork(), network.getNetworkId().getNetwork()); + assertNotNull(network.getGeneratedId()); + assertNotNull(network.getCreationTimestamp()); + assertEquals(NetworkConfiguration.Type.STANDARD, network.getConfiguration().getType()); + remoteConfiguration = network.getConfiguration(); + assertEquals("192.168.0.0/16", remoteConfiguration.getIpRange()); operation = network.delete(); operation.waitFor(); assertNull(compute.getNetwork(name)); @@ -1362,12 +1363,12 @@ public void testListNetworks() throws InterruptedException, TimeoutException { int count = 0; while (networkIterator.hasNext()) { Network network = networkIterator.next(); - assertEquals(networkId.network(), network.networkId().network()); - assertNotNull(network.generatedId()); - assertNotNull(network.creationTimestamp()); - assertEquals(NetworkConfiguration.Type.STANDARD, network.configuration().type()); - StandardNetworkConfiguration remoteConfiguration = network.configuration(); - assertEquals("192.168.0.0/16", remoteConfiguration.ipRange()); + assertEquals(networkId.getNetwork(), network.getNetworkId().getNetwork()); + assertNotNull(network.getGeneratedId()); + assertNotNull(network.getCreationTimestamp()); + assertEquals(NetworkConfiguration.Type.STANDARD, network.getConfiguration().getType()); + StandardNetworkConfiguration remoteConfiguration = network.getConfiguration(); + assertEquals("192.168.0.0/16", remoteConfiguration.getIpRange()); count++; } assertEquals(1, count); @@ -1378,13 +1379,13 @@ public void testListNetworks() throws InterruptedException, TimeoutException { networkIterator = networkPage.iterateAll(); while (networkIterator.hasNext()) { Network network = networkIterator.next(); - assertEquals(networkId.network(), network.networkId().network()); - assertNull(network.generatedId()); - assertNotNull(network.creationTimestamp()); - assertNull(network.description()); - assertEquals(NetworkConfiguration.Type.STANDARD, network.configuration().type()); - StandardNetworkConfiguration remoteConfiguration = network.configuration(); - assertEquals("192.168.0.0/16", remoteConfiguration.ipRange()); + assertEquals(networkId.getNetwork(), network.getNetworkId().getNetwork()); + assertNull(network.getGeneratedId()); + assertNotNull(network.getCreationTimestamp()); + assertNull(network.getDescription()); + assertEquals(NetworkConfiguration.Type.STANDARD, network.getConfiguration().getType()); + StandardNetworkConfiguration remoteConfiguration = network.getConfiguration(); + assertEquals("192.168.0.0/16", remoteConfiguration.getIpRange()); count++; } assertEquals(1, count); @@ -1401,13 +1402,13 @@ public void testCreateNetworkAndSubnetwork() throws InterruptedException, Timeou Operation operation = compute.create(networkInfo); operation.waitFor(); // test get network - Network network = compute.getNetwork(networkId.network()); - assertEquals(networkId.network(), network.networkId().network()); - assertNotNull(network.generatedId()); - assertNotNull(network.creationTimestamp()); - assertEquals(NetworkConfiguration.Type.SUBNET, network.configuration().type()); - assertTrue(network.configuration() instanceof SubnetNetworkConfiguration); - assertFalse(network.configuration().autoCreateSubnetworks()); + Network network = compute.getNetwork(networkId.getNetwork()); + assertEquals(networkId.getNetwork(), network.getNetworkId().getNetwork()); + assertNotNull(network.getGeneratedId()); + assertNotNull(network.getCreationTimestamp()); + assertEquals(NetworkConfiguration.Type.SUBNET, network.getConfiguration().getType()); + assertTrue(network.getConfiguration() instanceof SubnetNetworkConfiguration); + assertFalse(network.getConfiguration().autoCreateSubnetworks()); String subnetworkName = BASE_RESOURCE_NAME + "create-subnetwork-subnetwork"; SubnetworkId subnetworkId = SubnetworkId.of(REGION, subnetworkName); SubnetworkInfo subnetworkInfo = SubnetworkInfo.of(subnetworkId, networkId, "192.168.0.0/16"); @@ -1416,21 +1417,21 @@ public void testCreateNetworkAndSubnetwork() throws InterruptedException, Timeou // test get subnetwork with selected fields Subnetwork subnetwork = compute.getSubnetwork(subnetworkId, Compute.SubnetworkOption.fields(Compute.SubnetworkField.CREATION_TIMESTAMP)); - assertNull(subnetwork.generatedId()); - assertEquals(subnetworkId.subnetwork(), subnetwork.subnetworkId().subnetwork()); - assertNotNull(subnetwork.creationTimestamp()); - assertNull(subnetwork.description()); - assertNull(subnetwork.gatewayAddress()); - assertNull(subnetwork.network()); - assertNull(subnetwork.ipRange()); + assertNull(subnetwork.getGeneratedId()); + assertEquals(subnetworkId.getSubnetwork(), subnetwork.getSubnetworkId().getSubnetwork()); + assertNotNull(subnetwork.getCreationTimestamp()); + assertNull(subnetwork.getDescription()); + assertNull(subnetwork.getGatewayAddress()); + assertNull(subnetwork.getNetwork()); + assertNull(subnetwork.getIpRange()); // test get subnetwork subnetwork = compute.getSubnetwork(subnetworkId); - assertNotNull(subnetwork.generatedId()); - assertEquals(subnetworkId.subnetwork(), subnetwork.subnetworkId().subnetwork()); - assertNotNull(subnetwork.creationTimestamp()); - assertNotNull(subnetwork.gatewayAddress()); - assertEquals(networkId.network(), subnetwork.network().network()); - assertEquals("192.168.0.0/16", subnetwork.ipRange()); + assertNotNull(subnetwork.getGeneratedId()); + assertEquals(subnetworkId.getSubnetwork(), subnetwork.getSubnetworkId().getSubnetwork()); + assertNotNull(subnetwork.getCreationTimestamp()); + assertNotNull(subnetwork.getGatewayAddress()); + assertEquals(networkId.getNetwork(), subnetwork.getNetwork().getNetwork()); + assertEquals("192.168.0.0/16", subnetwork.getIpRange()); // test list subnetworks Compute.SubnetworkFilter filter = Compute.SubnetworkFilter.equals(Compute.SubnetworkField.NAME, subnetworkName); @@ -1440,12 +1441,13 @@ public void testCreateNetworkAndSubnetwork() throws InterruptedException, Timeou int count = 0; while (subnetworkIterator.hasNext()) { Subnetwork remoteSubnetwork = subnetworkIterator.next(); - assertNotNull(remoteSubnetwork.generatedId()); - assertEquals(subnetworkId.subnetwork(), remoteSubnetwork.subnetworkId().subnetwork()); - assertNotNull(remoteSubnetwork.creationTimestamp()); - assertNotNull(remoteSubnetwork.gatewayAddress()); - assertEquals(networkId.network(), remoteSubnetwork.network().network()); - assertEquals("192.168.0.0/16", remoteSubnetwork.ipRange()); + assertNotNull(remoteSubnetwork.getGeneratedId()); + assertEquals(subnetworkId.getSubnetwork(), + remoteSubnetwork.getSubnetworkId().getSubnetwork()); + assertNotNull(remoteSubnetwork.getCreationTimestamp()); + assertNotNull(remoteSubnetwork.getGatewayAddress()); + assertEquals(networkId.getNetwork(), remoteSubnetwork.getNetwork().getNetwork()); + assertEquals("192.168.0.0/16", remoteSubnetwork.getIpRange()); count++; } assertEquals(1, count); @@ -1456,13 +1458,14 @@ public void testCreateNetworkAndSubnetwork() throws InterruptedException, Timeou count = 0; while (subnetworkIterator.hasNext()) { Subnetwork remoteSubnetwork = subnetworkIterator.next(); - assertNull(remoteSubnetwork.generatedId()); - assertEquals(subnetworkId.subnetwork(), remoteSubnetwork.subnetworkId().subnetwork()); - assertNotNull(remoteSubnetwork.creationTimestamp()); - assertNull(remoteSubnetwork.description()); - assertNull(remoteSubnetwork.gatewayAddress()); - assertNull(remoteSubnetwork.network()); - assertNull(remoteSubnetwork.ipRange()); + assertNull(remoteSubnetwork.getGeneratedId()); + assertEquals(subnetworkId.getSubnetwork(), + remoteSubnetwork.getSubnetworkId().getSubnetwork()); + assertNotNull(remoteSubnetwork.getCreationTimestamp()); + assertNull(remoteSubnetwork.getDescription()); + assertNull(remoteSubnetwork.getGatewayAddress()); + assertNull(remoteSubnetwork.getNetwork()); + assertNull(remoteSubnetwork.getIpRange()); count++; } assertEquals(1, count); @@ -1506,13 +1509,13 @@ public void testAggregatedListSubnetworks() throws InterruptedException, Timeout int count = 0; while (subnetworkIterator.hasNext()) { Subnetwork remoteSubnetwork = subnetworkIterator.next(); - assertNotNull(remoteSubnetwork.generatedId()); - assertTrue(regionSet.contains(remoteSubnetwork.subnetworkId().region())); - assertTrue(subnetworkSet.contains(remoteSubnetwork.subnetworkId().subnetwork())); - assertNotNull(remoteSubnetwork.creationTimestamp()); - assertNotNull(remoteSubnetwork.gatewayAddress()); - assertEquals(networkId.network(), remoteSubnetwork.network().network()); - assertTrue(rangeSet.contains(remoteSubnetwork.ipRange())); + assertNotNull(remoteSubnetwork.getGeneratedId()); + assertTrue(regionSet.contains(remoteSubnetwork.getSubnetworkId().getRegion())); + assertTrue(subnetworkSet.contains(remoteSubnetwork.getSubnetworkId().getSubnetwork())); + assertNotNull(remoteSubnetwork.getCreationTimestamp()); + assertNotNull(remoteSubnetwork.getGatewayAddress()); + assertEquals(networkId.getNetwork(), remoteSubnetwork.getNetwork().getNetwork()); + assertTrue(rangeSet.contains(remoteSubnetwork.getIpRange())); count++; } assertEquals(2, count); @@ -1538,64 +1541,68 @@ public void testCreateGetAndDeleteInstance() throws InterruptedException, Timeou // Create an instance InstanceId instanceId = InstanceId.of(ZONE, instanceName); NetworkId networkId = NetworkId.of("default"); - NetworkInterface networkInterface = NetworkInterface.builder(networkId) - .accessConfigurations(NetworkInterface.AccessConfig.builder().name("NAT").natIp(address.address()).build()) + NetworkInterface networkInterface = NetworkInterface.newBuilder(networkId) + .setAccessConfigurations(NetworkInterface.AccessConfig.newBuilder() + .setName("NAT") + .setNatIp(address.getAddress()).build()) .build(); AttachedDisk disk1 = AttachedDisk.of("dev0", - AttachedDisk.CreateDiskConfiguration.builder(IMAGE_ID).autoDelete(true).build()); + AttachedDisk.CreateDiskConfiguration.newBuilder(IMAGE_ID).setAutoDelete(true).build()); AttachedDisk disk2 = - AttachedDisk.of("dev1", AttachedDisk.ScratchDiskConfiguration.of(DiskTypeId.of(ZONE, DISK_TYPE))); + AttachedDisk.of("dev1", + AttachedDisk.ScratchDiskConfiguration.of(DiskTypeId.of(ZONE, DISK_TYPE))); InstanceInfo instanceInfo = - InstanceInfo.builder(instanceId, MachineTypeId.of(ZONE, "n1-standard-1")) - .attachedDisks(disk1, disk2) - .networkInterfaces(networkInterface) + InstanceInfo.newBuilder(instanceId, MachineTypeId.of(ZONE, "n1-standard-1")) + .setAttachedDisks(disk1, disk2) + .setNetworkInterfaces(networkInterface) .build(); operation = compute.create(instanceInfo); operation.waitFor(); // test get Instance remoteInstance = compute.getInstance(instanceId); - assertEquals(instanceName, remoteInstance.instanceId().instance()); - assertEquals(ZONE, remoteInstance.instanceId().zone()); - assertEquals(InstanceInfo.Status.RUNNING, remoteInstance.status()); - assertEquals("n1-standard-1", remoteInstance.machineType().type()); - assertEquals(ZONE, remoteInstance.machineType().zone()); - assertNotNull(remoteInstance.creationTimestamp()); + assertEquals(instanceName, remoteInstance.getInstanceId().getInstance()); + assertEquals(ZONE, remoteInstance.getInstanceId().getZone()); + assertEquals(InstanceInfo.Status.RUNNING, remoteInstance.getStatus()); + assertEquals("n1-standard-1", remoteInstance.getMachineType().getType()); + assertEquals(ZONE, remoteInstance.getMachineType().getZone()); + assertNotNull(remoteInstance.getCreationTimestamp()); Set deviceSet = ImmutableSet.of("dev0", "dev1"); - assertEquals(2, remoteInstance.attachedDisks().size()); - for (AttachedDisk remoteAttachedDisk : remoteInstance.attachedDisks()) { - assertTrue(deviceSet.contains(remoteAttachedDisk.deviceName())); + assertEquals(2, remoteInstance.getAttachedDisks().size()); + for (AttachedDisk remoteAttachedDisk : remoteInstance.getAttachedDisks()) { + assertTrue(deviceSet.contains(remoteAttachedDisk.getDeviceName())); } - Assert.assertEquals(AttachedDisk.AttachedDiskConfiguration.Type.PERSISTENT, - remoteInstance.attachedDisks().get(0).configuration().type()); + assertEquals(AttachedDisk.AttachedDiskConfiguration.Type.PERSISTENT, + remoteInstance.getAttachedDisks().get(0).getConfiguration().getType()); AttachedDisk.PersistentDiskConfiguration remoteConfiguration = - remoteInstance.attachedDisks().get(0).configuration(); - assertEquals(instanceName, remoteConfiguration.sourceDisk().disk()); - assertEquals(ZONE, remoteConfiguration.sourceDisk().zone()); + remoteInstance.getAttachedDisks().get(0).getConfiguration(); + assertEquals(instanceName, remoteConfiguration.getSourceDisk().getDisk()); + assertEquals(ZONE, remoteConfiguration.getSourceDisk().getZone()); assertTrue(remoteConfiguration.boot()); assertTrue(remoteConfiguration.autoDelete()); - assertEquals(1, remoteInstance.networkInterfaces().size()); - NetworkInterface remoteNetworkInterface = remoteInstance.networkInterfaces().get(0); - assertNotNull(remoteNetworkInterface.name()); - assertEquals("default", remoteNetworkInterface.network().network()); - List remoteAccessConfigurations = remoteNetworkInterface.accessConfigurations(); + assertEquals(1, remoteInstance.getNetworkInterfaces().size()); + NetworkInterface remoteNetworkInterface = remoteInstance.getNetworkInterfaces().get(0); + assertNotNull(remoteNetworkInterface.getName()); + assertEquals("default", remoteNetworkInterface.getNetwork().getNetwork()); + List remoteAccessConfigurations = + remoteNetworkInterface.getAccessConfigurations(); assertNotNull(remoteAccessConfigurations); assertEquals(1, remoteAccessConfigurations.size()); NetworkInterface.AccessConfig remoteAccessConfig = remoteAccessConfigurations.get(0); - assertEquals(address.address(), remoteAccessConfig.natIp()); - assertEquals("NAT", remoteAccessConfig.name()); - assertNotNull(remoteInstance.metadata()); - assertNotNull(remoteInstance.tags()); + assertEquals(address.getAddress(), remoteAccessConfig.getNatIp()); + assertEquals("NAT", remoteAccessConfig.getName()); + assertNotNull(remoteInstance.getMetadata()); + assertNotNull(remoteInstance.getTags()); // test get with selected fields remoteInstance = compute.getInstance(instanceId, Compute.InstanceOption.fields(Compute.InstanceField.CREATION_TIMESTAMP)); - assertEquals(instanceName, remoteInstance.instanceId().instance()); - assertEquals(ZONE, remoteInstance.instanceId().zone()); - assertNull(remoteInstance.machineType()); - assertNotNull(remoteInstance.creationTimestamp()); - assertNull(remoteInstance.attachedDisks()); - assertNull(remoteInstance.networkInterfaces()); - assertNull(remoteInstance.metadata()); - assertNull(remoteInstance.tags()); + assertEquals(instanceName, remoteInstance.getInstanceId().getInstance()); + assertEquals(ZONE, remoteInstance.getInstanceId().getZone()); + assertNull(remoteInstance.getMachineType()); + assertNotNull(remoteInstance.getCreationTimestamp()); + assertNull(remoteInstance.getAttachedDisks()); + assertNull(remoteInstance.getNetworkInterfaces()); + assertNull(remoteInstance.getMetadata()); + assertNull(remoteInstance.getTags()); // test get default serial port output String serialPortOutput = remoteInstance.getSerialPortOutput(); assertNotNull(serialPortOutput); @@ -1613,34 +1620,34 @@ public void testStartStopAndResetInstance() throws InterruptedException, Timeout String instanceName = BASE_RESOURCE_NAME + "start-stop-reset-instance"; InstanceId instanceId = InstanceId.of(ZONE, instanceName); NetworkId networkId = NetworkId.of("default"); - NetworkInterface networkInterface = NetworkInterface.builder(networkId).build(); + NetworkInterface networkInterface = NetworkInterface.newBuilder(networkId).build(); AttachedDisk disk = AttachedDisk.of("dev0", - AttachedDisk.CreateDiskConfiguration.builder(IMAGE_ID).autoDelete(true).build()); + AttachedDisk.CreateDiskConfiguration.newBuilder(IMAGE_ID).setAutoDelete(true).build()); InstanceInfo instanceInfo = - InstanceInfo.builder(instanceId, MachineTypeId.of(ZONE, MACHINE_TYPE)) - .attachedDisks(disk) - .networkInterfaces(networkInterface) + InstanceInfo.newBuilder(instanceId, MachineTypeId.of(ZONE, MACHINE_TYPE)) + .setAttachedDisks(disk) + .setNetworkInterfaces(networkInterface) .build(); Operation operation = compute.create(instanceInfo); operation.waitFor(); Instance remoteInstance = compute.getInstance(instanceId, Compute.InstanceOption.fields(Compute.InstanceField.STATUS)); - assertEquals(InstanceInfo.Status.RUNNING, remoteInstance.status()); + assertEquals(InstanceInfo.Status.RUNNING, remoteInstance.getStatus()); operation = remoteInstance.stop(); operation.waitFor(); remoteInstance = compute.getInstance(instanceId, Compute.InstanceOption.fields(Compute.InstanceField.STATUS)); - assertEquals(InstanceInfo.Status.TERMINATED, remoteInstance.status()); + assertEquals(InstanceInfo.Status.TERMINATED, remoteInstance.getStatus()); operation = remoteInstance.start(); operation.waitFor(); remoteInstance = compute.getInstance(instanceId, Compute.InstanceOption.fields(Compute.InstanceField.STATUS)); - assertEquals(InstanceInfo.Status.RUNNING, remoteInstance.status()); + assertEquals(InstanceInfo.Status.RUNNING, remoteInstance.getStatus()); operation = remoteInstance.reset(); operation.waitFor(); remoteInstance = compute.getInstance(instanceId, Compute.InstanceOption.fields(Compute.InstanceField.STATUS)); - assertEquals(InstanceInfo.Status.RUNNING, remoteInstance.status()); + assertEquals(InstanceInfo.Status.RUNNING, remoteInstance.getStatus()); remoteInstance.delete(); } @@ -1649,13 +1656,13 @@ public void testSetInstanceProperties() throws InterruptedException, TimeoutExce String instanceName = BASE_RESOURCE_NAME + "set-properties-instance"; InstanceId instanceId = InstanceId.of(ZONE, instanceName); NetworkId networkId = NetworkId.of("default"); - NetworkInterface networkInterface = NetworkInterface.builder(networkId).build(); + NetworkInterface networkInterface = NetworkInterface.newBuilder(networkId).build(); AttachedDisk disk = AttachedDisk.of("dev0", - AttachedDisk.CreateDiskConfiguration.builder(IMAGE_ID).autoDelete(true).build()); + AttachedDisk.CreateDiskConfiguration.newBuilder(IMAGE_ID).setAutoDelete(true).build()); InstanceInfo instanceInfo = - InstanceInfo.builder(instanceId, MachineTypeId.of(ZONE, MACHINE_TYPE)) - .attachedDisks(disk) - .networkInterfaces(networkInterface) + InstanceInfo.newBuilder(instanceId, MachineTypeId.of(ZONE, MACHINE_TYPE)) + .setAttachedDisks(disk) + .setNetworkInterfaces(networkInterface) .build(); Operation operation = compute.create(instanceInfo); operation.waitFor(); @@ -1665,27 +1672,28 @@ public void testSetInstanceProperties() throws InterruptedException, TimeoutExce operation = remoteInstance.setTags(tags); operation.waitFor(); remoteInstance = compute.getInstance(instanceId); - assertEquals(tags, remoteInstance.tags().values()); + assertEquals(tags, remoteInstance.getTags().getValues()); // test set metadata Map metadata = ImmutableMap.of("key", "value"); operation = remoteInstance.setMetadata(metadata); operation.waitFor(); remoteInstance = compute.getInstance(instanceId); - assertEquals(metadata, remoteInstance.metadata().values()); + assertEquals(metadata, remoteInstance.getMetadata().getValues()); // test set machine type operation = remoteInstance.stop(); operation.waitFor(); operation = remoteInstance.setMachineType(MachineTypeId.of(ZONE, "n1-standard-1")); operation.waitFor(); remoteInstance = compute.getInstance(instanceId); - assertEquals("n1-standard-1", remoteInstance.machineType().type()); - assertEquals(ZONE, remoteInstance.machineType().zone()); + assertEquals("n1-standard-1", remoteInstance.getMachineType().getType()); + assertEquals(ZONE, remoteInstance.getMachineType().getZone()); // test set scheduling options - SchedulingOptions options = SchedulingOptions.standard(false, SchedulingOptions.Maintenance.TERMINATE); + SchedulingOptions options = + SchedulingOptions.standard(false, SchedulingOptions.Maintenance.TERMINATE); operation = remoteInstance.setSchedulingOptions(options); operation.waitFor(); remoteInstance = compute.getInstance(instanceId); - assertEquals(options, remoteInstance.schedulingOptions()); + assertEquals(options, remoteInstance.getSchedulingOptions()); remoteInstance.delete(); } @@ -1695,13 +1703,13 @@ public void testAttachAndDetachDisk() throws InterruptedException, TimeoutExcept String diskName = BASE_RESOURCE_NAME + "attach-and-detach-disk"; InstanceId instanceId = InstanceId.of(ZONE, instanceName); NetworkId networkId = NetworkId.of("default"); - NetworkInterface networkInterface = NetworkInterface.builder(networkId).build(); + NetworkInterface networkInterface = NetworkInterface.newBuilder(networkId).build(); AttachedDisk disk = AttachedDisk.of("dev0", - AttachedDisk.CreateDiskConfiguration.builder(IMAGE_ID).autoDelete(true).build()); + AttachedDisk.CreateDiskConfiguration.newBuilder(IMAGE_ID).setAutoDelete(true).build()); InstanceInfo instanceInfo = - InstanceInfo.builder(instanceId, MachineTypeId.of(ZONE, MACHINE_TYPE)) - .attachedDisks(disk) - .networkInterfaces(networkInterface) + InstanceInfo.newBuilder(instanceId, MachineTypeId.of(ZONE, MACHINE_TYPE)) + .setAttachedDisks(disk) + .setNetworkInterfaces(networkInterface) .build(); Operation instanceOperation = compute.create(instanceInfo); DiskId diskId = DiskId.of(ZONE, diskName); @@ -1712,29 +1720,29 @@ public void testAttachAndDetachDisk() throws InterruptedException, TimeoutExcept Instance remoteInstance = compute.getInstance(instanceId); // test attach disk instanceOperation = remoteInstance.attachDisk("dev1", - AttachedDisk.PersistentDiskConfiguration.builder(diskId).build()); + AttachedDisk.PersistentDiskConfiguration.newBuilder(diskId).build()); instanceOperation.waitFor(); remoteInstance = compute.getInstance(instanceId); Set deviceSet = ImmutableSet.of("dev0", "dev1"); - assertEquals(2, remoteInstance.attachedDisks().size()); - for (AttachedDisk remoteAttachedDisk : remoteInstance.attachedDisks()) { - assertTrue(deviceSet.contains(remoteAttachedDisk.deviceName())); + assertEquals(2, remoteInstance.getAttachedDisks().size()); + for (AttachedDisk remoteAttachedDisk : remoteInstance.getAttachedDisks()) { + assertTrue(deviceSet.contains(remoteAttachedDisk.getDeviceName())); } // test set disk auto-delete instanceOperation = remoteInstance.setDiskAutoDelete("dev1", true); instanceOperation.waitFor(); remoteInstance = compute.getInstance(instanceId); - assertEquals(2, remoteInstance.attachedDisks().size()); - for (AttachedDisk remoteAttachedDisk : remoteInstance.attachedDisks()) { - assertTrue(deviceSet.contains(remoteAttachedDisk.deviceName())); - assertTrue(remoteAttachedDisk.configuration().autoDelete()); + assertEquals(2, remoteInstance.getAttachedDisks().size()); + for (AttachedDisk remoteAttachedDisk : remoteInstance.getAttachedDisks()) { + assertTrue(deviceSet.contains(remoteAttachedDisk.getDeviceName())); + assertTrue(remoteAttachedDisk.getConfiguration().autoDelete()); } // test detach disk instanceOperation = remoteInstance.detachDisk("dev1"); instanceOperation.waitFor(); remoteInstance = compute.getInstance(instanceId); - assertEquals(1, remoteInstance.attachedDisks().size()); - assertEquals("dev0", remoteInstance.attachedDisks().get(0).deviceName()); + assertEquals(1, remoteInstance.getAttachedDisks().size()); + assertEquals("dev0", remoteInstance.getAttachedDisks().get(0).getDeviceName()); remoteInstance.delete(); compute.deleteDisk(diskId); } @@ -1745,13 +1753,13 @@ public void testAddAndRemoveAccessConfig() throws InterruptedException, TimeoutE String addressName = BASE_RESOURCE_NAME + "add-and-remove-access-address"; InstanceId instanceId = InstanceId.of(ZONE, instanceName); NetworkId networkId = NetworkId.of("default"); - NetworkInterface networkInterface = NetworkInterface.builder(networkId).build(); + NetworkInterface networkInterface = NetworkInterface.newBuilder(networkId).build(); AttachedDisk disk = AttachedDisk.of("dev0", - AttachedDisk.CreateDiskConfiguration.builder(IMAGE_ID).autoDelete(true).build()); + AttachedDisk.CreateDiskConfiguration.newBuilder(IMAGE_ID).setAutoDelete(true).build()); InstanceInfo instanceInfo = - InstanceInfo.builder(instanceId, MachineTypeId.of(ZONE, MACHINE_TYPE)) - .attachedDisks(disk) - .networkInterfaces(networkInterface) + InstanceInfo.newBuilder(instanceId, MachineTypeId.of(ZONE, MACHINE_TYPE)) + .setAttachedDisks(disk) + .setNetworkInterfaces(networkInterface) .build(); Operation instanceOperation = compute.create(instanceInfo); AddressId addressId = RegionAddressId.of(REGION, addressName); @@ -1761,24 +1769,24 @@ public void testAddAndRemoveAccessConfig() throws InterruptedException, TimeoutE instanceOperation.waitFor(); Address remoteAddress = compute.getAddress(addressId); Instance remoteInstance = compute.getInstance(instanceId); - String networkInterfaceName = remoteInstance.networkInterfaces().get(0).name(); + String networkInterfaceName = remoteInstance.getNetworkInterfaces().get(0).getName(); // test add access config - NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.builder() - .natIp(remoteAddress.address()) - .name("NAT") + NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.newBuilder() + .setNatIp(remoteAddress.getAddress()) + .setName("NAT") .build(); instanceOperation = remoteInstance.addAccessConfig(networkInterfaceName, accessConfig); instanceOperation.waitFor(); remoteInstance = compute.getInstance(instanceId); List accessConfigurations = - remoteInstance.networkInterfaces().get(0).accessConfigurations(); + remoteInstance.getNetworkInterfaces().get(0).getAccessConfigurations(); assertEquals(1, accessConfigurations.size()); - assertEquals("NAT", accessConfigurations.get(0).name()); + assertEquals("NAT", accessConfigurations.get(0).getName()); // test delete access config instanceOperation = remoteInstance.deleteAccessConfig(networkInterfaceName, "NAT"); instanceOperation.waitFor(); remoteInstance = compute.getInstance(instanceId); - assertTrue(remoteInstance.networkInterfaces().get(0).accessConfigurations().isEmpty()); + assertTrue(remoteInstance.getNetworkInterfaces().get(0).getAccessConfigurations().isEmpty()); remoteInstance.delete(); remoteAddress.delete(); } diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/testing/RemoteComputeHelperTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/testing/RemoteComputeHelperTest.java index 947bd4f1ea8c..5e57e658d509 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/testing/RemoteComputeHelperTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/testing/RemoteComputeHelperTest.java @@ -74,7 +74,8 @@ public void testBaseResourceName() { @Test public void testCreateFromStream() { RemoteComputeHelper helper = RemoteComputeHelper.create(PROJECT_ID, JSON_KEY_STREAM); - ComputeOptions options = helper.options(); + ComputeOptions options = helper.getOptions(); + assertEquals(options, helper.options()); assertEquals(PROJECT_ID, options.projectId()); assertEquals(60000, options.connectTimeout()); assertEquals(60000, options.readTimeout()); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/ComputeExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/ComputeExample.java index 7d8fbd2e228d..bea18bedc3c0 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/ComputeExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/ComputeExample.java @@ -308,7 +308,7 @@ private static class ListDiskTypesAction extends OptionalZoneAction { public void run(Compute compute, ZoneId zone) { Iterator diskTypeIterator; if (zone != null) { - diskTypeIterator = compute.listDiskTypes(zone.zone()).iterateAll(); + diskTypeIterator = compute.listDiskTypes(zone.getZone()).iterateAll(); } else { diskTypeIterator = compute.listDiskTypes().iterateAll(); } @@ -363,7 +363,7 @@ private static class ListMachineTypesAction extends OptionalZoneAction { public void run(Compute compute, ZoneId zone) { Iterator machineTypeIterator; if (zone != null) { - machineTypeIterator = compute.listMachineTypes(zone.zone()).iterateAll(); + machineTypeIterator = compute.listMachineTypes(zone.getZone()).iterateAll(); } else { machineTypeIterator = compute.listMachineTypes().iterateAll(); } @@ -429,7 +429,7 @@ public void run(Compute compute, Void arg) { private static class RegionInfoAction extends ComputeAction { @Override public void run(Compute compute, RegionId region) { - System.out.printf("Region info: %s%n", compute.getRegion(region.region())); + System.out.printf("Region info: %s%n", compute.getRegion(region.getRegion())); } @Override @@ -475,7 +475,7 @@ public void run(Compute compute, Void arg) { private static class ZoneInfoAction extends ComputeAction { @Override public void run(Compute compute, ZoneId zone) { - System.out.printf("Zone info: %s%n", compute.getZone(zone.zone())); + System.out.printf("Zone info: %s%n", compute.getZone(zone.getZone())); } @Override @@ -506,7 +506,7 @@ public String params() { private static class LicenseInfoAction extends ComputeAction { @Override public void run(Compute compute, LicenseId license) { - System.out.printf("License info: %s%n", compute.getLicense(license.license())); + System.out.printf("License info: %s%n", compute.getLicense(license.getLicense())); } @Override @@ -553,7 +553,8 @@ public void run(Compute compute, Void arg) { private static class ListZoneOperationsAction extends ComputeAction { @Override public void run(Compute compute, ZoneId zone) { - Iterator operationIterator = compute.listZoneOperations(zone.zone()).iterateAll(); + Iterator operationIterator = + compute.listZoneOperations(zone.getZone()).iterateAll(); while (operationIterator.hasNext()) { System.out.println(operationIterator.next()); } @@ -588,7 +589,7 @@ private static class ListRegionOperationsAction extends ComputeAction @Override public void run(Compute compute, RegionId region) { Iterator operationIterator = - compute.listRegionOperations(region.region()).iterateAll(); + compute.listRegionOperations(region.getRegion()).iterateAll(); while (operationIterator.hasNext()) { System.out.println(operationIterator.next()); } @@ -776,7 +777,7 @@ private static class ListAddressesAction extends OptionalRegionAction { public void run(Compute compute, RegionId region) { Iterator
addressIterator; if (region != null) { - addressIterator = compute.listRegionAddresses(region.region()).iterateAll(); + addressIterator = compute.listRegionAddresses(region.getRegion()).iterateAll(); } else { addressIterator = compute.listAddresses().iterateAll(); } @@ -841,15 +842,15 @@ public void run(Compute compute, AddressId address) throws InterruptedException } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Address %s was deleted%n", address); } else { System.out.printf("Deletion of address %s failed%n", address); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } } @@ -868,15 +869,15 @@ public void run(Compute compute, AddressId address) throws InterruptedException Operation operation = compute.create(AddressInfo.of(address)); while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Address %s was created%n", address); } else { System.out.printf("Creation of address %s failed%n", address); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } } @@ -926,7 +927,7 @@ public String params() { private static class SnapshotInfoAction extends SnapshotAction { @Override public void run(Compute compute, SnapshotId snapshot) { - System.out.printf("Snapshot info: %s%n", compute.getSnapshot(snapshot.snapshot())); + System.out.printf("Snapshot info: %s%n", compute.getSnapshot(snapshot.getSnapshot())); } } @@ -939,22 +940,22 @@ public void run(Compute compute, SnapshotId snapshot) { private static class DeleteSnapshotAction extends SnapshotAction { @Override public void run(Compute compute, SnapshotId snapshot) throws InterruptedException { - Operation operation = compute.deleteSnapshot(snapshot.snapshot()); + Operation operation = compute.deleteSnapshot(snapshot.getSnapshot()); if (operation == null) { System.out.printf("Snapshot %s does not exist%n", snapshot); return; } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Snapshot %s was deleted%n", snapshot); } else { System.out.printf("Deletion of snapshot %s failed%n", snapshot); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } } @@ -971,15 +972,15 @@ public void run(Compute compute, SnapshotInfo snapshot) throws InterruptedExcept Operation operation = compute.create(snapshot); while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { - System.out.printf("Snapshot %s was created%n", snapshot.snapshotId()); + if (operation.getErrors() == null) { + System.out.printf("Snapshot %s was created%n", snapshot.getSnapshotId()); } else { - System.out.printf("Creation of snapshot %s failed%n", snapshot.snapshotId()); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Creation of snapshot %s failed%n", snapshot.getSnapshotId()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -1070,15 +1071,15 @@ public void run(Compute compute, ImageId image) throws InterruptedException { } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Image %s was deleted%n", image); } else { System.out.printf("Deletion of image %s failed%n", image); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } } @@ -1095,15 +1096,15 @@ public void run(Compute compute, ImageInfo image) throws InterruptedException { Operation operation = compute.create(image); while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { - System.out.printf("Image %s was created%n", image.imageId()); + if (operation.getErrors() == null) { + System.out.printf("Image %s was created%n", image.getImageId()); } else { - System.out.printf("Creation of image %s failed%n", image.imageId()); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Creation of image %s failed%n", image.getImageId()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -1178,15 +1179,15 @@ public void run(Compute compute, DiskId disk) throws InterruptedException { } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Disk %s was deleted%n", disk); } else { System.out.printf("Deletion of disk %s failed%n", disk); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } } @@ -1213,15 +1214,15 @@ public void run(Compute compute, DiskInfo disk) throws InterruptedException { Operation operation = compute.create(disk); while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { - System.out.printf("Disk %s was created%n", disk.diskId()); + if (operation.getErrors() == null) { + System.out.printf("Disk %s was created%n", disk.getDiskId()); } else { - System.out.printf("Creation of disk %s failed%n", disk.diskId()); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Creation of disk %s failed%n", disk.getDiskId()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -1245,13 +1246,13 @@ DiskInfo parse(String... args) throws Exception { DiskConfiguration configuration; if (args.length == 4) { try { - configuration = StandardDiskConfiguration.of(DiskTypeId.of(diskId.zone(), diskType), + configuration = StandardDiskConfiguration.of(DiskTypeId.of(diskId.getZone(), diskType), Integer.parseInt(args[3])); } catch (NumberFormatException ex) { throw new IllegalArgumentException("Error parsing disk size parameter."); } } else if (args.length == 3) { - configuration = StandardDiskConfiguration.of(DiskTypeId.of(diskId.zone(), diskType)); + configuration = StandardDiskConfiguration.of(DiskTypeId.of(diskId.getZone(), diskType)); } else { throw new IllegalArgumentException("Too many arguments."); } @@ -1365,7 +1366,7 @@ public String params() { private static class NetworkInfoAction extends NetworkAction { @Override public void run(Compute compute, NetworkId network) { - System.out.printf("Network info: %s%n", compute.getNetwork(network.network())); + System.out.printf("Network info: %s%n", compute.getNetwork(network.getNetwork())); } } @@ -1378,22 +1379,22 @@ public void run(Compute compute, NetworkId network) { private static class DeleteNetworkAction extends NetworkAction { @Override public void run(Compute compute, NetworkId network) throws InterruptedException { - Operation operation = compute.deleteNetwork(network.network()); + Operation operation = compute.deleteNetwork(network.getNetwork()); if (operation == null) { System.out.printf("Network %s does not exist%n", network); return; } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Network %s was deleted%n", network); } else { System.out.printf("Deletion of network %s failed%n", network); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } } @@ -1404,15 +1405,15 @@ public void run(Compute compute, NetworkInfo network) throws InterruptedExceptio Operation operation = compute.create(network); while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { - System.out.printf("Network %s was created%n", network.networkId()); + if (operation.getErrors() == null) { + System.out.printf("Network %s was created%n", network.getNetworkId()); } else { - System.out.printf("Creation of network %s failed%n", network.networkId()); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Creation of network %s failed%n", network.getNetworkId()); + System.out.printf("Error: %s%n", operation.getErrors()); } } } @@ -1491,7 +1492,7 @@ private static class ListSubnetworksAction extends OptionalRegionAction { public void run(Compute compute, RegionId region) { Iterator subnetworkIterator; if (region != null) { - subnetworkIterator = compute.listSubnetworks(region.region()).iterateAll(); + subnetworkIterator = compute.listSubnetworks(region.getRegion()).iterateAll(); } else { subnetworkIterator = compute.listSubnetworks().iterateAll(); } @@ -1550,15 +1551,15 @@ public void run(Compute compute, SubnetworkId subnetwork) throws InterruptedExce } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Subnetwork %s was deleted%n", subnetwork); } else { System.out.printf("Deletion of subnetwork %s failed%n", subnetwork); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } } @@ -1575,15 +1576,15 @@ public void run(Compute compute, SubnetworkInfo subnetwork) throws InterruptedEx Operation operation = compute.create(subnetwork); while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { - System.out.printf("Subnetwork %s was created%n", subnetwork.subnetworkId()); + if (operation.getErrors() == null) { + System.out.printf("Subnetwork %s was created%n", subnetwork.getSubnetworkId()); } else { - System.out.printf("Creation of subnetwork %s failed%n", subnetwork.subnetworkId()); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Creation of subnetwork %s failed%n", subnetwork.getSubnetworkId()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -1618,7 +1619,7 @@ private static class ListInstancesAction extends OptionalZoneAction { public void run(Compute compute, ZoneId zone) { Iterator instanceIterator; if (zone != null) { - instanceIterator = compute.listInstances(zone.zone()).iterateAll(); + instanceIterator = compute.listInstances(zone.getZone()).iterateAll(); } else { instanceIterator = compute.listInstances().iterateAll(); } @@ -1677,15 +1678,15 @@ public void run(Compute compute, InstanceId instance) throws InterruptedExceptio } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Instance %s was deleted%n", instance); } else { System.out.printf("Deletion of instance %s failed%n", instance); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } } @@ -1702,15 +1703,15 @@ public void run(Compute compute, InstanceInfo instance) throws InterruptedExcept Operation operation = compute.create(instance); while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { - System.out.printf("Instance %s was created%n", instance.instanceId()); + if (operation.getErrors() == null) { + System.out.printf("Instance %s was created%n", instance.getInstanceId()); } else { - System.out.printf("Creation of instance %s failed%n", instance.instanceId()); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Creation of instance %s failed%n", instance.getInstanceId()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -1724,7 +1725,7 @@ InstanceInfo parse(String... args) throws Exception { MachineTypeId machineTypeId = MachineTypeId.of(zone, args[2]); DiskId diskId = DiskId.of(zone, args[3]); AttachedDisk disk = - AttachedDisk.of(PersistentDiskConfiguration.builder(diskId).boot(true).build()); + AttachedDisk.of(PersistentDiskConfiguration.newBuilder(diskId).setBoot(true).build()); NetworkInterface networkInterface = NetworkInterface.of(args[4]); return InstanceInfo.of(instanceId, machineTypeId, disk, networkInterface); } else if (args.length > 5) { @@ -1813,17 +1814,17 @@ public void run(Compute compute, Triple interf } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Access config added to network interface %s of instance %s%n", networkInterface, instance); } else { System.out.printf("Attempt to add access config to network interface %s of instance %s%n", networkInterface, instance); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -1836,10 +1837,10 @@ Triple parse(String... args) throws Exception String accessConfig = args[3]; if (args.length == 4) { return Triple.of(instance, networkInterface, - AccessConfig.builder().name(accessConfig).build()); + AccessConfig.newBuilder().setName(accessConfig).build()); } else if (args.length == 5) { return Triple.of(instance, networkInterface, - AccessConfig.builder().name(accessConfig).natIp(args[4]).build()); + AccessConfig.newBuilder().setName(accessConfig).setNatIp(args[4]).build()); } else { message = "Too many arguments."; } @@ -1877,18 +1878,18 @@ public void run(Compute compute, Triple interfaceAnd } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Access config deleted from network interface %s of instance %s%n", networkInterface, instance); } else { System.out.printf( "Attempt to delete access config from network interface %s of instance %s failed%n", networkInterface, instance); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -1935,15 +1936,15 @@ public void run(Compute compute, Triple instanceAndDevice) } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Disk detached from instance %s%n", instance); } else { System.out.printf("Attempt to detach disk from instance %s failed%n", instance); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -2046,16 +2047,16 @@ public void run(Compute compute, Triple deviceAndAu } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Auto-delete set for device %s of instance %s%n", deviceName, instance); } else { System.out.printf("Attempt to set auto-delete for device %s of instance %s failed%n", deviceName, instance); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -2112,15 +2113,15 @@ public void run(Compute compute, Tuple instanceAndTyp } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Machine type set for instance %s%n", instance); } else { System.out.printf("Attempt to set machine type for instance %s failed%n", instance); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -2166,15 +2167,15 @@ public void run(Compute compute, Tuple> instanceAndTags Operation operation = instance.setTags(tags); while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Tags set for instance %s%n", instanceId); } else { System.out.printf("Attempt to set tags for instance %s failed%n", instanceId); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -2217,15 +2218,15 @@ public void run(Compute compute, Tuple> instance Operation operation = instance.setMetadata(metadata); while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Metadata set for instance %s%n", instanceId); } else { System.out.printf("Attempt to set metadata for instance %s failed%n", instanceId); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -2272,16 +2273,16 @@ public void run(Compute compute, Tuple instanceAn } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Scheduling options set for instance %s%n", instanceId); } else { System.out.printf( "Attempt to set scheduling options for instance %s failed%n", instanceId); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } @@ -2338,15 +2339,15 @@ public void run(Compute compute, InstanceId instance) throws InterruptedExceptio } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Instance %s was reset%n", instance); } else { System.out.printf("Attempt to reset instance %s failed%n", instance); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } } @@ -2367,15 +2368,15 @@ public void run(Compute compute, InstanceId instance) throws InterruptedExceptio } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Instance %s was stopped%n", instance); } else { System.out.printf("Attempt to stop instance %s failed%n", instance); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } } @@ -2396,15 +2397,15 @@ public void run(Compute compute, InstanceId instance) throws InterruptedExceptio } while (!operation.isDone()) { System.out.printf( - "Waiting for operation %s to complete%n", operation.operationId().operation()); + "Waiting for operation %s to complete%n", operation.getOperationId().getOperation()); Thread.sleep(1000L); } operation = operation.reload(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.printf("Instance %s was started%n", instance); } else { System.out.printf("Attempt to start instance %s failed%n", instance); - System.out.printf("Error: %s%n", operation.errors()); + System.out.printf("Error: %s%n", operation.getErrors()); } } } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateAddressDiskAndInstance.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateAddressDiskAndInstance.java index 0a63865904e0..2e0834fa600b 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateAddressDiskAndInstance.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateAddressDiskAndInstance.java @@ -53,7 +53,7 @@ public static void main(String... args) throws InterruptedException, TimeoutExce Operation operation = compute.create(AddressInfo.of(addressId)); // Wait for operation to complete operation = operation.waitFor(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.println("Address " + addressId + " was successfully created"); } else { // inspect operation.errors() @@ -68,7 +68,7 @@ public static void main(String... args) throws InterruptedException, TimeoutExce operation = compute.create(disk); // Wait for operation to complete operation = operation.waitFor(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.println("Disk " + diskId + " was successfully created"); } else { // inspect operation.errors() @@ -80,10 +80,10 @@ public static void main(String... args) throws InterruptedException, TimeoutExce InstanceId instanceId = InstanceId.of("us-central1-a", "test-instance"); NetworkId networkId = NetworkId.of("default"); PersistentDiskConfiguration attachConfiguration = - PersistentDiskConfiguration.builder(diskId).boot(true).build(); + PersistentDiskConfiguration.newBuilder(diskId).setBoot(true).build(); AttachedDisk attachedDisk = AttachedDisk.of("dev0", attachConfiguration); - NetworkInterface networkInterface = NetworkInterface.builder(networkId) - .accessConfigurations(AccessConfig.of(externalIp.address())) + NetworkInterface networkInterface = NetworkInterface.newBuilder(networkId) + .setAccessConfigurations(AccessConfig.of(externalIp.getAddress())) .build(); MachineTypeId machineTypeId = MachineTypeId.of("us-central1-a", "n1-standard-1"); InstanceInfo instance = @@ -91,7 +91,7 @@ public static void main(String... args) throws InterruptedException, TimeoutExce operation = compute.create(instance); // Wait for operation to complete operation = operation.waitFor(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { System.out.println("Instance " + instanceId + " was successfully created"); } else { // inspect operation.errors() diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateInstance.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateInstance.java index 66c10bace269..0d55dfa3e52f 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateInstance.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateInstance.java @@ -46,7 +46,7 @@ public static void main(String... args) throws InterruptedException, TimeoutExce Operation operation = compute.create(InstanceInfo.of(instanceId, machineTypeId, attachedDisk, networkInterface)); operation = operation.waitFor(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { // use instance Instance instance = compute.getInstance(instanceId); } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateSnapshot.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateSnapshot.java index 35d19e38e18e..8c221d6bb5f6 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateSnapshot.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateSnapshot.java @@ -39,7 +39,7 @@ public static void main(String... args) throws InterruptedException, TimeoutExce String snapshotName = "disk-name-snapshot"; Operation operation = disk.createSnapshot(snapshotName); operation = operation.waitFor(); - if (operation.errors() == null) { + if (operation.getErrors() == null) { // use snapshot Snapshot snapshot = compute.getSnapshot(snapshotName); } From bf0fd0c47ea6d3d296f59b15500722232e9e14d7 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Wed, 26 Oct 2016 22:43:30 +0200 Subject: [PATCH 23/32] Rename setters/getters/builders for Translate classes to meet proto conventions (#1337) --- README.md | 4 +-- TESTING.md | 2 +- .../snippets/DetectLanguageAndTranslate.java | 4 +-- .../snippets/ITTranslateSnippets.java | 36 +++++++++---------- google-cloud-translate/README.md | 2 +- .../com/google/cloud/translate/Detection.java | 21 +++++++++++ .../com/google/cloud/translate/Language.java | 16 +++++++++ .../com/google/cloud/translate/Option.java | 4 +-- .../com/google/cloud/translate/Translate.java | 6 ++-- .../google/cloud/translate/TranslateImpl.java | 2 +- .../google/cloud/translate/Translation.java | 17 +++++++++ .../google/cloud/translate/package-info.java | 4 +-- .../testing/RemoteTranslateHelper.java | 10 +++++- .../cloud/translate/testing/package-info.java | 2 +- .../google/cloud/translate/DetectionTest.java | 11 ++++-- .../google/cloud/translate/LanguageTest.java | 14 ++++++-- .../google/cloud/translate/OptionTest.java | 8 ++--- .../cloud/translate/TranslateImplTest.java | 6 ++-- .../google/cloud/translate/TranslateTest.java | 12 +++---- .../cloud/translate/TranslationTest.java | 11 ++++-- .../cloud/translate/it/ITTranslateTest.java | 36 +++++++++---------- 21 files changed, 157 insertions(+), 71 deletions(-) diff --git a/README.md b/README.md index 3bc2219ab2bd..58044d675a8a 100644 --- a/README.md +++ b/README.md @@ -601,14 +601,14 @@ import com.google.cloud.translate.Translation; Translate translate = TranslateOptions.defaultInstance().service(); Detection detection = translate.detect("Hola"); -String detectedLanguage = detection.language(); +String detectedLanguage = detection.getLanguage(); Translation translation = translate.translate( "World", TranslateOption.sourceLanguage("en"), TranslateOption.targetLanguage(detectedLanguage)); -System.out.printf("Hola %s%n", translation.translatedText()); +System.out.printf("Hola %s%n", translation.getTranslatedText()); ``` Troubleshooting diff --git a/TESTING.md b/TESTING.md index b6a3b68082bb..249936c1cf0b 100644 --- a/TESTING.md +++ b/TESTING.md @@ -285,7 +285,7 @@ key. that uses the `RemoteTranslateHelper` to list supported languages. ```java RemoteTranslateHelper translateHelper = RemoteTranslateHelper.create(PROJECT_ID, API_KEY); - Translate translate = translateHelper.options().service(); + Translate translate = translateHelper.getOptions().service(); List languages = translate.listSupportedLanguages(); ``` diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java index 994ff40852fe..e66921e60ace 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java @@ -41,7 +41,7 @@ public static void main(String... args) { // Detect the language of some text Detection detection = translate.detect("Hola"); - String detectedLanguage = detection.language(); + String detectedLanguage = detection.getLanguage(); // Translate some text Translation translation = translate.translate( @@ -49,6 +49,6 @@ public static void main(String... args) { TranslateOption.sourceLanguage("en"), TranslateOption.targetLanguage(detectedLanguage)); - System.out.printf("Hola %s%n", translation.translatedText()); + System.out.printf("Hola %s%n", translation.getTranslatedText()); } } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/translate/snippets/ITTranslateSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/translate/snippets/ITTranslateSnippets.java index 0aaaa2952772..2fe45d2147e9 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/translate/snippets/ITTranslateSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/translate/snippets/ITTranslateSnippets.java @@ -47,7 +47,7 @@ public class ITTranslateSnippets { @BeforeClass public static void beforeClass() { RemoteTranslateHelper helper = RemoteTranslateHelper.create(); - translateSnippets = new TranslateSnippets(helper.options().service()); + translateSnippets = new TranslateSnippets(helper.getOptions().service()); } @Test @@ -55,8 +55,8 @@ public void testListSupportedLanguages() { Set supportedLanguages = new HashSet<>(); List languages = translateSnippets.listSupportedLanguages(); for (Language language : languages) { - supportedLanguages.add(language.code()); - assertNotNull(language.name()); + supportedLanguages.add(language.getCode()); + assertNotNull(language.getName()); } for (String code : LANGUAGES) { assertTrue(supportedLanguages.contains(code)); @@ -68,8 +68,8 @@ public void testListSupportedLanguagesWithTarget() { Set supportedLanguages = new HashSet<>(); List languages = translateSnippets.listSupportedLanguagesWithTarget(); for (Language language : languages) { - supportedLanguages.add(language.code()); - assertNotNull(language.name()); + supportedLanguages.add(language.getCode()); + assertNotNull(language.getName()); } for (String code : LANGUAGES) { assertTrue(supportedLanguages.contains(code)); @@ -80,48 +80,48 @@ public void testListSupportedLanguagesWithTarget() { public void testDetectLanguageOfTexts() { List detections = translateSnippets.detectLanguageOfTexts(); Detection detection = detections.get(0); - assertEquals("en", detection.language()); + assertEquals("en", detection.getLanguage()); detection = detections.get(1); - assertEquals("es", detection.language()); + assertEquals("es", detection.getLanguage()); } @Test public void testDetectLanguageOfTextList() { List detections = translateSnippets.detectLanguageOfTextList(); Detection detection = detections.get(0); - assertEquals("en", detection.language()); + assertEquals("en", detection.getLanguage()); detection = detections.get(1); - assertEquals("es", detection.language()); + assertEquals("es", detection.getLanguage()); } @Test public void testDetectLanguageOfText() { Detection detection = translateSnippets.detectLanguageOfText(); - assertEquals("en", detection.language()); + assertEquals("en", detection.getLanguage()); } @Test public void testTranslateTextList() { List translations = translateSnippets.translateTexts(); Translation translation = translations.get(0); - assertEquals("Hello, World!", translation.translatedText()); - assertEquals("en", translation.sourceLanguage()); + assertEquals("Hello, World!", translation.getTranslatedText()); + assertEquals("en", translation.getSourceLanguage()); translation = translations.get(1); - assertEquals("Hello World!", translation.translatedText()); - assertEquals("es", translation.sourceLanguage()); + assertEquals("Hello World!", translation.getTranslatedText()); + assertEquals("es", translation.getSourceLanguage()); } @Test public void testTranslateText() { Translation translation = translateSnippets.translateText(); - assertEquals("Hello World!", translation.translatedText()); - assertEquals("es", translation.sourceLanguage()); + assertEquals("Hello World!", translation.getTranslatedText()); + assertEquals("es", translation.getSourceLanguage()); } @Test public void testTranslateTextWithOptions() { Translation translation = translateSnippets.translateTextWithOptions(); - assertEquals("Hallo Welt!", translation.translatedText()); - assertEquals("es", translation.sourceLanguage()); + assertEquals("Hallo Welt!", translation.getTranslatedText()); + assertEquals("es", translation.getSourceLanguage()); } } diff --git a/google-cloud-translate/README.md b/google-cloud-translate/README.md index a1d6237049c4..1d51871eb550 100644 --- a/google-cloud-translate/README.md +++ b/google-cloud-translate/README.md @@ -104,7 +104,7 @@ import com.google.cloud.translate.Detection; Then add the following code to detect the text's language: ```java -String detectedLanguage = detection.language(); +String detectedLanguage = detection.getLanguage(); ``` #### Translating text diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/Detection.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/Detection.java index 8b924e5e9173..9157ca2cb9ff 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/Detection.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/Detection.java @@ -47,7 +47,18 @@ private Detection(String language, Float confidence) { * @see * Supported Languages */ + @Deprecated public String language() { + return getLanguage(); + } + + /** + * Returns the code of the detected language. + * + * @see + * Supported Languages + */ + public String getLanguage() { return language; } @@ -56,7 +67,17 @@ public String language() { * higher the confidence level for the language detection. Note that this value is not always * available. */ + @Deprecated public float confidence() { + return getConfidence(); + } + + /** + * Returns an optional confidence value in the interval [0,1]. The closer this value is to 1, the + * higher the confidence level for the language detection. Note that this value is not always + * available. + */ + public float getConfidence() { return confidence; } diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/Language.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/Language.java index 4847b5ebb540..6a8b99b8a07f 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/Language.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/Language.java @@ -54,14 +54,30 @@ private Language(String code, String name) { /** * Returns the code of the language. */ + @Deprecated public String code() { + return getCode(); + } + + /** + * Returns the code of the language. + */ + public String getCode() { return code; } /** * Returns the name of the language. */ + @Deprecated public String name() { + return getName(); + } + + /** + * Returns the name of the language. + */ + public String getName() { return name; } diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/Option.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/Option.java index 7fc05678e39e..7c9ff11d7849 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/Option.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/Option.java @@ -39,11 +39,11 @@ abstract class Option implements Serializable { this.value = value; } - TranslateRpc.Option rpcOption() { + TranslateRpc.Option getRpcOption() { return rpcOption; } - Object value() { + Object getValue() { return value; } diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/Translate.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/Translate.java index 57f3a4a1137d..0bad2b22e1a9 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/Translate.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/Translate.java @@ -85,9 +85,9 @@ public static TranslateOption targetLanguage(String targetLanguage) { /** * Returns the list of languages supported by Google Translate. If - * {@link LanguageListOption#targetLanguage(String)} is provided, {@link Language#name()} values - * are localized according to the provided target language. If no such option is passed, - * {@link Language#name()} values are localized according to + * {@link LanguageListOption#targetLanguage(String)} is provided, {@link Language#getName()} + * values are localized according to the provided target language. If no such option is passed, + * {@link Language#getName()} values are localized according to * {@link TranslateOptions#targetLanguage()}. * *

Example of listing supported languages, localized according to diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateImpl.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateImpl.java index 3d02ac898660..da49b20da3f6 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateImpl.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateImpl.java @@ -126,7 +126,7 @@ public Translation translate(String text, TranslateOption... options) { private Map optionMap(Option... options) { Map optionMap = Maps.newEnumMap(TranslateRpc.Option.class); for (Option option : options) { - Object prev = optionMap.put(option.rpcOption(), option.value()); + Object prev = optionMap.put(option.getRpcOption(), option.getValue()); checkArgument(prev == null, "Duplicate option %s", option); } return optionMap; diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/Translation.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/Translation.java index ebf9db4835a2..fa79635a4a94 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/Translation.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/Translation.java @@ -52,15 +52,32 @@ private Translation(String translatedText, String sourceLanguage) { /** * Returns the translated text. */ + @Deprecated public String translatedText() { return translatedText; } + /** + * Returns the translated text. + */ + public String getTranslatedText() { + return translatedText; + } + /** * Returns the language code of the source text. If no source language was provided this value is * the source language as detected by the Google Translate service. */ + @Deprecated public String sourceLanguage() { + return getSourceLanguage(); + } + + /** + * Returns the language code of the source text. If no source language was provided this value is + * the source language as detected by the Google Translate service. + */ + public String getSourceLanguage() { return sourceLanguage; } diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/package-info.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/package-info.java index 4d417914a89a..cb022c5cb53e 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/package-info.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/package-info.java @@ -28,14 +28,14 @@ * Translate translate = TranslateOptions.defaultInstance().service(); * * Detection detection = translate.detect("Hola"); - * String detectedLanguage = detection.language(); + * String detectedLanguage = detection.getLanguage(); * * Translation translation = translate.translate( * "World", * TranslateOption.sourceLanguage("en"), * TranslateOption.targetLanguage(detectedLanguage)); * - * System.out.printf("Hola %s%n", translation.translatedText()); + * System.out.printf("Hola %s%n", translation.getTranslatedText()); * } */ package com.google.cloud.translate; diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java index a903d08ddb9b..6afe5c58d615 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java @@ -21,7 +21,7 @@ /** * Utility to create a remote translate configuration for testing. Translate options can be obtained - * via the {@link #options()} method. Returned options have custom + * via the {@link #getOptions()} method. Returned options have custom * {@link TranslateOptions#retryParams()}: {@link RetryParams#retryMaxAttempts()} is {@code 10}, * {@link RetryParams#retryMinAttempts()} is {@code 6}, {@link RetryParams#maxRetryDelayMillis()} * is {@code 30000}, {@link RetryParams#totalRetryPeriodMillis()} is {@code 120000} and @@ -40,7 +40,15 @@ private RemoteTranslateHelper(TranslateOptions options) { /** * Returns a {@link TranslateOptions} object to be used for testing. */ + @Deprecated public TranslateOptions options() { + return getOptions(); + } + + /** + * Returns a {@link TranslateOptions} object to be used for testing. + */ + public TranslateOptions getOptions() { return options; } diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/package-info.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/package-info.java index 317b7f71e493..d919feb87335 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/package-info.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/package-info.java @@ -21,7 +21,7 @@ *

Before the test: *

 {@code
  * RemoteTranslateHelper helper = RemoteTranslateHelper.create();
- * Translate translate = helper.options().service();
+ * Translate translate = helper.getOptions().service();
  * } 
* * @see diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/DetectionTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/DetectionTest.java index 9300fae3e85d..5e2b5c4182c7 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/DetectionTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/DetectionTest.java @@ -32,6 +32,13 @@ public class DetectionTest { @Test public void testFromPb() { + assertEquals(LANGUAGE, DETECTION.getLanguage()); + assertEquals(CONFIDENCE, DETECTION.getConfidence(), 0); + compareDetection(DETECTION, Detection.fromPb(DETECTION_PB)); + } + + @Test + public void testFromPbDeprecated() { assertEquals(LANGUAGE, DETECTION.language()); assertEquals(CONFIDENCE, DETECTION.confidence(), 0); compareDetection(DETECTION, Detection.fromPb(DETECTION_PB)); @@ -39,8 +46,8 @@ public void testFromPb() { private void compareDetection(Detection expected, Detection value) { assertEquals(expected, value); - assertEquals(expected.language(), value.language()); - assertEquals(expected.confidence(), value.confidence(), 0); + assertEquals(expected.getLanguage(), value.getLanguage()); + assertEquals(expected.getConfidence(), value.getConfidence(), 0); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/LanguageTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/LanguageTest.java index 4f6849270de0..3eefb2853b37 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/LanguageTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/LanguageTest.java @@ -33,6 +33,16 @@ public class LanguageTest { @Test public void testFromPb() { + assertEquals(CODE, LANGUAGE.getCode()); + assertEquals(NAME, LANGUAGE.getName()); + Language language = Language.fromPb(new LanguagesResource().setLanguage(CODE)); + assertEquals(CODE, language.getCode()); + assertNull(language.getName()); + compareLanguage(LANGUAGE, Language.fromPb(LANGUAGE_PB)); + } + + @Test + public void testFromPbDeprecated() { assertEquals(CODE, LANGUAGE.code()); assertEquals(NAME, LANGUAGE.name()); Language language = Language.fromPb(new LanguagesResource().setLanguage(CODE)); @@ -43,8 +53,8 @@ public void testFromPb() { private void compareLanguage(Language expected, Language value) { assertEquals(expected, value); - assertEquals(expected.name(), value.name()); - assertEquals(expected.code(), value.code()); + assertEquals(expected.getName(), value.getName()); + assertEquals(expected.getCode(), value.getCode()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/OptionTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/OptionTest.java index 152e5c10c455..1151ce9b73cd 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/OptionTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/OptionTest.java @@ -51,11 +51,11 @@ public void testHashCode() { @Test public void testConstructor() { - assertEquals(RPC_OPTION, OPTION.rpcOption()); - assertEquals(VALUE, OPTION.value()); + assertEquals(RPC_OPTION, OPTION.getRpcOption()); + assertEquals(VALUE, OPTION.getValue()); Option option = new Option(RPC_OPTION, null) {}; - assertEquals(RPC_OPTION, option.rpcOption()); - assertNull(option.value()); + assertEquals(RPC_OPTION, option.getRpcOption()); + assertNull(option.getValue()); thrown.expect(NullPointerException.class); new Option(null, VALUE) {}; } diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateImplTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateImplTest.java index 5c98c2c0cd23..f3eb4b04bf92 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateImplTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateImplTest.java @@ -79,7 +79,7 @@ public class TranslateImplTest { private static final LanguageListOption LANGUAGE_LIST_OPTION = LanguageListOption.targetLanguage(TARGET_LANGUAGE); private static final Map LANGUAGE_LIST_OPTIONS = ImmutableMap.of( - TranslateRpc.Option.TARGET_LANGUAGE, LANGUAGE_LIST_OPTION.value()); + TranslateRpc.Option.TARGET_LANGUAGE, LANGUAGE_LIST_OPTION.getValue()); // Translate options private static final TranslateOption TARGET_LANGUAGE_OPTION = @@ -87,8 +87,8 @@ public class TranslateImplTest { private static final TranslateOption SOURCE_LANGUAGE_OPTION = TranslateOption.sourceLanguage("de"); private static final Map TRANSLATE_OPTIONS = ImmutableMap.of( - TranslateRpc.Option.TARGET_LANGUAGE, TARGET_LANGUAGE_OPTION.value(), - TranslateRpc.Option.SOURCE_LANGUAGE, SOURCE_LANGUAGE_OPTION.value()); + TranslateRpc.Option.TARGET_LANGUAGE, TARGET_LANGUAGE_OPTION.getValue(), + TranslateRpc.Option.SOURCE_LANGUAGE, SOURCE_LANGUAGE_OPTION.getValue()); private TranslateOptions options; private TranslateRpcFactory rpcFactoryMock; diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateTest.java index 899ee32a7109..0c87e1e32e31 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateTest.java @@ -32,19 +32,19 @@ public class TranslateTest { public void testListOptions() { // target language LanguageListOption listOption = LanguageListOption.targetLanguage(LANGUAGE); - assertEquals(TranslateRpc.Option.TARGET_LANGUAGE, listOption.rpcOption()); - assertEquals(LANGUAGE, listOption.value()); + assertEquals(TranslateRpc.Option.TARGET_LANGUAGE, listOption.getRpcOption()); + assertEquals(LANGUAGE, listOption.getValue()); } @Test public void testTranslateOptions() { // target language TranslateOption translateOption = TranslateOption.targetLanguage(LANGUAGE); - assertEquals(TranslateRpc.Option.TARGET_LANGUAGE, translateOption.rpcOption()); - assertEquals(LANGUAGE, translateOption.value()); + assertEquals(TranslateRpc.Option.TARGET_LANGUAGE, translateOption.getRpcOption()); + assertEquals(LANGUAGE, translateOption.getValue()); // source language translateOption = TranslateOption.sourceLanguage(LANGUAGE); - assertEquals(TranslateRpc.Option.SOURCE_LANGUAGE, translateOption.rpcOption()); - assertEquals(LANGUAGE, translateOption.value()); + assertEquals(TranslateRpc.Option.SOURCE_LANGUAGE, translateOption.getRpcOption()); + assertEquals(LANGUAGE, translateOption.getValue()); } } diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslationTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslationTest.java index efb819f81362..1e70aaa40044 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslationTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslationTest.java @@ -33,6 +33,13 @@ public class TranslationTest { @Test public void testFromPb() { + assertEquals(TRANSLATED_TEXT, TRANSLATION.getTranslatedText()); + assertEquals(SOURCE_LANGUAGE, TRANSLATION.getSourceLanguage()); + compareTranslation(TRANSLATION, Translation.fromPb(TRANSLATION_PB)); + } + + @Test + public void testFromPbDeprecated() { assertEquals(TRANSLATED_TEXT, TRANSLATION.translatedText()); assertEquals(SOURCE_LANGUAGE, TRANSLATION.sourceLanguage()); compareTranslation(TRANSLATION, Translation.fromPb(TRANSLATION_PB)); @@ -40,8 +47,8 @@ public void testFromPb() { private void compareTranslation(Translation expected, Translation value) { assertEquals(expected, value); - assertEquals(expected.translatedText(), value.translatedText()); - assertEquals(expected.sourceLanguage(), value.sourceLanguage()); + assertEquals(expected.getTranslatedText(), value.getTranslatedText()); + assertEquals(expected.getSourceLanguage(), value.getSourceLanguage()); assertEquals(expected.hashCode(), value.hashCode()); assertEquals(expected.toString(), value.toString()); } diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/it/ITTranslateTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/it/ITTranslateTest.java index c92c09b5ac14..78e7fd11793e 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/it/ITTranslateTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/it/ITTranslateTest.java @@ -37,7 +37,7 @@ public class ITTranslateTest { - private static final Translate TRANSLATE = RemoteTranslateHelper.create().options().service(); + private static final Translate TRANSLATE = RemoteTranslateHelper.create().getOptions().service(); private static final String[] LANGUAGES = {"af", "sq", "ar", "hy", "az", "eu", "be", "bn", "bs", "bg", "ca", "ceb", "ny", "zh-TW", "hr", "cs", "da", "nl", "en", "eo", "et", "tl", "fi", "fr", "gl", "ka", "de", "el", "gu", "ht", "ha", "iw", "hi", "hmn", "hu", "is", "ig", "id", "ga", @@ -51,8 +51,8 @@ public void testListSupportedLanguages() { Set supportedLanguages = new HashSet<>(); List languages = TRANSLATE.listSupportedLanguages(); for (Language language : languages) { - supportedLanguages.add(language.code()); - assertNotNull(language.name()); + supportedLanguages.add(language.getCode()); + assertNotNull(language.getName()); } for (String code : LANGUAGES) { assertTrue(supportedLanguages.contains(code)); @@ -65,8 +65,8 @@ public void testListSupportedLanguagesWithOptions() { List languages = TRANSLATE.listSupportedLanguages( LanguageListOption.targetLanguage("es")); for (Language language : languages) { - supportedLanguages.add(language.code()); - assertNotNull(language.name()); + supportedLanguages.add(language.getCode()); + assertNotNull(language.getName()); } for (String code : LANGUAGES) { assertTrue(supportedLanguages.contains(code)); @@ -77,49 +77,49 @@ public void testListSupportedLanguagesWithOptions() { public void testDetectLanguageOfTexts() { List detections = TRANSLATE.detect("Hello", "Hallo"); Detection detection = detections.get(0); - assertEquals("en", detection.language()); + assertEquals("en", detection.getLanguage()); detection = detections.get(1); - assertEquals("de", detection.language()); + assertEquals("de", detection.getLanguage()); } @Test public void testDetectLanguageOfTextList() { List detections = TRANSLATE.detect(ImmutableList.of("Hello", "Hallo")); Detection detection = detections.get(0); - assertEquals("en", detection.language()); + assertEquals("en", detection.getLanguage()); detection = detections.get(1); - assertEquals("de", detection.language()); + assertEquals("de", detection.getLanguage()); } @Test public void testDetectLanguageOfText() { Detection detection = TRANSLATE.detect("Hello"); - assertEquals("en", detection.language()); + assertEquals("en", detection.getLanguage()); } @Test public void testTranslateTextList() { List translations = TRANSLATE.translate(ImmutableList.of("Hola", "Hallo")); Translation translation = translations.get(0); - assertEquals("Hello", translation.translatedText()); - assertEquals("es", translation.sourceLanguage()); + assertEquals("Hello", translation.getTranslatedText()); + assertEquals("es", translation.getSourceLanguage()); translation = translations.get(1); - assertEquals("Hello", translation.translatedText()); - assertEquals("de", translation.sourceLanguage()); + assertEquals("Hello", translation.getTranslatedText()); + assertEquals("de", translation.getSourceLanguage()); } @Test public void testTranslateText() { Translation translation = TRANSLATE.translate("Hola"); - assertEquals("Hello", translation.translatedText()); - assertEquals("es", translation.sourceLanguage()); + assertEquals("Hello", translation.getTranslatedText()); + assertEquals("es", translation.getSourceLanguage()); } @Test public void testTranslateTextWithOptions() { Translation translation = TRANSLATE.translate("Hola", TranslateOption.sourceLanguage("es"), TranslateOption.targetLanguage("de")); - assertEquals("Hallo", translation.translatedText()); - assertEquals("es", translation.sourceLanguage()); + assertEquals("Hallo", translation.getTranslatedText()); + assertEquals("es", translation.getSourceLanguage()); } } From f76f1c9916ef87c9fb1f213d28bd3f771d379bf1 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Thu, 27 Oct 2016 09:57:36 +0200 Subject: [PATCH 24/32] Fix listMonitoredResourceDescriptors tests flakeyness (#1340) --- .../logging/snippets/ITLoggingSnippets.java | 26 ++++++------------ .../google/cloud/logging/BaseSystemTest.java | 27 ++++++------------- 2 files changed, 16 insertions(+), 37 deletions(-) diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITLoggingSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITLoggingSnippets.java index b8737784ee06..3aeede060f55 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITLoggingSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITLoggingSnippets.java @@ -25,7 +25,6 @@ import com.google.cloud.logging.Metric; import com.google.cloud.logging.Sink; import com.google.cloud.logging.testing.RemoteLoggingHelper; -import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterators; import com.google.common.collect.Sets; @@ -36,7 +35,6 @@ import org.junit.rules.ExpectedException; import org.junit.rules.Timeout; -import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ExecutionException; @@ -44,12 +42,6 @@ public class ITLoggingSnippets { private static final String DATASET = "dataset"; - private static final Set DESCRIPTOR_TYPES = ImmutableSet.of("gce_instance", "gae_app", - "cloudsql_database", "api", "gcs_bucket", "global", "dataflow_step", "build", - "app_script_function", "dataproc_cluster", "ml_job", "bigquery_resource", "container", - "gke_cluster", "cloud_debugger_resource", "http_load_balancer", "aws_ec2_instance", - "client_auth_config_brand", "client_auth_config_client", "logging_log", "logging_sink", - "metric", "project", "testservice_matrix", "service_account", "deployment"); private static Logging logging; private static LoggingSnippets loggingSnippets; @@ -134,21 +126,19 @@ public void testMetric() throws ExecutionException, InterruptedException { public void testMonitoredResourceDescriptor() throws ExecutionException, InterruptedException { Iterator iterator = loggingSnippets.listMonitoredResourceDescriptors().iterateAll(); - Set descriptorTypes = new HashSet<>(); + int count = 0; while (iterator.hasNext()) { - descriptorTypes.add(iterator.next().type()); - } - for (String type : DESCRIPTOR_TYPES) { - assertTrue(descriptorTypes.contains(type)); + assertNotNull(iterator.next().getType()); + count += 1; } + assertTrue(count > 0); iterator = loggingSnippets.listMonitoredResourceDescriptorsAsync().iterateAll(); - descriptorTypes.clear(); + count = 0; while (iterator.hasNext()) { - descriptorTypes.add(iterator.next().type()); - } - for (String type : DESCRIPTOR_TYPES) { - assertTrue(descriptorTypes.contains(type)); + assertNotNull(iterator.next().getType()); + count += 1; } + assertTrue(count > 0); } @Test diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java index 4e5d42ef9281..c27e02183042 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java @@ -36,7 +36,6 @@ import com.google.cloud.logging.SinkInfo.Destination.DatasetDestination; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterators; import com.google.common.collect.Sets; import com.google.protobuf.Any; @@ -47,7 +46,6 @@ import org.junit.rules.ExpectedException; import org.junit.rules.Timeout; -import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.ExecutionException; @@ -60,13 +58,6 @@ */ public abstract class BaseSystemTest { - private static final Set DESCRIPTOR_TYPES = ImmutableSet.of("gce_instance", "gae_app", - "cloudsql_database", "api", "gcs_bucket", "global", "dataflow_step", "build", - "app_script_function", "dataproc_cluster", "ml_job", "bigquery_resource", "container", - "gke_cluster", "cloud_debugger_resource", "http_load_balancer", "aws_ec2_instance", - "client_auth_config_brand", "client_auth_config_client", "logging_log", "logging_sink", - "metric", "project", "testservice_matrix", "service_account", "deployment"); - @Rule public ExpectedException thrown = ExpectedException.none(); @@ -214,13 +205,12 @@ public void testListSinksAsync() throws ExecutionException, InterruptedException public void testListMonitoredResourceDescriptors() { Iterator iterator = logging().listMonitoredResourceDescriptors(Logging.ListOption.pageSize(1)).iterateAll(); - Set descriptorTypes = new HashSet<>(); + int count = 0; while (iterator.hasNext()) { - descriptorTypes.add(iterator.next().getType()); - } - for (String type : DESCRIPTOR_TYPES) { - assertTrue(descriptorTypes.contains(type)); + assertNotNull(iterator.next().getType()); + count += 1; } + assertTrue(count > 0); } @Test @@ -228,13 +218,12 @@ public void testListMonitoredResourceDescriptorsAsync() throws ExecutionException, InterruptedException { Iterator iterator = logging() .listMonitoredResourceDescriptorsAsync(Logging.ListOption.pageSize(1)).get().iterateAll(); - Set descriptorTypes = new HashSet<>(); + int count = 0; while (iterator.hasNext()) { - descriptorTypes.add(iterator.next().getType()); - } - for (String type : DESCRIPTOR_TYPES) { - assertTrue(descriptorTypes.contains(type)); + assertNotNull(iterator.next().getType()); + count += 1; } + assertTrue(count > 0); } @Test From 0221851bde459dc58ec0dcaa98d31778f76f5882 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Fri, 28 Oct 2016 10:25:58 +0200 Subject: [PATCH 25/32] Fix links to examples in main README and landing page (#1342) --- README.md | 7 ++++--- src/site/resources/index.html | 11 +++++++---- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 58044d675a8a..b51d76f147fd 100644 --- a/README.md +++ b/README.md @@ -65,16 +65,17 @@ Example Applications - Read more about using this application on the [`DatastoreExample` docs page](https://googlecloudplatform.github.io/google-cloud-java/apidocs/?com/google/cloud/examples/datastore/DatastoreExample.html). - [`DnsExample`](./google-cloud-examples/src/main/java/com/google/cloud/examples/dns/DnsExample.java) - A simple command line interface for Cloud DNS - Read more about using this application on the [`DnsExample` docs page](https://googlecloudplatform.github.io/google-cloud-java/apidocs/?com/google/cloud/examples/dns/DnsExample.html). -- [`Flexible Environment/Datastore example`](https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/managed_vms/datastore) - A simple app that uses Cloud Datastore to list the last 10 IP addresses that visited your site. +- [`Flexible Environment/Datastore example`](https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/flexible/datastore) - A simple app that uses Cloud Datastore to list the last 10 IP addresses that visited your site. - Read about how to run the application [here](https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/managed_vms/README.md). -- [`Flexible Environment/Storage example`](https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/managed_vms/cloudstorage) - An app that uploads files to a public Cloud Storage bucket on the App Engine Flexible Environment runtime. +- [`Flexible Environment/Storage example`](https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/flexible/cloudstorage) - An app that uploads files to a public Cloud Storage bucket on the App Engine Flexible Environment runtime. +- [`GuestBook`](https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/appengine/guestbook-cloud-datastore) - An App Engine Standard guestbook that uses Cloud Datastore. - [`LoggingExample`](./google-cloud-examples/src/main/java/com/google/cloud/examples/logging/LoggingExample.java) - A simple command line interface providing some of Stackdriver Logging's functionality - Read more about using this application on the [`LoggingExample` docs page](https://googlecloudplatform.github.io/google-cloud-java/apidocs/?com/google/cloud/examples/logging/LoggingExample.html). - [`PubSubExample`](./google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/PubSubExample.java) - A simple command line interface providing some of Cloud Pub/Sub's functionality - Read more about using this application on the [`PubSubExample` docs page](https://googlecloudplatform.github.io/google-cloud-java/apidocs/?com/google/cloud/examples/pubsub/PubSubExample.html). - [`ResourceManagerExample`](./google-cloud-examples/src/main/java/com/google/cloud/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](https://googlecloudplatform.github.io/google-cloud-java/apidocs/?com/google/cloud/examples/resourcemanager/ResourceManagerExample.html). -- [`SparkDemo`](https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/managed_vms/sparkjava) - An example of using `google-cloud-datastore` from within the SparkJava and App Engine Flexible Environment frameworks. +- [`SparkDemo`](https://github.com/GoogleCloudPlatform/java-docs-samples/blob/master/flexible/sparkjava) - An example of using `google-cloud-datastore` from within the SparkJava and App Engine Flexible Environment frameworks. - Read about how it works on the example's [README page](https://github.com/GoogleCloudPlatform/java-docs-samples/tree/master/managed_vms/sparkjava#how-does-it-work). - [`StorageExample`](./google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java) - A simple command line interface providing some of Cloud Storage's functionality - Read more about using this application on the [`StorageExample` docs page](https://googlecloudplatform.github.io/google-cloud-java/apidocs/?com/google/cloud/examples/storage/StorageExample.html). diff --git a/src/site/resources/index.html b/src/site/resources/index.html index 848d6ee777e6..e1475a02293a 100644 --- a/src/site/resources/index.html +++ b/src/site/resources/index.html @@ -201,16 +201,19 @@

Examples

  • - Flexible Environment/Datastore example - A simple app that uses Cloud Datastore to list the last 10 IP addresses that visited your site. Read about how to run the application here. + Flexible Environment/Datastore example - A simple app that uses Cloud Datastore to list the last 10 IP addresses that visited your site. Read about how to run the application here.
  • - Flexible Environment/Storage example - An app that uploads files to a public Cloud Storage bucket on the App Engine Flexible Environment runtime. + Flexible Environment/Storage example - An app that uploads files to a public Cloud Storage bucket on the App Engine Flexible Environment runtime.
  • - SparkJava demo - Uses google-cloud with App Engine Flexible Environment, Datastore, and SparkJava. + GuestBook - An App Engine Standard guestbook that uses Cloud Datastore.
  • - TaskList - An command line app that manages a to-do list using Cloud Datastore. + SparkJava demo - Uses google-cloud with App Engine Flexible Environment, Datastore, and SparkJava. +
  • +
  • + TaskList - A command line app that manages a to-do list using Cloud Datastore.
  • From 201eda8cc7bbc7988642e5c6671f115956532b1b Mon Sep 17 00:00:00 2001 From: Shin Fan Date: Fri, 28 Oct 2016 06:48:24 -0700 Subject: [PATCH 26/32] Update spi classes with GAX 0.0.21 (#1326) --- google-cloud-core/pom.xml | 2 +- .../com/google/cloud/GrpcServiceOptions.java | 6 +- .../spi/v1beta1/ErrorGroupServiceApi.java | 18 +- .../v1beta1/ErrorGroupServiceSettings.java | 44 +-- .../spi/v1beta1/ErrorStatsServiceApi.java | 76 +++-- .../v1beta1/ErrorStatsServiceSettings.java | 125 +++++--- .../spi/v1beta1/PagedResponseWrappers.java | 61 ++++ .../spi/v1beta1/ReportErrorsServiceApi.java | 12 +- .../v1beta1/ReportErrorsServiceSettings.java | 42 +-- .../spi/v1beta1/package-info.java | 2 +- .../spi/v1beta1/ErrorStatsServiceTest.java | 11 +- .../spi/v1beta1/LanguageServiceApi.java | 24 +- .../spi/v1beta1/LanguageServiceSettings.java | 44 +-- .../spi/v1beta1/PagedResponseWrappers.java | 24 ++ .../language/spi/v1beta1/package-info.java | 2 +- google-cloud-logging/pom.xml | 2 +- .../cloud/logging/spi/DefaultLoggingRpc.java | 6 +- .../logging/spi/v2/ConfigServiceV2Api.java | 90 +++--- .../spi/v2/ConfigServiceV2Settings.java | 85 ++++-- .../logging/spi/v2/LoggingServiceV2Api.java | 120 ++++---- .../spi/v2/LoggingServiceV2Settings.java | 136 ++++++--- .../logging/spi/v2/MetricsServiceV2Api.java | 58 ++-- .../spi/v2/MetricsServiceV2Settings.java | 91 +++--- .../logging/spi/v2/PagedResponseWrappers.java | 97 ++++++ .../cloud/logging/spi/v2/package-info.java | 2 +- .../logging/spi/v2/ConfigServiceV2Test.java | 30 +- .../logging/spi/v2/LoggingServiceV2Test.java | 6 +- .../logging/spi/v2/MetricsServiceV2Test.java | 6 +- .../spi/v3/AgentTranslationServiceApi.java | 283 ------------------ .../v3/AgentTranslationServiceSettings.java | 270 ----------------- .../monitoring/spi/v3/GroupServiceApi.java | 189 ++++-------- .../spi/v3/GroupServiceSettings.java | 125 +++++--- .../monitoring/spi/v3/MetricServiceApi.java | 274 ++++++++--------- .../spi/v3/MetricServiceSettings.java | 181 +++++++---- .../spi/v3/PagedResponseWrappers.java | 117 ++++++++ .../cloud/monitoring/spi/v3/package-info.java | 22 +- .../spi/v3/AgentTranslationServiceTest.java | 101 ------- .../monitoring/spi/v3/GroupServiceTest.java | 25 +- .../monitoring/spi/v3/MetricServiceTest.java | 71 +++-- .../spi/v3/MockAgentTranslationService.java | 49 --- .../v3/MockAgentTranslationServiceImpl.java | 59 ---- .../cloud/pubsub/spi/DefaultPubSubRpc.java | 8 +- .../pubsub/spi/v1/PagedResponseWrappers.java | 77 +++++ .../cloud/pubsub/spi/v1/PublisherApi.java | 143 +++++---- .../pubsub/spi/v1/PublisherSettings.java | 131 +++++--- .../cloud/pubsub/spi/v1/SubscriberApi.java | 131 ++++---- .../pubsub/spi/v1/SubscriberSettings.java | 93 +++--- .../cloud/pubsub/spi/v1/package-info.java | 2 +- .../cloud/pubsub/spi/v1/PublisherTest.java | 11 +- .../cloud/pubsub/spi/v1/SubscriberTest.java | 6 +- .../spi/v1beta1/PagedResponseWrappers.java | 24 ++ .../cloud/speech/spi/v1beta1/SpeechApi.java | 64 +++- .../speech/spi/v1beta1/SpeechSettings.java | 71 +++-- .../speech/spi/v1beta1/package-info.java | 2 +- .../speech/spi/v1beta1/MockSpeechImpl.java | 23 +- .../cloud/speech/spi/v1beta1/SpeechTest.java | 32 ++ .../trace/spi/v1/PagedResponseWrappers.java | 44 +++ .../cloud/trace/spi/v1/TraceServiceApi.java | 58 ++-- .../trace/spi/v1/TraceServiceSettings.java | 87 ++++-- .../cloud/trace/spi/v1/package-info.java | 2 +- .../cloud/trace/spi/v1/TraceServiceTest.java | 6 +- .../vision/spi/v1/ImageAnnotatorApi.java | 12 +- .../vision/spi/v1/ImageAnnotatorSettings.java | 44 +-- .../vision/spi/v1/PagedResponseWrappers.java | 24 ++ .../cloud/vision/spi/v1/package-info.java | 2 +- 65 files changed, 2083 insertions(+), 2002 deletions(-) create mode 100644 google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/PagedResponseWrappers.java create mode 100644 google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/PagedResponseWrappers.java create mode 100644 google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/PagedResponseWrappers.java delete mode 100644 google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceApi.java delete mode 100644 google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceSettings.java create mode 100644 google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/PagedResponseWrappers.java delete mode 100644 google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceTest.java delete mode 100644 google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockAgentTranslationService.java delete mode 100644 google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockAgentTranslationServiceImpl.java create mode 100644 google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PagedResponseWrappers.java create mode 100644 google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/PagedResponseWrappers.java create mode 100644 google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/PagedResponseWrappers.java create mode 100644 google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/PagedResponseWrappers.java diff --git a/google-cloud-core/pom.xml b/google-cloud-core/pom.xml index e3fb52ed2ef8..1ea4eb6cceb8 100644 --- a/google-cloud-core/pom.xml +++ b/google-cloud-core/pom.xml @@ -106,7 +106,7 @@ com.google.api gax - 0.0.18 + 0.0.21 com.google.api.grpc diff --git a/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java b/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java index 330a3dff2b15..a4991ae312d1 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java +++ b/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java @@ -20,7 +20,7 @@ import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.spi.ServiceRpcFactory; import com.google.common.annotations.VisibleForTesting; @@ -226,7 +226,7 @@ protected ExecutorFactory executorFactory() { /** * Returns a builder for API call settings. */ - protected ApiCallSettings.Builder apiCallSettings() { + protected UnaryCallSettings.Builder apiCallSettings() { // todo(mziccard): specify timeout these settings: // retryParams().retryMaxAttempts(), retryParams().retryMinAttempts() final RetrySettings.Builder builder = RetrySettings.newBuilder() @@ -237,7 +237,7 @@ protected ApiCallSettings.Builder apiCallSettings() { .setInitialRetryDelay(Duration.millis(retryParams().initialRetryDelayMillis())) .setRetryDelayMultiplier(retryParams().retryDelayBackoffFactor()) .setMaxRetryDelay(Duration.millis(retryParams().maxRetryDelayMillis())); - return ApiCallSettings.newBuilder().setRetrySettingsBuilder(builder); + return UnaryCallSettings.newBuilder().setRetrySettingsBuilder(builder); } /** diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceApi.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceApi.java index fecd24c11af0..945e0fc6b2be 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceApi.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceApi.java @@ -13,7 +13,7 @@ */ package com.google.cloud.errorreporting.spi.v1beta1; -import com.google.api.gax.grpc.ApiCallable; +import com.google.api.gax.grpc.UnaryCallable; import com.google.api.gax.protobuf.PathTemplate; import com.google.devtools.clouderrorreporting.v1beta1.ErrorGroup; import com.google.devtools.clouderrorreporting.v1beta1.GetGroupRequest; @@ -54,8 +54,8 @@ *
  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -83,8 +83,8 @@ public class ErrorGroupServiceApi implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable getGroupCallable; - private final ApiCallable updateGroupCallable; + private final UnaryCallable getGroupCallable; + private final UnaryCallable updateGroupCallable; private static final PathTemplate GROUP_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}/groups/{group}"); @@ -130,9 +130,9 @@ protected ErrorGroupServiceApi(ErrorGroupServiceSettings settings) throws IOExce this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.getGroupCallable = - ApiCallable.create(settings.getGroupSettings(), this.channel, this.executor); + UnaryCallable.create(settings.getGroupSettings(), this.channel, this.executor); this.updateGroupCallable = - ApiCallable.create(settings.updateGroupSettings(), this.channel, this.executor); + UnaryCallable.create(settings.updateGroupSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { closeables.add( @@ -226,7 +226,7 @@ private final ErrorGroup getGroup(GetGroupRequest request) { * } * */ - public final ApiCallable getGroupCallable() { + public final UnaryCallable getGroupCallable() { return getGroupCallable; } @@ -292,7 +292,7 @@ private final ErrorGroup updateGroup(UpdateGroupRequest request) { * } * */ - public final ApiCallable updateGroupCallable() { + public final UnaryCallable updateGroupCallable() { return updateGroupCallable; } diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceSettings.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceSettings.java index 4dc8bbeae7f1..653ea1709602 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceSettings.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceSettings.java @@ -15,9 +15,9 @@ import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; import com.google.auth.Credentials; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -74,14 +74,6 @@ public class ErrorGroupServiceSettings extends ServiceApiSettings { private static final ImmutableList DEFAULT_SERVICE_SCOPES = ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - private final SimpleCallSettings getGroupSettings; private final SimpleCallSettings updateGroupSettings; @@ -140,7 +132,7 @@ private ErrorGroupServiceSettings(Builder settingsBuilder) throws IOException { /** Builder for ErrorGroupServiceSettings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; private final SimpleCallSettings.Builder getGroupSettings; private final SimpleCallSettings.Builder updateGroupSettings; @@ -177,15 +169,15 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); getGroupSettings = SimpleCallSettings.newBuilder(ErrorGroupServiceGrpc.METHOD_GET_GROUP); updateGroupSettings = SimpleCallSettings.newBuilder(ErrorGroupServiceGrpc.METHOD_UPDATE_GROUP); - methodSettingsBuilders = - ImmutableList.of(getGroupSettings, updateGroupSettings); + unaryMethodSettingsBuilders = + ImmutableList.of(getGroupSettings, updateGroupSettings); } private static Builder createDefault() { @@ -210,13 +202,20 @@ private Builder(ErrorGroupServiceSettings settings) { getGroupSettings = settings.getGroupSettings.toBuilder(); updateGroupSettings = settings.updateGroupSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of(getGroupSettings, updateGroupSettings); + unaryMethodSettingsBuilders = + ImmutableList.of(getGroupSettings, updateGroupSettings); + } + + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); } @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -262,11 +261,14 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceApi.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceApi.java index f333c555e500..589951fd7189 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceApi.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceApi.java @@ -13,13 +13,13 @@ */ package com.google.cloud.errorreporting.spi.v1beta1; -import com.google.api.gax.core.PagedListResponse; -import com.google.api.gax.grpc.ApiCallable; +import static com.google.cloud.errorreporting.spi.v1beta1.PagedResponseWrappers.ListEventsPagedResponse; +import static com.google.cloud.errorreporting.spi.v1beta1.PagedResponseWrappers.ListGroupStatsPagedResponse; + +import com.google.api.gax.grpc.UnaryCallable; import com.google.api.gax.protobuf.PathTemplate; import com.google.devtools.clouderrorreporting.v1beta1.DeleteEventsRequest; import com.google.devtools.clouderrorreporting.v1beta1.DeleteEventsResponse; -import com.google.devtools.clouderrorreporting.v1beta1.ErrorEvent; -import com.google.devtools.clouderrorreporting.v1beta1.ErrorGroupStats; import com.google.devtools.clouderrorreporting.v1beta1.ListEventsRequest; import com.google.devtools.clouderrorreporting.v1beta1.ListEventsResponse; import com.google.devtools.clouderrorreporting.v1beta1.ListGroupStatsRequest; @@ -62,8 +62,8 @@ *

  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -91,16 +91,12 @@ public class ErrorStatsServiceApi implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable listGroupStatsCallable; - private final ApiCallable< - ListGroupStatsRequest, - PagedListResponse> + private final UnaryCallable listGroupStatsCallable; + private final UnaryCallable listGroupStatsPagedCallable; - private final ApiCallable listEventsCallable; - private final ApiCallable< - ListEventsRequest, PagedListResponse> - listEventsPagedCallable; - private final ApiCallable deleteEventsCallable; + private final UnaryCallable listEventsCallable; + private final UnaryCallable listEventsPagedCallable; + private final UnaryCallable deleteEventsCallable; private static final PathTemplate PROJECT_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}"); @@ -139,16 +135,17 @@ protected ErrorStatsServiceApi(ErrorStatsServiceSettings settings) throws IOExce this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.listGroupStatsCallable = - ApiCallable.create(settings.listGroupStatsSettings(), this.channel, this.executor); + UnaryCallable.create(settings.listGroupStatsSettings(), this.channel, this.executor); this.listGroupStatsPagedCallable = - ApiCallable.createPagedVariant( + UnaryCallable.createPagedVariant( settings.listGroupStatsSettings(), this.channel, this.executor); this.listEventsCallable = - ApiCallable.create(settings.listEventsSettings(), this.channel, this.executor); + UnaryCallable.create(settings.listEventsSettings(), this.channel, this.executor); this.listEventsPagedCallable = - ApiCallable.createPagedVariant(settings.listEventsSettings(), this.channel, this.executor); + UnaryCallable.createPagedVariant( + settings.listEventsSettings(), this.channel, this.executor); this.deleteEventsCallable = - ApiCallable.create(settings.deleteEventsSettings(), this.channel, this.executor); + UnaryCallable.create(settings.deleteEventsSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { closeables.add( @@ -195,13 +192,14 @@ public final ErrorStatsServiceSettings getSettings() { * href="https://support.google.com/cloud/answer/6158840">Google Cloud Platform project * ID</a>. *

    Example: <code>projects/my-project-123</code>. - * @param timeRange [Required] List data for the given time range. The service is tuned for - * retrieving data up to (approximately) 'now'. Retrieving data for arbitrary time periods in - * the past can result in higher response times or in returning incomplete results. + * @param timeRange [Required] List data for the given time range. Only + * <code>ErrorGroupStats</code> with a non-zero count in the given time range are + * returned, unless the request contains an explicit group_id list. If a group_id list is + * given, also <code>ErrorGroupStats</code> with zero occurrences are returned. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse - listGroupStats(String projectName, QueryTimeRange timeRange) { + public final ListGroupStatsPagedResponse listGroupStats( + String projectName, QueryTimeRange timeRange) { PROJECT_PATH_TEMPLATE.validate(projectName, "listGroupStats"); ListGroupStatsRequest request = ListGroupStatsRequest.newBuilder() @@ -234,8 +232,7 @@ public final ErrorStatsServiceSettings getSettings() { * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse - listGroupStats(ListGroupStatsRequest request) { + public final ListGroupStatsPagedResponse listGroupStats(ListGroupStatsRequest request) { return listGroupStatsPagedCallable().call(request); } @@ -253,7 +250,7 @@ public final ErrorStatsServiceSettings getSettings() { * .setProjectName(formattedProjectName) * .setTimeRange(timeRange) * .build(); - * ListenableFuture<PagedListResponse<ListGroupStatsRequest,ListGroupStatsResponse,ErrorGroupStats>> future = errorStatsServiceApi.listGroupStatsPagedCallable().futureCall(request); + * ListenableFuture<ListGroupStatsPagedResponse> future = errorStatsServiceApi.listGroupStatsPagedCallable().futureCall(request); * // Do something * for (ErrorGroupStats element : future.get().iterateAllElements()) { * // doThingsWith(element); @@ -261,9 +258,7 @@ public final ErrorStatsServiceSettings getSettings() { * } * */ - public final ApiCallable< - ListGroupStatsRequest, - PagedListResponse> + public final UnaryCallable listGroupStatsPagedCallable() { return listGroupStatsPagedCallable; } @@ -297,7 +292,8 @@ public final ErrorStatsServiceSettings getSettings() { * } * */ - public final ApiCallable listGroupStatsCallable() { + public final UnaryCallable + listGroupStatsCallable() { return listGroupStatsCallable; } @@ -323,8 +319,7 @@ public final ApiCallable listGrou * @param groupId [Required] The group for which events shall be returned. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse listEvents( - String projectName, String groupId) { + public final ListEventsPagedResponse listEvents(String projectName, String groupId) { PROJECT_PATH_TEMPLATE.validate(projectName, "listEvents"); ListEventsRequest request = ListEventsRequest.newBuilder().setProjectName(projectName).setGroupId(groupId).build(); @@ -354,8 +349,7 @@ public final PagedListResponse listEvents( - ListEventsRequest request) { + public final ListEventsPagedResponse listEvents(ListEventsRequest request) { return listEventsPagedCallable().call(request); } @@ -373,7 +367,7 @@ public final PagedListResponse */ - public final ApiCallable< - ListEventsRequest, PagedListResponse> - listEventsPagedCallable() { + public final UnaryCallable listEventsPagedCallable() { return listEventsPagedCallable; } @@ -416,7 +408,7 @@ public final PagedListResponse */ - public final ApiCallable listEventsCallable() { + public final UnaryCallable listEventsCallable() { return listEventsCallable; } @@ -486,7 +478,7 @@ private final DeleteEventsResponse deleteEvents(DeleteEventsRequest request) { * } * */ - public final ApiCallable deleteEventsCallable() { + public final UnaryCallable deleteEventsCallable() { return deleteEventsCallable; } diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceSettings.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceSettings.java index b34dde3f867b..63ffa975b475 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceSettings.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceSettings.java @@ -13,13 +13,19 @@ */ package com.google.cloud.errorreporting.spi.v1beta1; +import static com.google.cloud.errorreporting.spi.v1beta1.PagedResponseWrappers.ListEventsPagedResponse; +import static com.google.cloud.errorreporting.spi.v1beta1.PagedResponseWrappers.ListGroupStatsPagedResponse; + import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; -import com.google.api.gax.grpc.PageStreamingCallSettings; -import com.google.api.gax.grpc.PageStreamingDescriptor; +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedCallSettings; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseFactory; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; +import com.google.api.gax.grpc.UnaryCallable; import com.google.auth.Credentials; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -81,29 +87,22 @@ public class ErrorStatsServiceSettings extends ServiceApiSettings { private static final ImmutableList DEFAULT_SERVICE_SCOPES = ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - - private final PageStreamingCallSettings< - ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats> + private final PagedCallSettings< + ListGroupStatsRequest, ListGroupStatsResponse, ListGroupStatsPagedResponse> listGroupStatsSettings; - private final PageStreamingCallSettings + private final PagedCallSettings listEventsSettings; private final SimpleCallSettings deleteEventsSettings; /** Returns the object with the settings used for calls to listGroupStats. */ - public PageStreamingCallSettings + public PagedCallSettings< + ListGroupStatsRequest, ListGroupStatsResponse, ListGroupStatsPagedResponse> listGroupStatsSettings() { return listGroupStatsSettings; } /** Returns the object with the settings used for calls to listEvents. */ - public PageStreamingCallSettings + public PagedCallSettings listEventsSettings() { return listEventsSettings; } @@ -157,10 +156,10 @@ private ErrorStatsServiceSettings(Builder settingsBuilder) throws IOException { deleteEventsSettings = settingsBuilder.deleteEventsSettings().build(); } - private static final PageStreamingDescriptor< + private static final PagedListDescriptor< ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats> LIST_GROUP_STATS_PAGE_STR_DESC = - new PageStreamingDescriptor< + new PagedListDescriptor< ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats>() { @Override public Object emptyToken() { @@ -194,9 +193,9 @@ public Iterable extractResources(ListGroupStatsResponse payload } }; - private static final PageStreamingDescriptor + private static final PagedListDescriptor LIST_EVENTS_PAGE_STR_DESC = - new PageStreamingDescriptor() { + new PagedListDescriptor() { @Override public Object emptyToken() { return ""; @@ -228,15 +227,45 @@ public Iterable extractResources(ListEventsResponse payload) { } }; + private static final PagedListResponseFactory< + ListGroupStatsRequest, ListGroupStatsResponse, ListGroupStatsPagedResponse> + LIST_GROUP_STATS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListGroupStatsRequest, ListGroupStatsResponse, ListGroupStatsPagedResponse>() { + @Override + public ListGroupStatsPagedResponse createPagedListResponse( + UnaryCallable callable, + ListGroupStatsRequest request, + CallContext context) { + return new ListGroupStatsPagedResponse( + callable, LIST_GROUP_STATS_PAGE_STR_DESC, request, context); + } + }; + + private static final PagedListResponseFactory< + ListEventsRequest, ListEventsResponse, ListEventsPagedResponse> + LIST_EVENTS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListEventsRequest, ListEventsResponse, ListEventsPagedResponse>() { + @Override + public ListEventsPagedResponse createPagedListResponse( + UnaryCallable callable, + ListEventsRequest request, + CallContext context) { + return new ListEventsPagedResponse( + callable, LIST_EVENTS_PAGE_STR_DESC, request, context); + } + }; + /** Builder for ErrorStatsServiceSettings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; - private final PageStreamingCallSettings.Builder< - ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats> + private final PagedCallSettings.Builder< + ListGroupStatsRequest, ListGroupStatsResponse, ListGroupStatsPagedResponse> listGroupStatsSettings; - private final PageStreamingCallSettings.Builder< - ListEventsRequest, ListEventsResponse, ErrorEvent> + private final PagedCallSettings.Builder< + ListEventsRequest, ListEventsResponse, ListEventsPagedResponse> listEventsSettings; private final SimpleCallSettings.Builder deleteEventsSettings; @@ -273,21 +302,21 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); listGroupStatsSettings = - PageStreamingCallSettings.newBuilder( - ErrorStatsServiceGrpc.METHOD_LIST_GROUP_STATS, LIST_GROUP_STATS_PAGE_STR_DESC); + PagedCallSettings.newBuilder( + ErrorStatsServiceGrpc.METHOD_LIST_GROUP_STATS, LIST_GROUP_STATS_PAGE_STR_FACT); listEventsSettings = - PageStreamingCallSettings.newBuilder( - ErrorStatsServiceGrpc.METHOD_LIST_EVENTS, LIST_EVENTS_PAGE_STR_DESC); + PagedCallSettings.newBuilder( + ErrorStatsServiceGrpc.METHOD_LIST_EVENTS, LIST_EVENTS_PAGE_STR_FACT); deleteEventsSettings = SimpleCallSettings.newBuilder(ErrorStatsServiceGrpc.METHOD_DELETE_EVENTS); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( listGroupStatsSettings, listEventsSettings, deleteEventsSettings); } @@ -319,14 +348,21 @@ private Builder(ErrorStatsServiceSettings settings) { listEventsSettings = settings.listEventsSettings.toBuilder(); deleteEventsSettings = settings.deleteEventsSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( listGroupStatsSettings, listEventsSettings, deleteEventsSettings); } + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); + } + @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -372,23 +408,26 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } /** Returns the builder for the settings used for calls to listGroupStats. */ - public PageStreamingCallSettings.Builder< - ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats> + public PagedCallSettings.Builder< + ListGroupStatsRequest, ListGroupStatsResponse, ListGroupStatsPagedResponse> listGroupStatsSettings() { return listGroupStatsSettings; } /** Returns the builder for the settings used for calls to listEvents. */ - public PageStreamingCallSettings.Builder + public PagedCallSettings.Builder listEventsSettings() { return listEventsSettings; } diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/PagedResponseWrappers.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/PagedResponseWrappers.java new file mode 100644 index 000000000000..094cdcaa0ea1 --- /dev/null +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/PagedResponseWrappers.java @@ -0,0 +1,61 @@ +/* + * 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.cloud.errorreporting.spi.v1beta1; + +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseImpl; +import com.google.api.gax.grpc.UnaryCallable; +import com.google.devtools.clouderrorreporting.v1beta1.ErrorEvent; +import com.google.devtools.clouderrorreporting.v1beta1.ErrorGroupStats; +import com.google.devtools.clouderrorreporting.v1beta1.ListEventsRequest; +import com.google.devtools.clouderrorreporting.v1beta1.ListEventsResponse; +import com.google.devtools.clouderrorreporting.v1beta1.ListGroupStatsRequest; +import com.google.devtools.clouderrorreporting.v1beta1.ListGroupStatsResponse; + +// AUTO-GENERATED DOCUMENTATION AND CLASS +/** + * Wrapper class to contain paged response types for page streaming methods. Each static class + * inside this wrapper class is used as the return type of one of an API method that implements the + * page streaming pattern. + */ +@javax.annotation.Generated("by GAPIC") +public class PagedResponseWrappers { + + public static class ListGroupStatsPagedResponse + extends PagedListResponseImpl< + ListGroupStatsRequest, ListGroupStatsResponse, ErrorGroupStats> { + + public ListGroupStatsPagedResponse( + UnaryCallable callable, + PagedListDescriptor + pageDescriptor, + ListGroupStatsRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } + + public static class ListEventsPagedResponse + extends PagedListResponseImpl { + + public ListEventsPagedResponse( + UnaryCallable callable, + PagedListDescriptor pageDescriptor, + ListEventsRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } +} diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceApi.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceApi.java index cdd5714e093e..907c9d193271 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceApi.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceApi.java @@ -13,7 +13,7 @@ */ package com.google.cloud.errorreporting.spi.v1beta1; -import com.google.api.gax.grpc.ApiCallable; +import com.google.api.gax.grpc.UnaryCallable; import com.google.api.gax.protobuf.PathTemplate; import com.google.devtools.clouderrorreporting.v1beta1.ReportErrorEventRequest; import com.google.devtools.clouderrorreporting.v1beta1.ReportErrorEventResponse; @@ -56,8 +56,8 @@ *

  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -85,7 +85,7 @@ public class ReportErrorsServiceApi implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable + private final UnaryCallable reportErrorEventCallable; private static final PathTemplate PROJECT_PATH_TEMPLATE = @@ -126,7 +126,7 @@ protected ReportErrorsServiceApi(ReportErrorsServiceSettings settings) throws IO this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.reportErrorEventCallable = - ApiCallable.create(settings.reportErrorEventSettings(), this.channel, this.executor); + UnaryCallable.create(settings.reportErrorEventSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { closeables.add( @@ -246,7 +246,7 @@ public final ReportErrorEventResponse reportErrorEvent(ReportErrorEventRequest r * } * */ - public final ApiCallable + public final UnaryCallable reportErrorEventCallable() { return reportErrorEventCallable; } diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceSettings.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceSettings.java index a4b390017c31..5c0d864d7907 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceSettings.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceSettings.java @@ -15,9 +15,9 @@ import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; import com.google.auth.Credentials; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -73,14 +73,6 @@ public class ReportErrorsServiceSettings extends ServiceApiSettings { private static final ImmutableList DEFAULT_SERVICE_SCOPES = ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - private final SimpleCallSettings reportErrorEventSettings; @@ -134,7 +126,7 @@ private ReportErrorsServiceSettings(Builder settingsBuilder) throws IOException /** Builder for ReportErrorsServiceSettings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; private final SimpleCallSettings.Builder reportErrorEventSettings; @@ -171,12 +163,13 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); reportErrorEventSettings = SimpleCallSettings.newBuilder(ReportErrorsServiceGrpc.METHOD_REPORT_ERROR_EVENT); - methodSettingsBuilders = ImmutableList.of(reportErrorEventSettings); + unaryMethodSettingsBuilders = + ImmutableList.of(reportErrorEventSettings); } private static Builder createDefault() { @@ -195,12 +188,20 @@ private Builder(ReportErrorsServiceSettings settings) { reportErrorEventSettings = settings.reportErrorEventSettings.toBuilder(); - methodSettingsBuilders = ImmutableList.of(reportErrorEventSettings); + unaryMethodSettingsBuilders = + ImmutableList.of(reportErrorEventSettings); + } + + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); } @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -246,11 +247,14 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/package-info.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/package-info.java index 15a1f4bf3564..94e1d677bb90 100644 --- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/package-info.java +++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/package-info.java @@ -15,7 +15,7 @@ /** * A client to Stackdriver Error Reporting API. * - *

    The interfaces provided are listed below, along with a usage sample + *

    The interfaces provided are listed below, along with usage samples. * *

    ==================== ErrorGroupServiceApi ==================== * diff --git a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceTest.java b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceTest.java index df94dfc07b04..323f437c222e 100644 --- a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceTest.java +++ b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceTest.java @@ -14,7 +14,9 @@ package com.google.cloud.errorreporting.spi.v1beta1; -import com.google.api.gax.core.PagedListResponse; +import static com.google.cloud.errorreporting.spi.v1beta1.PagedResponseWrappers.ListEventsPagedResponse; +import static com.google.cloud.errorreporting.spi.v1beta1.PagedResponseWrappers.ListGroupStatsPagedResponse; + import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; import com.google.common.collect.Lists; @@ -98,8 +100,8 @@ public void listGroupStatsTest() { String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]"); QueryTimeRange timeRange = QueryTimeRange.newBuilder().build(); - PagedListResponse - pagedListResponse = api.listGroupStats(formattedProjectName, timeRange); + ListGroupStatsPagedResponse pagedListResponse = + api.listGroupStats(formattedProjectName, timeRange); List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); Assert.assertEquals(1, resources.size()); @@ -131,8 +133,7 @@ public void listEventsTest() { String formattedProjectName = ErrorStatsServiceApi.formatProjectName("[PROJECT]"); String groupId = "groupId506361563"; - PagedListResponse pagedListResponse = - api.listEvents(formattedProjectName, groupId); + ListEventsPagedResponse pagedListResponse = api.listEvents(formattedProjectName, groupId); List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); Assert.assertEquals(1, resources.size()); diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceApi.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceApi.java index 1f663b9929f6..d4efc38381aa 100644 --- a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceApi.java +++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceApi.java @@ -13,7 +13,7 @@ */ package com.google.cloud.language.spi.v1beta1; -import com.google.api.gax.grpc.ApiCallable; +import com.google.api.gax.grpc.UnaryCallable; import com.google.cloud.language.v1beta1.AnalyzeEntitiesRequest; import com.google.cloud.language.v1beta1.AnalyzeEntitiesResponse; import com.google.cloud.language.v1beta1.AnalyzeSentimentRequest; @@ -60,8 +60,8 @@ *

  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -89,11 +89,11 @@ public class LanguageServiceApi implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable + private final UnaryCallable analyzeSentimentCallable; - private final ApiCallable + private final UnaryCallable analyzeEntitiesCallable; - private final ApiCallable annotateTextCallable; + private final UnaryCallable annotateTextCallable; /** Constructs an instance of LanguageServiceApi with default settings. */ public static final LanguageServiceApi create() throws IOException { @@ -119,11 +119,11 @@ protected LanguageServiceApi(LanguageServiceSettings settings) throws IOExceptio this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.analyzeSentimentCallable = - ApiCallable.create(settings.analyzeSentimentSettings(), this.channel, this.executor); + UnaryCallable.create(settings.analyzeSentimentSettings(), this.channel, this.executor); this.analyzeEntitiesCallable = - ApiCallable.create(settings.analyzeEntitiesSettings(), this.channel, this.executor); + UnaryCallable.create(settings.analyzeEntitiesSettings(), this.channel, this.executor); this.annotateTextCallable = - ApiCallable.create(settings.annotateTextSettings(), this.channel, this.executor); + UnaryCallable.create(settings.annotateTextSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { closeables.add( @@ -213,7 +213,7 @@ private final AnalyzeSentimentResponse analyzeSentiment(AnalyzeSentimentRequest * } * */ - public final ApiCallable + public final UnaryCallable analyzeSentimentCallable() { return analyzeSentimentCallable; } @@ -294,7 +294,7 @@ public final AnalyzeEntitiesResponse analyzeEntities(AnalyzeEntitiesRequest requ * } * */ - public final ApiCallable + public final UnaryCallable analyzeEntitiesCallable() { return analyzeEntitiesCallable; } @@ -385,7 +385,7 @@ public final AnnotateTextResponse annotateText(AnnotateTextRequest request) { * } * */ - public final ApiCallable annotateTextCallable() { + public final UnaryCallable annotateTextCallable() { return annotateTextCallable; } diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceSettings.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceSettings.java index 394c2a7add5e..93e0cc6fc90c 100644 --- a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceSettings.java +++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/LanguageServiceSettings.java @@ -15,9 +15,9 @@ import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; import com.google.auth.Credentials; import com.google.cloud.language.v1beta1.AnalyzeEntitiesRequest; import com.google.cloud.language.v1beta1.AnalyzeEntitiesResponse; @@ -76,14 +76,6 @@ public class LanguageServiceSettings extends ServiceApiSettings { private static final ImmutableList DEFAULT_SERVICE_SCOPES = ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - private final SimpleCallSettings analyzeSentimentSettings; private final SimpleCallSettings @@ -153,7 +145,7 @@ private LanguageServiceSettings(Builder settingsBuilder) throws IOException { /** Builder for LanguageServiceSettings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; private final SimpleCallSettings.Builder analyzeSentimentSettings; @@ -194,7 +186,7 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); analyzeSentimentSettings = SimpleCallSettings.newBuilder(LanguageServiceGrpc.METHOD_ANALYZE_SENTIMENT); @@ -205,8 +197,8 @@ private Builder() { annotateTextSettings = SimpleCallSettings.newBuilder(LanguageServiceGrpc.METHOD_ANNOTATE_TEXT); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( analyzeSentimentSettings, analyzeEntitiesSettings, annotateTextSettings); } @@ -238,14 +230,21 @@ private Builder(LanguageServiceSettings settings) { analyzeEntitiesSettings = settings.analyzeEntitiesSettings.toBuilder(); annotateTextSettings = settings.annotateTextSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( analyzeSentimentSettings, analyzeEntitiesSettings, annotateTextSettings); } + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); + } + @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -291,11 +290,14 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/PagedResponseWrappers.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/PagedResponseWrappers.java new file mode 100644 index 000000000000..c3971cf9e604 --- /dev/null +++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/PagedResponseWrappers.java @@ -0,0 +1,24 @@ +/* + * 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.cloud.language.spi.v1beta1; + + +// AUTO-GENERATED DOCUMENTATION AND CLASS +/** + * Wrapper class to contain paged response types for page streaming methods. Each static class + * inside this wrapper class is used as the return type of one of an API method that implements the + * page streaming pattern. + */ +@javax.annotation.Generated("by GAPIC") +public class PagedResponseWrappers {} diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/package-info.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/package-info.java index 9adb4a848362..00a31e853d4c 100644 --- a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/package-info.java +++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta1/package-info.java @@ -15,7 +15,7 @@ /** * A client to Google Cloud Natural Language API. * - *

    The interfaces provided are listed below, along with a usage sample + *

    The interfaces provided are listed below, along with usage samples. * *

    ================== LanguageServiceApi ================== * diff --git a/google-cloud-logging/pom.xml b/google-cloud-logging/pom.xml index d2185f866bb2..c277ef51017f 100644 --- a/google-cloud-logging/pom.xml +++ b/google-cloud-logging/pom.xml @@ -30,7 +30,7 @@ com.google.api.grpc grpc-google-logging-v2 - 0.1.0 + 0.1.1 io.grpc diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/DefaultLoggingRpc.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/DefaultLoggingRpc.java index a707c29d5a42..20bb13cf7273 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/DefaultLoggingRpc.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/DefaultLoggingRpc.java @@ -19,7 +19,7 @@ import static com.google.common.base.MoreObjects.firstNonNull; import com.google.api.gax.core.ConnectionSettings; -import com.google.api.gax.grpc.ApiCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; import com.google.api.gax.grpc.ApiException; import com.google.cloud.AuthCredentials; import com.google.cloud.GrpcServiceOptions.ExecutorFactory; @@ -92,7 +92,7 @@ protected ExecutorFactory executorFactory() { } @Override - protected ApiCallSettings.Builder apiCallSettings() { + protected UnaryCallSettings.Builder apiCallSettings() { return super.apiCallSettings(); } @@ -133,7 +133,7 @@ public DefaultLoggingRpc(LoggingOptions options) throws IOException { logBuilder.provideChannelWith(connectionSettings); metricsBuilder.provideChannelWith(connectionSettings); } - ApiCallSettings.Builder callSettingsBuilder = internalOptions.apiCallSettings(); + UnaryCallSettings.Builder callSettingsBuilder = internalOptions.apiCallSettings(); confBuilder.applyToAllApiMethods(callSettingsBuilder); logBuilder.applyToAllApiMethods(callSettingsBuilder); metricsBuilder.applyToAllApiMethods(callSettingsBuilder); diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Api.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Api.java index f49aca494e33..42c8ae8cccf0 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Api.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Api.java @@ -13,8 +13,9 @@ */ package com.google.cloud.logging.spi.v2; -import com.google.api.gax.core.PagedListResponse; -import com.google.api.gax.grpc.ApiCallable; +import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListSinksPagedResponse; + +import com.google.api.gax.grpc.UnaryCallable; import com.google.api.gax.protobuf.PathTemplate; import com.google.logging.v2.CreateSinkRequest; import com.google.logging.v2.DeleteSinkRequest; @@ -61,8 +62,8 @@ *

  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -90,14 +91,12 @@ public class ConfigServiceV2Api implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable listSinksCallable; - private final ApiCallable< - ListSinksRequest, PagedListResponse> - listSinksPagedCallable; - private final ApiCallable getSinkCallable; - private final ApiCallable createSinkCallable; - private final ApiCallable updateSinkCallable; - private final ApiCallable deleteSinkCallable; + private final UnaryCallable listSinksCallable; + private final UnaryCallable listSinksPagedCallable; + private final UnaryCallable getSinkCallable; + private final UnaryCallable createSinkCallable; + private final UnaryCallable updateSinkCallable; + private final UnaryCallable deleteSinkCallable; private static final PathTemplate PARENT_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}"); @@ -156,17 +155,17 @@ protected ConfigServiceV2Api(ConfigServiceV2Settings settings) throws IOExceptio this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.listSinksCallable = - ApiCallable.create(settings.listSinksSettings(), this.channel, this.executor); + UnaryCallable.create(settings.listSinksSettings(), this.channel, this.executor); this.listSinksPagedCallable = - ApiCallable.createPagedVariant(settings.listSinksSettings(), this.channel, this.executor); + UnaryCallable.createPagedVariant(settings.listSinksSettings(), this.channel, this.executor); this.getSinkCallable = - ApiCallable.create(settings.getSinkSettings(), this.channel, this.executor); + UnaryCallable.create(settings.getSinkSettings(), this.channel, this.executor); this.createSinkCallable = - ApiCallable.create(settings.createSinkSettings(), this.channel, this.executor); + UnaryCallable.create(settings.createSinkSettings(), this.channel, this.executor); this.updateSinkCallable = - ApiCallable.create(settings.updateSinkSettings(), this.channel, this.executor); + UnaryCallable.create(settings.updateSinkSettings(), this.channel, this.executor); this.deleteSinkCallable = - ApiCallable.create(settings.deleteSinkSettings(), this.channel, this.executor); + UnaryCallable.create(settings.deleteSinkSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { closeables.add( @@ -207,12 +206,11 @@ public final ConfigServiceV2Settings getSettings() { * } * * - * @param parent Required. The resource name containing the sinks. Example: + * @param parent Required. The cloud resource containing the sinks. Example: * `"projects/my-logging-project"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse listSinks( - String parent) { + public final ListSinksPagedResponse listSinks(String parent) { PARENT_PATH_TEMPLATE.validate(parent, "listSinks"); ListSinksRequest request = ListSinksRequest.newBuilder().setParent(parent).build(); return listSinks(request); @@ -239,8 +237,7 @@ public final PagedListResponse lis * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse listSinks( - ListSinksRequest request) { + public final ListSinksPagedResponse listSinks(ListSinksRequest request) { return listSinksPagedCallable().call(request); } @@ -256,7 +253,7 @@ public final PagedListResponse lis * ListSinksRequest request = ListSinksRequest.newBuilder() * .setParent(formattedParent) * .build(); - * ListenableFuture<PagedListResponse<ListSinksRequest,ListSinksResponse,LogSink>> future = configServiceV2Api.listSinksPagedCallable().futureCall(request); + * ListenableFuture<ListSinksPagedResponse> future = configServiceV2Api.listSinksPagedCallable().futureCall(request); * // Do something * for (LogSink element : future.get().iterateAllElements()) { * // doThingsWith(element); @@ -264,9 +261,7 @@ public final PagedListResponse lis * } * */ - public final ApiCallable< - ListSinksRequest, PagedListResponse> - listSinksPagedCallable() { + public final UnaryCallable listSinksPagedCallable() { return listSinksPagedCallable; } @@ -297,7 +292,7 @@ public final PagedListResponse lis * } * */ - public final ApiCallable listSinksCallable() { + public final UnaryCallable listSinksCallable() { return listSinksCallable; } @@ -314,7 +309,7 @@ public final ApiCallable listSinksCallable( * } * * - * @param sinkName The resource name of the sink to return. Example: + * @param sinkName Required. The resource name of the sink to return. Example: * `"projects/my-project-id/sinks/my-sink-id"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ @@ -365,7 +360,7 @@ private final LogSink getSink(GetSinkRequest request) { * } * */ - public final ApiCallable getSinkCallable() { + public final UnaryCallable getSinkCallable() { return getSinkCallable; } @@ -383,9 +378,10 @@ public final ApiCallable getSinkCallable() { * } * * - * @param parent The resource in which to create the sink. Example: `"projects/my-project-id"`. - *

    The new sink must be provided in the request. - * @param sink The new sink, which must not have an identifier that already exists. + * @param parent Required. The resource in which to create the sink. Example: + * `"projects/my-project-id"`. The new sink must be provided in the request. + * @param sink Required. The new sink, whose `name` parameter is a sink identifier that is not + * already in use. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final LogSink createSink(String parent, LogSink sink) { @@ -440,13 +436,13 @@ public final LogSink createSink(CreateSinkRequest request) { * } * */ - public final ApiCallable createSinkCallable() { + public final UnaryCallable createSinkCallable() { return createSinkCallable; } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Creates or updates a sink. + * Updates or creates a sink. * *

    Sample code: * @@ -458,12 +454,11 @@ public final ApiCallable createSinkCallable() { * } * * - * @param sinkName The resource name of the sink to update. Example: - * `"projects/my-project-id/sinks/my-sink-id"`. - *

    The updated sink must be provided in the request and have the same name that is - * specified in `sinkName`. If the sink does not exist, it is created. - * @param sink The updated sink, whose name must be the same as the sink identifier in `sinkName`. - * If `sinkName` does not exist, then this method creates a new sink. + * @param sinkName Required. The resource name of the sink to update, including the parent + * resource and the sink identifier. If the sink does not exist, this method creates the sink. + * Example: `"projects/my-project-id/sinks/my-sink-id"`. + * @param sink Required. The updated sink, whose name is the same identifier that appears as part + * of `sinkName`. If `sinkName` does not exist, then this method creates a new sink. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final LogSink updateSink(String sinkName, LogSink sink) { @@ -475,7 +470,7 @@ public final LogSink updateSink(String sinkName, LogSink sink) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Creates or updates a sink. + * Updates or creates a sink. * *

    Sample code: * @@ -500,7 +495,7 @@ public final LogSink updateSink(UpdateSinkRequest request) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Creates or updates a sink. + * Updates or creates a sink. * *

    Sample code: * @@ -518,7 +513,7 @@ public final LogSink updateSink(UpdateSinkRequest request) { * } * */ - public final ApiCallable updateSinkCallable() { + public final UnaryCallable updateSinkCallable() { return updateSinkCallable; } @@ -535,8 +530,9 @@ public final ApiCallable updateSinkCallable() { * } * * - * @param sinkName The resource name of the sink to delete. Example: - * `"projects/my-project-id/sinks/my-sink-id"`. + * @param sinkName Required. The resource name of the sink to delete, including the parent + * resource and the sink identifier. Example: `"projects/my-project-id/sinks/my-sink-id"`. It + * is an error if the sink does not exist. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final void deleteSink(String sinkName) { @@ -586,7 +582,7 @@ private final void deleteSink(DeleteSinkRequest request) { * } * */ - public final ApiCallable deleteSinkCallable() { + public final UnaryCallable deleteSinkCallable() { return deleteSinkCallable; } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Settings.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Settings.java index f44dddab6743..e64335800d90 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Settings.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Settings.java @@ -13,13 +13,18 @@ */ package com.google.cloud.logging.spi.v2; +import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListSinksPagedResponse; + import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; -import com.google.api.gax.grpc.PageStreamingCallSettings; -import com.google.api.gax.grpc.PageStreamingDescriptor; +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedCallSettings; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseFactory; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; +import com.google.api.gax.grpc.UnaryCallable; import com.google.auth.Credentials; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -86,15 +91,7 @@ public class ConfigServiceV2Settings extends ServiceApiSettings { .add("https://www.googleapis.com/auth/logging.write") .build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - - private final PageStreamingCallSettings + private final PagedCallSettings listSinksSettings; private final SimpleCallSettings getSinkSettings; private final SimpleCallSettings createSinkSettings; @@ -102,7 +99,7 @@ public class ConfigServiceV2Settings extends ServiceApiSettings { private final SimpleCallSettings deleteSinkSettings; /** Returns the object with the settings used for calls to listSinks. */ - public PageStreamingCallSettings + public PagedCallSettings listSinksSettings() { return listSinksSettings; } @@ -173,9 +170,9 @@ private ConfigServiceV2Settings(Builder settingsBuilder) throws IOException { deleteSinkSettings = settingsBuilder.deleteSinkSettings().build(); } - private static final PageStreamingDescriptor + private static final PagedListDescriptor LIST_SINKS_PAGE_STR_DESC = - new PageStreamingDescriptor() { + new PagedListDescriptor() { @Override public Object emptyToken() { return ""; @@ -207,11 +204,27 @@ public Iterable extractResources(ListSinksResponse payload) { } }; + private static final PagedListResponseFactory< + ListSinksRequest, ListSinksResponse, ListSinksPagedResponse> + LIST_SINKS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListSinksRequest, ListSinksResponse, ListSinksPagedResponse>() { + @Override + public ListSinksPagedResponse createPagedListResponse( + UnaryCallable callable, + ListSinksRequest request, + CallContext context) { + return new ListSinksPagedResponse( + callable, LIST_SINKS_PAGE_STR_DESC, request, context); + } + }; + /** Builder for ConfigServiceV2Settings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; - private final PageStreamingCallSettings.Builder + private final PagedCallSettings.Builder< + ListSinksRequest, ListSinksResponse, ListSinksPagedResponse> listSinksSettings; private final SimpleCallSettings.Builder getSinkSettings; private final SimpleCallSettings.Builder createSinkSettings; @@ -250,11 +263,11 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); listSinksSettings = - PageStreamingCallSettings.newBuilder( - ConfigServiceV2Grpc.METHOD_LIST_SINKS, LIST_SINKS_PAGE_STR_DESC); + PagedCallSettings.newBuilder( + ConfigServiceV2Grpc.METHOD_LIST_SINKS, LIST_SINKS_PAGE_STR_FACT); getSinkSettings = SimpleCallSettings.newBuilder(ConfigServiceV2Grpc.METHOD_GET_SINK); @@ -264,8 +277,8 @@ private Builder() { deleteSinkSettings = SimpleCallSettings.newBuilder(ConfigServiceV2Grpc.METHOD_DELETE_SINK); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( listSinksSettings, getSinkSettings, createSinkSettings, @@ -313,8 +326,8 @@ private Builder(ConfigServiceV2Settings settings) { updateSinkSettings = settings.updateSinkSettings.toBuilder(); deleteSinkSettings = settings.deleteSinkSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( listSinksSettings, getSinkSettings, createSinkSettings, @@ -322,9 +335,16 @@ private Builder(ConfigServiceV2Settings settings) { deleteSinkSettings); } + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); + } + @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -370,16 +390,19 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } /** Returns the builder for the settings used for calls to listSinks. */ - public PageStreamingCallSettings.Builder + public PagedCallSettings.Builder listSinksSettings() { return listSinksSettings; } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Api.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Api.java index 0200b82f7d2a..7897bfd14a57 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Api.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Api.java @@ -13,10 +13,11 @@ */ package com.google.cloud.logging.spi.v2; +import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListLogEntriesPagedResponse; +import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListMonitoredResourceDescriptorsPagedResponse; + import com.google.api.MonitoredResource; -import com.google.api.MonitoredResourceDescriptor; -import com.google.api.gax.core.PagedListResponse; -import com.google.api.gax.grpc.ApiCallable; +import com.google.api.gax.grpc.UnaryCallable; import com.google.api.gax.protobuf.PathTemplate; import com.google.logging.v2.DeleteLogRequest; import com.google.logging.v2.ListLogEntriesRequest; @@ -64,8 +65,8 @@ *

  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -93,22 +94,17 @@ public class LoggingServiceV2Api implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable deleteLogCallable; - private final ApiCallable + private final UnaryCallable deleteLogCallable; + private final UnaryCallable writeLogEntriesCallable; - private final ApiCallable listLogEntriesCallable; - private final ApiCallable< - ListLogEntriesRequest, - PagedListResponse> + private final UnaryCallable listLogEntriesCallable; + private final UnaryCallable listLogEntriesPagedCallable; - private final ApiCallable< + private final UnaryCallable< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse> listMonitoredResourceDescriptorsCallable; - private final ApiCallable< - ListMonitoredResourceDescriptorsRequest, - PagedListResponse< - ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor>> + private final UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsPagedResponse> listMonitoredResourceDescriptorsPagedCallable; private static final PathTemplate PARENT_PATH_TEMPLATE = @@ -168,19 +164,19 @@ protected LoggingServiceV2Api(LoggingServiceV2Settings settings) throws IOExcept this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.deleteLogCallable = - ApiCallable.create(settings.deleteLogSettings(), this.channel, this.executor); + UnaryCallable.create(settings.deleteLogSettings(), this.channel, this.executor); this.writeLogEntriesCallable = - ApiCallable.create(settings.writeLogEntriesSettings(), this.channel, this.executor); + UnaryCallable.create(settings.writeLogEntriesSettings(), this.channel, this.executor); this.listLogEntriesCallable = - ApiCallable.create(settings.listLogEntriesSettings(), this.channel, this.executor); + UnaryCallable.create(settings.listLogEntriesSettings(), this.channel, this.executor); this.listLogEntriesPagedCallable = - ApiCallable.createPagedVariant( + UnaryCallable.createPagedVariant( settings.listLogEntriesSettings(), this.channel, this.executor); this.listMonitoredResourceDescriptorsCallable = - ApiCallable.create( + UnaryCallable.create( settings.listMonitoredResourceDescriptorsSettings(), this.channel, this.executor); this.listMonitoredResourceDescriptorsPagedCallable = - ApiCallable.createPagedVariant( + UnaryCallable.createPagedVariant( settings.listMonitoredResourceDescriptorsSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { @@ -271,7 +267,7 @@ private final void deleteLog(DeleteLogRequest request) { * } * */ - public final ApiCallable deleteLogCallable() { + public final UnaryCallable deleteLogCallable() { return deleteLogCallable; } @@ -291,19 +287,24 @@ public final ApiCallable deleteLogCallable() { * } * * - * @param logName Optional. A default log resource name for those log entries in `entries` that do - * not specify their own `logName`. Example: `"projects/my-project/logs/syslog"`. See + * @param logName Optional. A default log resource name that is assigned to all log entries in + * `entries` that do not specify a value for `log_name`. Example: + * `"projects/my-project/logs/syslog"`. See [LogEntry][google.logging.v2.LogEntry]. + * @param resource Optional. A default monitored resource object that is assigned to all log + * entries in `entries` that do not specify a value for `resource`. Example: + *

    { "type": "gce_instance", "labels": { "zone": "us-central1-a", "instance_id": + * "00000000000000000000" }} + *

    See [LogEntry][google.logging.v2.LogEntry]. + * @param labels Optional. Default labels that are added to the `labels` field of all log entries + * in `entries`. If a log entry already has a label with the same key as a label in this + * parameter, then the log entry's label is not changed. See * [LogEntry][google.logging.v2.LogEntry]. - * @param resource Optional. A default monitored resource for those log entries in `entries` that - * do not specify their own `resource`. - * @param labels Optional. User-defined `key:value` items that are added to the `labels` field of - * each log entry in `entries`, except when a log entry specifies its own `key:value` item - * with the same key. Example: `{ "size": "large", "color":"red" }` - * @param entries Required. The log entries to write. The log entries must have values for all - * required fields. - *

    To improve throughput and to avoid exceeding the quota limit for calls to - * `entries.write`, use this field to write multiple log entries at once rather than // - * calling this method for each log entry. + * @param entries Required. The log entries to write. Values supplied for the fields `log_name`, + * `resource`, and `labels` in this `entries.write` request are added to those log entries + * that do not provide their own values for the fields. + *

    To improve throughput and to avoid exceeding the [quota limit](/logging/quota-policy) + * for calls to `entries.write`, you should write multiple log entries at once rather than + * calling this method for each individual log entry. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final WriteLogEntriesResponse writeLogEntries( @@ -365,7 +366,7 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ * } * */ - public final ApiCallable + public final UnaryCallable writeLogEntriesCallable() { return writeLogEntriesCallable; } @@ -388,11 +389,13 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ * } * * - * @param projectIds Required. One or more project IDs or project numbers from which to retrieve - * log entries. Examples of a project ID: `"my-project-1A"`, `"1234567890"`. - * @param filter Optional. An [advanced logs filter](/logging/docs/view/advanced_filters). The - * filter is compared against all log entries in the projects specified by `projectIds`. Only - * entries that match the filter are retrieved. An empty filter matches all log entries. + * @param projectIds Deprecated. One or more project identifiers or project numbers from which to + * retrieve log entries. Examples: `"my-project-1A"`, `"1234567890"`. If present, these + * project identifiers are converted to resource format and added to the list of resources in + * `resourceNames`. Callers should use `resourceNames` rather than this parameter. + * @param filter Optional. A filter that chooses which log entries to return. See [Advanced Logs + * Filters](/logging/docs/view/advanced_filters). Only log entries that match the filter are + * returned. An empty filter matches all log entries. * @param orderBy Optional. How the results should be sorted. Presently, the only permitted values * are `"timestamp asc"` (default) and `"timestamp desc"`. The first option returns entries in * order of increasing values of `LogEntry.timestamp` (oldest first), and the second option @@ -400,8 +403,8 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ * timestamps are returned in order of `LogEntry.insertId`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse - listLogEntries(List projectIds, String filter, String orderBy) { + public final ListLogEntriesPagedResponse listLogEntries( + List projectIds, String filter, String orderBy) { ListLogEntriesRequest request = ListLogEntriesRequest.newBuilder() .addAllProjectIds(projectIds) @@ -433,8 +436,7 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse - listLogEntries(ListLogEntriesRequest request) { + public final ListLogEntriesPagedResponse listLogEntries(ListLogEntriesRequest request) { return listLogEntriesPagedCallable().call(request); } @@ -451,7 +453,7 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ * ListLogEntriesRequest request = ListLogEntriesRequest.newBuilder() * .addAllProjectIds(projectIds) * .build(); - * ListenableFuture<PagedListResponse<ListLogEntriesRequest,ListLogEntriesResponse,LogEntry>> future = loggingServiceV2Api.listLogEntriesPagedCallable().futureCall(request); + * ListenableFuture<ListLogEntriesPagedResponse> future = loggingServiceV2Api.listLogEntriesPagedCallable().futureCall(request); * // Do something * for (LogEntry element : future.get().iterateAllElements()) { * // doThingsWith(element); @@ -459,9 +461,7 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ * } * */ - public final ApiCallable< - ListLogEntriesRequest, - PagedListResponse> + public final UnaryCallable listLogEntriesPagedCallable() { return listLogEntriesPagedCallable; } @@ -494,7 +494,8 @@ public final WriteLogEntriesResponse writeLogEntries(WriteLogEntriesRequest requ * } * */ - public final ApiCallable listLogEntriesCallable() { + public final UnaryCallable + listLogEntriesCallable() { return listLogEntriesCallable; } @@ -516,10 +517,8 @@ public final ApiCallable listLogE * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse< - ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor> - listMonitoredResourceDescriptors(ListMonitoredResourceDescriptorsRequest request) { + public final ListMonitoredResourceDescriptorsPagedResponse listMonitoredResourceDescriptors( + ListMonitoredResourceDescriptorsRequest request) { return listMonitoredResourceDescriptorsPagedCallable().call(request); } @@ -532,7 +531,7 @@ public final ApiCallable listLogE *

    
        * try (LoggingServiceV2Api loggingServiceV2Api = LoggingServiceV2Api.create()) {
        *   ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder().build();
    -   *   ListenableFuture<PagedListResponse<ListMonitoredResourceDescriptorsRequest,ListMonitoredResourceDescriptorsResponse,MonitoredResourceDescriptor>> future = loggingServiceV2Api.listMonitoredResourceDescriptorsPagedCallable().futureCall(request);
    +   *   ListenableFuture<ListMonitoredResourceDescriptorsPagedResponse> future = loggingServiceV2Api.listMonitoredResourceDescriptorsPagedCallable().futureCall(request);
        *   // Do something
        *   for (MonitoredResourceDescriptor element : future.get().iterateAllElements()) {
        *     // doThingsWith(element);
    @@ -540,11 +539,8 @@ public final ApiCallable listLogE
        * }
        * 
    */ - public final ApiCallable< - ListMonitoredResourceDescriptorsRequest, - PagedListResponse< - ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor>> + public final UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsPagedResponse> listMonitoredResourceDescriptorsPagedCallable() { return listMonitoredResourceDescriptorsPagedCallable; } @@ -573,7 +569,7 @@ public final ApiCallable listLogE * } * */ - public final ApiCallable< + public final UnaryCallable< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse> listMonitoredResourceDescriptorsCallable() { return listMonitoredResourceDescriptorsCallable; diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Settings.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Settings.java index 3db49f10b4f0..9df5a05994cd 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Settings.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Settings.java @@ -13,14 +13,20 @@ */ package com.google.cloud.logging.spi.v2; +import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListLogEntriesPagedResponse; +import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListMonitoredResourceDescriptorsPagedResponse; + import com.google.api.MonitoredResourceDescriptor; import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; -import com.google.api.gax.grpc.PageStreamingCallSettings; -import com.google.api.gax.grpc.PageStreamingDescriptor; +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedCallSettings; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseFactory; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; +import com.google.api.gax.grpc.UnaryCallable; import com.google.auth.Credentials; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -88,22 +94,15 @@ public class LoggingServiceV2Settings extends ServiceApiSettings { .add("https://www.googleapis.com/auth/logging.write") .build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - private final SimpleCallSettings deleteLogSettings; private final SimpleCallSettings writeLogEntriesSettings; - private final PageStreamingCallSettings + private final PagedCallSettings< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse> listLogEntriesSettings; - private final PageStreamingCallSettings< + private final PagedCallSettings< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor> + ListMonitoredResourceDescriptorsPagedResponse> listMonitoredResourceDescriptorsSettings; /** Returns the object with the settings used for calls to deleteLog. */ @@ -118,15 +117,16 @@ public SimpleCallSettings deleteLogSettings() { } /** Returns the object with the settings used for calls to listLogEntries. */ - public PageStreamingCallSettings + public PagedCallSettings< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse> listLogEntriesSettings() { return listLogEntriesSettings; } /** Returns the object with the settings used for calls to listMonitoredResourceDescriptors. */ - public PageStreamingCallSettings< + public PagedCallSettings< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor> + ListMonitoredResourceDescriptorsPagedResponse> listMonitoredResourceDescriptorsSettings() { return listMonitoredResourceDescriptorsSettings; } @@ -177,10 +177,9 @@ private LoggingServiceV2Settings(Builder settingsBuilder) throws IOException { settingsBuilder.listMonitoredResourceDescriptorsSettings().build(); } - private static final PageStreamingDescriptor< - ListLogEntriesRequest, ListLogEntriesResponse, LogEntry> + private static final PagedListDescriptor LIST_LOG_ENTRIES_PAGE_STR_DESC = - new PageStreamingDescriptor() { + new PagedListDescriptor() { @Override public Object emptyToken() { return ""; @@ -213,11 +212,11 @@ public Iterable extractResources(ListLogEntriesResponse payload) { } }; - private static final PageStreamingDescriptor< + private static final PagedListDescriptor< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC = - new PageStreamingDescriptor< + new PagedListDescriptor< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor>() { @Override @@ -258,19 +257,54 @@ public Iterable extractResources( } }; + private static final PagedListResponseFactory< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse> + LIST_LOG_ENTRIES_PAGE_STR_FACT = + new PagedListResponseFactory< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse>() { + @Override + public ListLogEntriesPagedResponse createPagedListResponse( + UnaryCallable callable, + ListLogEntriesRequest request, + CallContext context) { + return new ListLogEntriesPagedResponse( + callable, LIST_LOG_ENTRIES_PAGE_STR_DESC, request, context); + } + }; + + private static final PagedListResponseFactory< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, + ListMonitoredResourceDescriptorsPagedResponse> + LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, + ListMonitoredResourceDescriptorsPagedResponse>() { + @Override + public ListMonitoredResourceDescriptorsPagedResponse createPagedListResponse( + UnaryCallable< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse> + callable, + ListMonitoredResourceDescriptorsRequest request, + CallContext context) { + return new ListMonitoredResourceDescriptorsPagedResponse( + callable, LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC, request, context); + } + }; + /** Builder for LoggingServiceV2Settings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; private final SimpleCallSettings.Builder deleteLogSettings; private final SimpleCallSettings.Builder writeLogEntriesSettings; - private final PageStreamingCallSettings.Builder< - ListLogEntriesRequest, ListLogEntriesResponse, LogEntry> + private final PagedCallSettings.Builder< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse> listLogEntriesSettings; - private final PageStreamingCallSettings.Builder< + private final PagedCallSettings.Builder< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor> + ListMonitoredResourceDescriptorsPagedResponse> listMonitoredResourceDescriptorsSettings; private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS; @@ -315,7 +349,7 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); deleteLogSettings = SimpleCallSettings.newBuilder(LoggingServiceV2Grpc.METHOD_DELETE_LOG); @@ -323,16 +357,16 @@ private Builder() { SimpleCallSettings.newBuilder(LoggingServiceV2Grpc.METHOD_WRITE_LOG_ENTRIES); listLogEntriesSettings = - PageStreamingCallSettings.newBuilder( - LoggingServiceV2Grpc.METHOD_LIST_LOG_ENTRIES, LIST_LOG_ENTRIES_PAGE_STR_DESC); + PagedCallSettings.newBuilder( + LoggingServiceV2Grpc.METHOD_LIST_LOG_ENTRIES, LIST_LOG_ENTRIES_PAGE_STR_FACT); listMonitoredResourceDescriptorsSettings = - PageStreamingCallSettings.newBuilder( + PagedCallSettings.newBuilder( LoggingServiceV2Grpc.METHOD_LIST_MONITORED_RESOURCE_DESCRIPTORS, - LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC); + LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_FACT); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( deleteLogSettings, writeLogEntriesSettings, listLogEntriesSettings, @@ -374,17 +408,24 @@ private Builder(LoggingServiceV2Settings settings) { listMonitoredResourceDescriptorsSettings = settings.listMonitoredResourceDescriptorsSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( deleteLogSettings, writeLogEntriesSettings, listLogEntriesSettings, listMonitoredResourceDescriptorsSettings); } + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); + } + @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -430,11 +471,14 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } @@ -450,16 +494,16 @@ public SimpleCallSettings.Builder deleteLogSettings() { } /** Returns the builder for the settings used for calls to listLogEntries. */ - public PageStreamingCallSettings.Builder< - ListLogEntriesRequest, ListLogEntriesResponse, LogEntry> + public PagedCallSettings.Builder< + ListLogEntriesRequest, ListLogEntriesResponse, ListLogEntriesPagedResponse> listLogEntriesSettings() { return listLogEntriesSettings; } /** Returns the builder for the settings used for calls to listMonitoredResourceDescriptors. */ - public PageStreamingCallSettings.Builder< + public PagedCallSettings.Builder< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor> + ListMonitoredResourceDescriptorsPagedResponse> listMonitoredResourceDescriptorsSettings() { return listMonitoredResourceDescriptorsSettings; } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Api.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Api.java index e458ba1c756e..14e282373f89 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Api.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Api.java @@ -13,8 +13,9 @@ */ package com.google.cloud.logging.spi.v2; -import com.google.api.gax.core.PagedListResponse; -import com.google.api.gax.grpc.ApiCallable; +import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListLogMetricsPagedResponse; + +import com.google.api.gax.grpc.UnaryCallable; import com.google.api.gax.protobuf.PathTemplate; import com.google.logging.v2.CreateLogMetricRequest; import com.google.logging.v2.DeleteLogMetricRequest; @@ -60,8 +61,8 @@ *

  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -89,15 +90,13 @@ public class MetricsServiceV2Api implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable listLogMetricsCallable; - private final ApiCallable< - ListLogMetricsRequest, - PagedListResponse> + private final UnaryCallable listLogMetricsCallable; + private final UnaryCallable listLogMetricsPagedCallable; - private final ApiCallable getLogMetricCallable; - private final ApiCallable createLogMetricCallable; - private final ApiCallable updateLogMetricCallable; - private final ApiCallable deleteLogMetricCallable; + private final UnaryCallable getLogMetricCallable; + private final UnaryCallable createLogMetricCallable; + private final UnaryCallable updateLogMetricCallable; + private final UnaryCallable deleteLogMetricCallable; private static final PathTemplate PARENT_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}"); @@ -156,18 +155,18 @@ protected MetricsServiceV2Api(MetricsServiceV2Settings settings) throws IOExcept this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.listLogMetricsCallable = - ApiCallable.create(settings.listLogMetricsSettings(), this.channel, this.executor); + UnaryCallable.create(settings.listLogMetricsSettings(), this.channel, this.executor); this.listLogMetricsPagedCallable = - ApiCallable.createPagedVariant( + UnaryCallable.createPagedVariant( settings.listLogMetricsSettings(), this.channel, this.executor); this.getLogMetricCallable = - ApiCallable.create(settings.getLogMetricSettings(), this.channel, this.executor); + UnaryCallable.create(settings.getLogMetricSettings(), this.channel, this.executor); this.createLogMetricCallable = - ApiCallable.create(settings.createLogMetricSettings(), this.channel, this.executor); + UnaryCallable.create(settings.createLogMetricSettings(), this.channel, this.executor); this.updateLogMetricCallable = - ApiCallable.create(settings.updateLogMetricSettings(), this.channel, this.executor); + UnaryCallable.create(settings.updateLogMetricSettings(), this.channel, this.executor); this.deleteLogMetricCallable = - ApiCallable.create(settings.deleteLogMetricSettings(), this.channel, this.executor); + UnaryCallable.create(settings.deleteLogMetricSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { closeables.add( @@ -212,8 +211,7 @@ public final MetricsServiceV2Settings getSettings() { * `"projects/my-project-id"`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse - listLogMetrics(String parent) { + public final ListLogMetricsPagedResponse listLogMetrics(String parent) { PARENT_PATH_TEMPLATE.validate(parent, "listLogMetrics"); ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder().setParent(parent).build(); return listLogMetrics(request); @@ -240,8 +238,7 @@ public final MetricsServiceV2Settings getSettings() { * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse - listLogMetrics(ListLogMetricsRequest request) { + public final ListLogMetricsPagedResponse listLogMetrics(ListLogMetricsRequest request) { return listLogMetricsPagedCallable().call(request); } @@ -257,7 +254,7 @@ public final MetricsServiceV2Settings getSettings() { * ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder() * .setParent(formattedParent) * .build(); - * ListenableFuture<PagedListResponse<ListLogMetricsRequest,ListLogMetricsResponse,LogMetric>> future = metricsServiceV2Api.listLogMetricsPagedCallable().futureCall(request); + * ListenableFuture<ListLogMetricsPagedResponse> future = metricsServiceV2Api.listLogMetricsPagedCallable().futureCall(request); * // Do something * for (LogMetric element : future.get().iterateAllElements()) { * // doThingsWith(element); @@ -265,9 +262,7 @@ public final MetricsServiceV2Settings getSettings() { * } * */ - public final ApiCallable< - ListLogMetricsRequest, - PagedListResponse> + public final UnaryCallable listLogMetricsPagedCallable() { return listLogMetricsPagedCallable; } @@ -299,7 +294,8 @@ public final MetricsServiceV2Settings getSettings() { * } * */ - public final ApiCallable listLogMetricsCallable() { + public final UnaryCallable + listLogMetricsCallable() { return listLogMetricsCallable; } @@ -368,7 +364,7 @@ private final LogMetric getLogMetric(GetLogMetricRequest request) { * } * */ - public final ApiCallable getLogMetricCallable() { + public final UnaryCallable getLogMetricCallable() { return getLogMetricCallable; } @@ -444,7 +440,7 @@ public final LogMetric createLogMetric(CreateLogMetricRequest request) { * } * */ - public final ApiCallable createLogMetricCallable() { + public final UnaryCallable createLogMetricCallable() { return createLogMetricCallable; } @@ -522,7 +518,7 @@ public final LogMetric updateLogMetric(UpdateLogMetricRequest request) { * } * */ - public final ApiCallable updateLogMetricCallable() { + public final UnaryCallable updateLogMetricCallable() { return updateLogMetricCallable; } @@ -591,7 +587,7 @@ private final void deleteLogMetric(DeleteLogMetricRequest request) { * } * */ - public final ApiCallable deleteLogMetricCallable() { + public final UnaryCallable deleteLogMetricCallable() { return deleteLogMetricCallable; } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Settings.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Settings.java index 33302e500c2f..c7959b1f2953 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Settings.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Settings.java @@ -13,13 +13,18 @@ */ package com.google.cloud.logging.spi.v2; +import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListLogMetricsPagedResponse; + import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; -import com.google.api.gax.grpc.PageStreamingCallSettings; -import com.google.api.gax.grpc.PageStreamingDescriptor; +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedCallSettings; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseFactory; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; +import com.google.api.gax.grpc.UnaryCallable; import com.google.auth.Credentials; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -86,15 +91,8 @@ public class MetricsServiceV2Settings extends ServiceApiSettings { .add("https://www.googleapis.com/auth/logging.write") .build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - - private final PageStreamingCallSettings + private final PagedCallSettings< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse> listLogMetricsSettings; private final SimpleCallSettings getLogMetricSettings; private final SimpleCallSettings createLogMetricSettings; @@ -102,7 +100,8 @@ public class MetricsServiceV2Settings extends ServiceApiSettings { private final SimpleCallSettings deleteLogMetricSettings; /** Returns the object with the settings used for calls to listLogMetrics. */ - public PageStreamingCallSettings + public PagedCallSettings< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse> listLogMetricsSettings() { return listLogMetricsSettings; } @@ -173,10 +172,9 @@ private MetricsServiceV2Settings(Builder settingsBuilder) throws IOException { deleteLogMetricSettings = settingsBuilder.deleteLogMetricSettings().build(); } - private static final PageStreamingDescriptor< - ListLogMetricsRequest, ListLogMetricsResponse, LogMetric> + private static final PagedListDescriptor LIST_LOG_METRICS_PAGE_STR_DESC = - new PageStreamingDescriptor() { + new PagedListDescriptor() { @Override public Object emptyToken() { return ""; @@ -209,12 +207,27 @@ public Iterable extractResources(ListLogMetricsResponse payload) { } }; + private static final PagedListResponseFactory< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse> + LIST_LOG_METRICS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse>() { + @Override + public ListLogMetricsPagedResponse createPagedListResponse( + UnaryCallable callable, + ListLogMetricsRequest request, + CallContext context) { + return new ListLogMetricsPagedResponse( + callable, LIST_LOG_METRICS_PAGE_STR_DESC, request, context); + } + }; + /** Builder for MetricsServiceV2Settings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; - private final PageStreamingCallSettings.Builder< - ListLogMetricsRequest, ListLogMetricsResponse, LogMetric> + private final PagedCallSettings.Builder< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse> listLogMetricsSettings; private final SimpleCallSettings.Builder getLogMetricSettings; private final SimpleCallSettings.Builder @@ -255,11 +268,11 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); listLogMetricsSettings = - PageStreamingCallSettings.newBuilder( - MetricsServiceV2Grpc.METHOD_LIST_LOG_METRICS, LIST_LOG_METRICS_PAGE_STR_DESC); + PagedCallSettings.newBuilder( + MetricsServiceV2Grpc.METHOD_LIST_LOG_METRICS, LIST_LOG_METRICS_PAGE_STR_FACT); getLogMetricSettings = SimpleCallSettings.newBuilder(MetricsServiceV2Grpc.METHOD_GET_LOG_METRIC); @@ -273,8 +286,8 @@ private Builder() { deleteLogMetricSettings = SimpleCallSettings.newBuilder(MetricsServiceV2Grpc.METHOD_DELETE_LOG_METRIC); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( listLogMetricsSettings, getLogMetricSettings, createLogMetricSettings, @@ -322,8 +335,8 @@ private Builder(MetricsServiceV2Settings settings) { updateLogMetricSettings = settings.updateLogMetricSettings.toBuilder(); deleteLogMetricSettings = settings.deleteLogMetricSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( listLogMetricsSettings, getLogMetricSettings, createLogMetricSettings, @@ -331,9 +344,16 @@ private Builder(MetricsServiceV2Settings settings) { deleteLogMetricSettings); } + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); + } + @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -379,17 +399,20 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } /** Returns the builder for the settings used for calls to listLogMetrics. */ - public PageStreamingCallSettings.Builder< - ListLogMetricsRequest, ListLogMetricsResponse, LogMetric> + public PagedCallSettings.Builder< + ListLogMetricsRequest, ListLogMetricsResponse, ListLogMetricsPagedResponse> listLogMetricsSettings() { return listLogMetricsSettings; } diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/PagedResponseWrappers.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/PagedResponseWrappers.java new file mode 100644 index 000000000000..75e2e10d3584 --- /dev/null +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/PagedResponseWrappers.java @@ -0,0 +1,97 @@ +/* + * 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.cloud.logging.spi.v2; + +import com.google.api.MonitoredResourceDescriptor; +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseImpl; +import com.google.api.gax.grpc.UnaryCallable; +import com.google.logging.v2.ListLogEntriesRequest; +import com.google.logging.v2.ListLogEntriesResponse; +import com.google.logging.v2.ListLogMetricsRequest; +import com.google.logging.v2.ListLogMetricsResponse; +import com.google.logging.v2.ListMonitoredResourceDescriptorsRequest; +import com.google.logging.v2.ListMonitoredResourceDescriptorsResponse; +import com.google.logging.v2.ListSinksRequest; +import com.google.logging.v2.ListSinksResponse; +import com.google.logging.v2.LogEntry; +import com.google.logging.v2.LogMetric; +import com.google.logging.v2.LogSink; + +// AUTO-GENERATED DOCUMENTATION AND CLASS +/** + * Wrapper class to contain paged response types for page streaming methods. Each static class + * inside this wrapper class is used as the return type of one of an API method that implements the + * page streaming pattern. + */ +@javax.annotation.Generated("by GAPIC") +public class PagedResponseWrappers { + + public static class ListLogEntriesPagedResponse + extends PagedListResponseImpl { + + public ListLogEntriesPagedResponse( + UnaryCallable callable, + PagedListDescriptor pageDescriptor, + ListLogEntriesRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } + + public static class ListMonitoredResourceDescriptorsPagedResponse + extends PagedListResponseImpl< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor> { + + public ListMonitoredResourceDescriptorsPagedResponse( + UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse> + callable, + PagedListDescriptor< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor> + pageDescriptor, + ListMonitoredResourceDescriptorsRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } + + public static class ListSinksPagedResponse + extends PagedListResponseImpl { + + public ListSinksPagedResponse( + UnaryCallable callable, + PagedListDescriptor pageDescriptor, + ListSinksRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } + + public static class ListLogMetricsPagedResponse + extends PagedListResponseImpl { + + public ListLogMetricsPagedResponse( + UnaryCallable callable, + PagedListDescriptor + pageDescriptor, + ListLogMetricsRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } +} diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/package-info.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/package-info.java index c579f3ff26d6..26d0600a08b3 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/package-info.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/package-info.java @@ -15,7 +15,7 @@ /** * A client to Stackdriver Logging API. * - *

    The interfaces provided are listed below, along with a usage sample + *

    The interfaces provided are listed below, along with usage samples. * *

    =================== LoggingServiceV2Api =================== * diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Test.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Test.java index 4ea8363a0dd8..32433dc85e51 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Test.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/ConfigServiceV2Test.java @@ -14,7 +14,8 @@ package com.google.cloud.logging.spi.v2; -import com.google.api.gax.core.PagedListResponse; +import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListSinksPagedResponse; + import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; import com.google.common.collect.Lists; @@ -93,8 +94,7 @@ public void listSinksTest() { String formattedParent = ConfigServiceV2Api.formatParentName("[PROJECT]"); - PagedListResponse pagedListResponse = - api.listSinks(formattedParent); + ListSinksPagedResponse pagedListResponse = api.listSinks(formattedParent); List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); Assert.assertEquals(1, resources.size()); @@ -113,8 +113,14 @@ public void getSinkTest() { String name = "name3373707"; String destination = "destination-1429847026"; String filter = "filter-1274492040"; + String writerIdentity = "writerIdentity775638794"; LogSink expectedResponse = - LogSink.newBuilder().setName(name).setDestination(destination).setFilter(filter).build(); + LogSink.newBuilder() + .setName(name) + .setDestination(destination) + .setFilter(filter) + .setWriterIdentity(writerIdentity) + .build(); List expectedResponses = new ArrayList<>(); expectedResponses.add(expectedResponse); mockConfigServiceV2.setResponses(expectedResponses); @@ -137,8 +143,14 @@ public void createSinkTest() { String name = "name3373707"; String destination = "destination-1429847026"; String filter = "filter-1274492040"; + String writerIdentity = "writerIdentity775638794"; LogSink expectedResponse = - LogSink.newBuilder().setName(name).setDestination(destination).setFilter(filter).build(); + LogSink.newBuilder() + .setName(name) + .setDestination(destination) + .setFilter(filter) + .setWriterIdentity(writerIdentity) + .build(); List expectedResponses = new ArrayList<>(); expectedResponses.add(expectedResponse); mockConfigServiceV2.setResponses(expectedResponses); @@ -163,8 +175,14 @@ public void updateSinkTest() { String name = "name3373707"; String destination = "destination-1429847026"; String filter = "filter-1274492040"; + String writerIdentity = "writerIdentity775638794"; LogSink expectedResponse = - LogSink.newBuilder().setName(name).setDestination(destination).setFilter(filter).build(); + LogSink.newBuilder() + .setName(name) + .setDestination(destination) + .setFilter(filter) + .setWriterIdentity(writerIdentity) + .build(); List expectedResponses = new ArrayList<>(); expectedResponses.add(expectedResponse); mockConfigServiceV2.setResponses(expectedResponses); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Test.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Test.java index 24e7dcd5d64e..e4a44b72031e 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Test.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/LoggingServiceV2Test.java @@ -14,8 +14,9 @@ package com.google.cloud.logging.spi.v2; +import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListLogEntriesPagedResponse; + import com.google.api.MonitoredResource; -import com.google.api.gax.core.PagedListResponse; import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; import com.google.common.collect.Lists; @@ -146,8 +147,7 @@ public void listLogEntriesTest() { String filter = "filter-1274492040"; String orderBy = "orderBy1234304744"; - PagedListResponse pagedListResponse = - api.listLogEntries(projectIds, filter, orderBy); + ListLogEntriesPagedResponse pagedListResponse = api.listLogEntries(projectIds, filter, orderBy); List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); Assert.assertEquals(1, resources.size()); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Test.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Test.java index a497c5570804..54c76528be31 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Test.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/spi/v2/MetricsServiceV2Test.java @@ -14,7 +14,8 @@ package com.google.cloud.logging.spi.v2; -import com.google.api.gax.core.PagedListResponse; +import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListLogMetricsPagedResponse; + import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; import com.google.common.collect.Lists; @@ -96,8 +97,7 @@ public void listLogMetricsTest() { String formattedParent = MetricsServiceV2Api.formatParentName("[PROJECT]"); - PagedListResponse pagedListResponse = - api.listLogMetrics(formattedParent); + ListLogMetricsPagedResponse pagedListResponse = api.listLogMetrics(formattedParent); List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); Assert.assertEquals(1, resources.size()); diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceApi.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceApi.java deleted file mode 100644 index a81142c23194..000000000000 --- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceApi.java +++ /dev/null @@ -1,283 +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.cloud.monitoring.spi.v3; - -import com.google.api.MonitoredResource; -import com.google.api.gax.grpc.ApiCallable; -import com.google.api.gax.protobuf.PathTemplate; -import com.google.monitoring.v3.CollectdPayload; -import com.google.monitoring.v3.CreateCollectdTimeSeriesRequest; -import com.google.protobuf.Empty; -import io.grpc.ManagedChannel; -import java.io.Closeable; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ScheduledExecutorService; - -// AUTO-GENERATED DOCUMENTATION AND SERVICE -/** - * Service Description: The AgentTranslation API allows `collectd`-based agents to write time series - * data to Cloud Monitoring. See [google.monitoring.v3.MetricService.CreateTimeSeries] instead. - * - *

    This class provides the ability to make remote calls to the backing service through method - * calls that map to API methods. Sample code to get started: - * - *

    - * 
    - * try (AgentTranslationServiceApi agentTranslationServiceApi = AgentTranslationServiceApi.create()) {
    - *   String formattedName = AgentTranslationServiceApi.formatProjectName("[PROJECT]");
    - *   MonitoredResource resource = MonitoredResource.newBuilder().build();
    - *   String collectdVersion = "";
    - *   List<CollectdPayload> collectdPayloads = new ArrayList<>();
    - *   agentTranslationServiceApi.createCollectdTimeSeries(formattedName, resource, collectdVersion, collectdPayloads);
    - * }
    - * 
    - * 
    - * - *

    Note: close() needs to be called on the agentTranslationServiceApi object to clean up - * resources such as threads. In the example above, try-with-resources is used, which automatically - * calls close(). - * - *

    The surface of this class includes several types of Java methods for each of the API's - * methods: - * - *

      - *
    1. A "flattened" method. With this type of method, the fields of the request type have been - * converted into function parameters. It may be the case that not all fields are available as - * parameters, and not every API method will have a flattened method entry point. - *
    2. A "request object" method. This type of method only takes one parameter, a request object, - * which must be constructed before the call. Not every API method will have a request object - * method. - *
    3. A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. - *
    - * - *

    See the individual methods for example code. - * - *

    Many parameters require resource names to be formatted in a particular way. To assist with - * these names, this class includes a format method for each type of name, and additionally a parse - * method to extract the individual identifiers contained within names that are returned. - * - *

    This class can be customized by passing in a custom instance of - * AgentTranslationServiceSettings to create(). For example: - * - *

    - * 
    - * AgentTranslationServiceSettings agentTranslationServiceSettings = AgentTranslationServiceSettings.defaultBuilder()
    - *     .provideChannelWith(myCredentials)
    - *     .build();
    - * AgentTranslationServiceApi agentTranslationServiceApi = AgentTranslationServiceApi.create(agentTranslationServiceSettings);
    - * 
    - * 
    - */ -@javax.annotation.Generated("by GAPIC") -public class AgentTranslationServiceApi implements AutoCloseable { - private final AgentTranslationServiceSettings settings; - private final ManagedChannel channel; - private final ScheduledExecutorService executor; - private final List closeables = new ArrayList<>(); - - private final ApiCallable - createCollectdTimeSeriesCallable; - - private static final PathTemplate PROJECT_PATH_TEMPLATE = - PathTemplate.createWithoutUrlEncoding("projects/{project}"); - - /** Formats a string containing the fully-qualified path to represent a project resource. */ - public static final String formatProjectName(String project) { - return PROJECT_PATH_TEMPLATE.instantiate("project", project); - } - - /** Parses the project from the given fully-qualified path which represents a project resource. */ - public static final String parseProjectFromProjectName(String projectName) { - return PROJECT_PATH_TEMPLATE.parse(projectName).get("project"); - } - - /** Constructs an instance of AgentTranslationServiceApi with default settings. */ - public static final AgentTranslationServiceApi create() throws IOException { - return create(AgentTranslationServiceSettings.defaultBuilder().build()); - } - - /** - * Constructs an instance of AgentTranslationServiceApi, using the given settings. The channels - * are created based on the settings passed in, or defaults for any settings that are not set. - */ - public static final AgentTranslationServiceApi create(AgentTranslationServiceSettings settings) - throws IOException { - return new AgentTranslationServiceApi(settings); - } - - /** - * Constructs an instance of AgentTranslationServiceApi, using the given settings. This is - * protected so that it easy to make a subclass, but otherwise, the static factory methods should - * be preferred. - */ - protected AgentTranslationServiceApi(AgentTranslationServiceSettings settings) - throws IOException { - this.settings = settings; - this.executor = settings.getExecutorProvider().getOrBuildExecutor(); - this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); - - this.createCollectdTimeSeriesCallable = - ApiCallable.create( - settings.createCollectdTimeSeriesSettings(), this.channel, this.executor); - - if (settings.getChannelProvider().shouldAutoClose()) { - closeables.add( - new Closeable() { - @Override - public void close() throws IOException { - channel.shutdown(); - } - }); - } - if (settings.getExecutorProvider().shouldAutoClose()) { - closeables.add( - new Closeable() { - @Override - public void close() throws IOException { - executor.shutdown(); - } - }); - } - } - - public final AgentTranslationServiceSettings getSettings() { - return settings; - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD - /** - * **Stackdriver Monitoring Agent only:** Creates a new time series. - * - *

    <aside class="caution">This method is only for use by the Google Monitoring Agent. Use - * [projects.timeSeries.create][google.monitoring.v3.MetricService.CreateTimeSeries] - * instead.</aside> - * - *

    Sample code: - * - *

    
    -   * try (AgentTranslationServiceApi agentTranslationServiceApi = AgentTranslationServiceApi.create()) {
    -   *   String formattedName = AgentTranslationServiceApi.formatProjectName("[PROJECT]");
    -   *   MonitoredResource resource = MonitoredResource.newBuilder().build();
    -   *   String collectdVersion = "";
    -   *   List<CollectdPayload> collectdPayloads = new ArrayList<>();
    -   *   agentTranslationServiceApi.createCollectdTimeSeries(formattedName, resource, collectdVersion, collectdPayloads);
    -   * }
    -   * 
    - * - * @param name The project in which to create the time series. The format is - * `"projects/PROJECT_ID_OR_NUMBER"`. - * @param resource The monitored resource associated with the time series. - * @param collectdVersion The version of `collectd` that collected the data. Example: - * `"5.3.0-192.el6"`. - * @param collectdPayloads The `collectd` payloads representing the time series data. You must not - * include more than a single point for each time series, so no two payloads can have the same - * values for all of the fields `plugin`, `plugin_instance`, `type`, and `type_instance`. - * @throws com.google.api.gax.grpc.ApiException if the remote call fails - */ - public final void createCollectdTimeSeries( - String name, - MonitoredResource resource, - String collectdVersion, - List collectdPayloads) { - PROJECT_PATH_TEMPLATE.validate(name, "createCollectdTimeSeries"); - CreateCollectdTimeSeriesRequest request = - CreateCollectdTimeSeriesRequest.newBuilder() - .setName(name) - .setResource(resource) - .setCollectdVersion(collectdVersion) - .addAllCollectdPayloads(collectdPayloads) - .build(); - createCollectdTimeSeries(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD - /** - * **Stackdriver Monitoring Agent only:** Creates a new time series. - * - *

    <aside class="caution">This method is only for use by the Google Monitoring Agent. Use - * [projects.timeSeries.create][google.monitoring.v3.MetricService.CreateTimeSeries] - * instead.</aside> - * - *

    Sample code: - * - *

    
    -   * try (AgentTranslationServiceApi agentTranslationServiceApi = AgentTranslationServiceApi.create()) {
    -   *   String formattedName = AgentTranslationServiceApi.formatProjectName("[PROJECT]");
    -   *   MonitoredResource resource = MonitoredResource.newBuilder().build();
    -   *   String collectdVersion = "";
    -   *   List<CollectdPayload> collectdPayloads = new ArrayList<>();
    -   *   CreateCollectdTimeSeriesRequest request = CreateCollectdTimeSeriesRequest.newBuilder()
    -   *     .setName(formattedName)
    -   *     .setResource(resource)
    -   *     .setCollectdVersion(collectdVersion)
    -   *     .addAllCollectdPayloads(collectdPayloads)
    -   *     .build();
    -   *   agentTranslationServiceApi.createCollectdTimeSeries(request);
    -   * }
    -   * 
    - * - * @param request The request object containing all of the parameters for the API call. - * @throws com.google.api.gax.grpc.ApiException if the remote call fails - */ - public final void createCollectdTimeSeries(CreateCollectdTimeSeriesRequest request) { - createCollectdTimeSeriesCallable().call(request); - } - - // AUTO-GENERATED DOCUMENTATION AND METHOD - /** - * **Stackdriver Monitoring Agent only:** Creates a new time series. - * - *

    <aside class="caution">This method is only for use by the Google Monitoring Agent. Use - * [projects.timeSeries.create][google.monitoring.v3.MetricService.CreateTimeSeries] - * instead.</aside> - * - *

    Sample code: - * - *

    
    -   * try (AgentTranslationServiceApi agentTranslationServiceApi = AgentTranslationServiceApi.create()) {
    -   *   String formattedName = AgentTranslationServiceApi.formatProjectName("[PROJECT]");
    -   *   MonitoredResource resource = MonitoredResource.newBuilder().build();
    -   *   String collectdVersion = "";
    -   *   List<CollectdPayload> collectdPayloads = new ArrayList<>();
    -   *   CreateCollectdTimeSeriesRequest request = CreateCollectdTimeSeriesRequest.newBuilder()
    -   *     .setName(formattedName)
    -   *     .setResource(resource)
    -   *     .setCollectdVersion(collectdVersion)
    -   *     .addAllCollectdPayloads(collectdPayloads)
    -   *     .build();
    -   *   ListenableFuture<Void> future = agentTranslationServiceApi.createCollectdTimeSeriesCallable().futureCall(request);
    -   *   // Do something
    -   *   future.get();
    -   * }
    -   * 
    - */ - public final ApiCallable - createCollectdTimeSeriesCallable() { - return createCollectdTimeSeriesCallable; - } - - /** - * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately - * cancelled. - */ - @Override - public final void close() throws Exception { - for (AutoCloseable closeable : closeables) { - closeable.close(); - } - } -} diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceSettings.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceSettings.java deleted file mode 100644 index 72bbff0eebbb..000000000000 --- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceSettings.java +++ /dev/null @@ -1,270 +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.cloud.monitoring.spi.v3; - -import com.google.api.gax.core.ConnectionSettings; -import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; -import com.google.api.gax.grpc.ServiceApiSettings; -import com.google.api.gax.grpc.SimpleCallSettings; -import com.google.auth.Credentials; -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.monitoring.v3.AgentTranslationServiceGrpc; -import com.google.monitoring.v3.CreateCollectdTimeSeriesRequest; -import com.google.protobuf.Empty; -import io.grpc.ManagedChannel; -import io.grpc.Status; -import java.io.IOException; -import java.util.List; -import java.util.concurrent.ScheduledExecutorService; -import org.joda.time.Duration; - -// AUTO-GENERATED DOCUMENTATION AND CLASS -/** - * Settings class to configure an instance of {@link AgentTranslationServiceApi}. - * - *

    The default instance has everything set to sensible defaults: - * - *

      - *
    • The default service address (monitoring.googleapis.com) and default port (443) are used. - *
    • Credentials are acquired automatically through Application Default Credentials. - *
    • Retries are configured for idempotent methods but not for non-idempotent methods. - *
    - * - *

    The builder of this class is recursive, so contained classes are themselves builders. When - * build() is called, the tree of builders is called to create the complete settings object. For - * example, to set the total timeout of createCollectdTimeSeries to 30 seconds: - * - *

    - * 
    - * AgentTranslationServiceSettings.Builder agentTranslationServiceSettingsBuilder =
    - *     AgentTranslationServiceSettings.defaultBuilder();
    - * agentTranslationServiceSettingsBuilder.createCollectdTimeSeriesSettings().getRetrySettingsBuilder()
    - *     .setTotalTimeout(Duration.standardSeconds(30));
    - * AgentTranslationServiceSettings agentTranslationServiceSettings = agentTranslationServiceSettingsBuilder.build();
    - * 
    - * 
    - */ -@javax.annotation.Generated("by GAPIC") -public class AgentTranslationServiceSettings extends ServiceApiSettings { - /** The default address of the service. */ - private static final String DEFAULT_SERVICE_ADDRESS = "monitoring.googleapis.com"; - - /** The default port of the service. */ - private static final int DEFAULT_SERVICE_PORT = 443; - - /** The default scopes of the service. */ - private static final ImmutableList DEFAULT_SERVICE_SCOPES = - ImmutableList.builder().build(); - - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - - private final SimpleCallSettings - createCollectdTimeSeriesSettings; - - /** Returns the object with the settings used for calls to createCollectdTimeSeries. */ - public SimpleCallSettings - createCollectdTimeSeriesSettings() { - return createCollectdTimeSeriesSettings; - } - - /** Returns the default service address. */ - public static String getDefaultServiceAddress() { - return DEFAULT_SERVICE_ADDRESS; - } - - /** Returns the default service port. */ - public static int getDefaultServicePort() { - return DEFAULT_SERVICE_PORT; - } - - /** Returns the default service scopes. */ - public static ImmutableList getDefaultServiceScopes() { - return DEFAULT_SERVICE_SCOPES; - } - - /** Returns a builder for this class with recommended defaults. */ - public static Builder defaultBuilder() { - return Builder.createDefault(); - } - - /** Returns a new builder for this class. */ - public static Builder newBuilder() { - return new Builder(); - } - - /** Returns a builder containing all the values of this settings class. */ - public Builder toBuilder() { - return new Builder(this); - } - - private AgentTranslationServiceSettings(Builder settingsBuilder) throws IOException { - super( - settingsBuilder.getChannelProvider(), - settingsBuilder.getExecutorProvider(), - settingsBuilder.getGeneratorName(), - settingsBuilder.getGeneratorVersion(), - settingsBuilder.getClientLibName(), - settingsBuilder.getClientLibVersion()); - - createCollectdTimeSeriesSettings = settingsBuilder.createCollectdTimeSeriesSettings().build(); - } - - /** Builder for AgentTranslationServiceSettings. */ - public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; - - private final SimpleCallSettings.Builder - createCollectdTimeSeriesSettings; - - private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS; - - static { - ImmutableMap.Builder> definitions = ImmutableMap.builder(); - definitions.put( - "idempotent", - Sets.immutableEnumSet( - Lists.newArrayList( - Status.Code.DEADLINE_EXCEEDED, Status.Code.UNAVAILABLE))); - definitions.put("non_idempotent", Sets.immutableEnumSet(Lists.newArrayList())); - RETRYABLE_CODE_DEFINITIONS = definitions.build(); - } - - private static final ImmutableMap RETRY_PARAM_DEFINITIONS; - - static { - ImmutableMap.Builder definitions = ImmutableMap.builder(); - RetrySettings.Builder settingsBuilder = null; - settingsBuilder = - RetrySettings.newBuilder() - .setInitialRetryDelay(Duration.millis(100L)) - .setRetryDelayMultiplier(1.3) - .setMaxRetryDelay(Duration.millis(60000L)) - .setInitialRpcTimeout(Duration.millis(20000L)) - .setRpcTimeoutMultiplier(1.0) - .setMaxRpcTimeout(Duration.millis(20000L)) - .setTotalTimeout(Duration.millis(600000L)); - definitions.put("default", settingsBuilder); - RETRY_PARAM_DEFINITIONS = definitions.build(); - } - - private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); - - createCollectdTimeSeriesSettings = - SimpleCallSettings.newBuilder( - AgentTranslationServiceGrpc.METHOD_CREATE_COLLECTD_TIME_SERIES); - - methodSettingsBuilders = - ImmutableList.of(createCollectdTimeSeriesSettings); - } - - private static Builder createDefault() { - Builder builder = new Builder(); - - builder - .createCollectdTimeSeriesSettings() - .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("non_idempotent")) - .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default")); - - return builder; - } - - private Builder(AgentTranslationServiceSettings settings) { - super(settings); - - createCollectdTimeSeriesSettings = settings.createCollectdTimeSeriesSettings.toBuilder(); - - methodSettingsBuilders = - ImmutableList.of(createCollectdTimeSeriesSettings); - } - - @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; - } - - @Override - public Builder provideExecutorWith(ScheduledExecutorService executor, boolean shouldAutoClose) { - super.provideExecutorWith(executor, shouldAutoClose); - return this; - } - - @Override - public Builder provideChannelWith(ManagedChannel channel, boolean shouldAutoClose) { - super.provideChannelWith(channel, shouldAutoClose); - return this; - } - - @Override - public Builder provideChannelWith(ConnectionSettings settings) { - super.provideChannelWith(settings); - return this; - } - - @Override - public Builder provideChannelWith(Credentials credentials) { - super.provideChannelWith(credentials); - return this; - } - - @Override - public Builder provideChannelWith(List scopes) { - super.provideChannelWith(scopes); - return this; - } - - @Override - public Builder setGeneratorHeader(String name, String version) { - super.setGeneratorHeader(name, version); - return this; - } - - @Override - public Builder setClientLibHeader(String name, String version) { - super.setClientLibHeader(name, version); - return this; - } - - /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. - */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); - return this; - } - - /** Returns the builder for the settings used for calls to createCollectdTimeSeries. */ - public SimpleCallSettings.Builder - createCollectdTimeSeriesSettings() { - return createCollectdTimeSeriesSettings; - } - - @Override - public AgentTranslationServiceSettings build() throws IOException { - return new AgentTranslationServiceSettings(this); - } - } -} diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceApi.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceApi.java index 850406c119de..1f9cb8ec9307 100644 --- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceApi.java +++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceApi.java @@ -13,9 +13,10 @@ */ package com.google.cloud.monitoring.spi.v3; -import com.google.api.MonitoredResource; -import com.google.api.gax.core.PagedListResponse; -import com.google.api.gax.grpc.ApiCallable; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListGroupMembersPagedResponse; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListGroupsPagedResponse; + +import com.google.api.gax.grpc.UnaryCallable; import com.google.api.gax.protobuf.PathTemplate; import com.google.monitoring.v3.CreateGroupRequest; import com.google.monitoring.v3.DeleteGroupRequest; @@ -25,7 +26,6 @@ import com.google.monitoring.v3.ListGroupMembersResponse; import com.google.monitoring.v3.ListGroupsRequest; import com.google.monitoring.v3.ListGroupsResponse; -import com.google.monitoring.v3.TimeInterval; import com.google.monitoring.v3.UpdateGroupRequest; import com.google.protobuf.Empty; import io.grpc.ManagedChannel; @@ -72,8 +72,8 @@ *
  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -101,19 +101,15 @@ public class GroupServiceApi implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable listGroupsCallable; - private final ApiCallable< - ListGroupsRequest, PagedListResponse> - listGroupsPagedCallable; - private final ApiCallable getGroupCallable; - private final ApiCallable createGroupCallable; - private final ApiCallable updateGroupCallable; - private final ApiCallable deleteGroupCallable; - private final ApiCallable + private final UnaryCallable listGroupsCallable; + private final UnaryCallable listGroupsPagedCallable; + private final UnaryCallable getGroupCallable; + private final UnaryCallable createGroupCallable; + private final UnaryCallable updateGroupCallable; + private final UnaryCallable deleteGroupCallable; + private final UnaryCallable listGroupMembersCallable; - private final ApiCallable< - ListGroupMembersRequest, - PagedListResponse> + private final UnaryCallable listGroupMembersPagedCallable; private static final PathTemplate PROJECT_PATH_TEMPLATE = @@ -172,21 +168,22 @@ protected GroupServiceApi(GroupServiceSettings settings) throws IOException { this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.listGroupsCallable = - ApiCallable.create(settings.listGroupsSettings(), this.channel, this.executor); + UnaryCallable.create(settings.listGroupsSettings(), this.channel, this.executor); this.listGroupsPagedCallable = - ApiCallable.createPagedVariant(settings.listGroupsSettings(), this.channel, this.executor); + UnaryCallable.createPagedVariant( + settings.listGroupsSettings(), this.channel, this.executor); this.getGroupCallable = - ApiCallable.create(settings.getGroupSettings(), this.channel, this.executor); + UnaryCallable.create(settings.getGroupSettings(), this.channel, this.executor); this.createGroupCallable = - ApiCallable.create(settings.createGroupSettings(), this.channel, this.executor); + UnaryCallable.create(settings.createGroupSettings(), this.channel, this.executor); this.updateGroupCallable = - ApiCallable.create(settings.updateGroupSettings(), this.channel, this.executor); + UnaryCallable.create(settings.updateGroupSettings(), this.channel, this.executor); this.deleteGroupCallable = - ApiCallable.create(settings.deleteGroupSettings(), this.channel, this.executor); + UnaryCallable.create(settings.deleteGroupSettings(), this.channel, this.executor); this.listGroupMembersCallable = - ApiCallable.create(settings.listGroupMembersSettings(), this.channel, this.executor); + UnaryCallable.create(settings.listGroupMembersSettings(), this.channel, this.executor); this.listGroupMembersPagedCallable = - ApiCallable.createPagedVariant( + UnaryCallable.createPagedVariant( settings.listGroupMembersSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { @@ -215,7 +212,7 @@ public final GroupServiceSettings getSettings() { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Lists the existing groups. The project ID in the URL path must refer to a Stackdriver account. + * Lists the existing groups. * *

    Sample code: * @@ -234,14 +231,13 @@ public final GroupServiceSettings getSettings() { * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse listGroups( - ListGroupsRequest request) { + public final ListGroupsPagedResponse listGroups(ListGroupsRequest request) { return listGroupsPagedCallable().call(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Lists the existing groups. The project ID in the URL path must refer to a Stackdriver account. + * Lists the existing groups. * *

    Sample code: * @@ -251,7 +247,7 @@ public final PagedListResponse lis * ListGroupsRequest request = ListGroupsRequest.newBuilder() * .setName(formattedName) * .build(); - * ListenableFuture<PagedListResponse<ListGroupsRequest,ListGroupsResponse,Group>> future = groupServiceApi.listGroupsPagedCallable().futureCall(request); + * ListenableFuture<ListGroupsPagedResponse> future = groupServiceApi.listGroupsPagedCallable().futureCall(request); * // Do something * for (Group element : future.get().iterateAllElements()) { * // doThingsWith(element); @@ -259,15 +255,13 @@ public final PagedListResponse lis * } * */ - public final ApiCallable< - ListGroupsRequest, PagedListResponse> - listGroupsPagedCallable() { + public final UnaryCallable listGroupsPagedCallable() { return listGroupsPagedCallable; } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Lists the existing groups. The project ID in the URL path must refer to a Stackdriver account. + * Lists the existing groups. * *

    Sample code: * @@ -292,13 +286,13 @@ public final PagedListResponse lis * } * */ - public final ApiCallable listGroupsCallable() { + public final UnaryCallable listGroupsCallable() { return listGroupsCallable; } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets a single group. The project ID in the URL path must refer to a Stackdriver account. + * Gets a single group. * *

    Sample code: * @@ -321,7 +315,7 @@ public final Group getGroup(String name) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets a single group. The project ID in the URL path must refer to a Stackdriver account. + * Gets a single group. * *

    Sample code: * @@ -344,7 +338,7 @@ private final Group getGroup(GetGroupRequest request) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets a single group. The project ID in the URL path must refer to a Stackdriver account. + * Gets a single group. * *

    Sample code: * @@ -360,13 +354,13 @@ private final Group getGroup(GetGroupRequest request) { * } * */ - public final ApiCallable getGroupCallable() { + public final UnaryCallable getGroupCallable() { return getGroupCallable; } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Creates a new group. The project ID in the URL path must refer to a Stackdriver account. + * Creates a new group. * *

    Sample code: * @@ -374,8 +368,7 @@ public final ApiCallable getGroupCallable() { * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) { * String formattedName = GroupServiceApi.formatProjectName("[PROJECT]"); * Group group = Group.newBuilder().build(); - * boolean validateOnly = false; - * Group response = groupServiceApi.createGroup(formattedName, group, validateOnly); + * Group response = groupServiceApi.createGroup(formattedName, group); * } * * @@ -383,23 +376,18 @@ public final ApiCallable getGroupCallable() { * `"projects/{project_id_or_number}"`. * @param group A group definition. It is an error to define the `name` field because the system * assigns the name. - * @param validateOnly If true, validate this request but do not create the group. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final Group createGroup(String name, Group group, boolean validateOnly) { + public final Group createGroup(String name, Group group) { PROJECT_PATH_TEMPLATE.validate(name, "createGroup"); CreateGroupRequest request = - CreateGroupRequest.newBuilder() - .setName(name) - .setGroup(group) - .setValidateOnly(validateOnly) - .build(); + CreateGroupRequest.newBuilder().setName(name).setGroup(group).build(); return createGroup(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Creates a new group. The project ID in the URL path must refer to a Stackdriver account. + * Creates a new group. * *

    Sample code: * @@ -407,11 +395,9 @@ public final Group createGroup(String name, Group group, boolean validateOnly) { * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) { * String formattedName = GroupServiceApi.formatProjectName("[PROJECT]"); * Group group = Group.newBuilder().build(); - * boolean validateOnly = false; * CreateGroupRequest request = CreateGroupRequest.newBuilder() * .setName(formattedName) * .setGroup(group) - * .setValidateOnly(validateOnly) * .build(); * Group response = groupServiceApi.createGroup(request); * } @@ -426,7 +412,7 @@ public final Group createGroup(CreateGroupRequest request) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Creates a new group. The project ID in the URL path must refer to a Stackdriver account. + * Creates a new group. * *

    Sample code: * @@ -434,11 +420,9 @@ public final Group createGroup(CreateGroupRequest request) { * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) { * String formattedName = GroupServiceApi.formatProjectName("[PROJECT]"); * Group group = Group.newBuilder().build(); - * boolean validateOnly = false; * CreateGroupRequest request = CreateGroupRequest.newBuilder() * .setName(formattedName) * .setGroup(group) - * .setValidateOnly(validateOnly) * .build(); * ListenableFuture<Group> future = groupServiceApi.createGroupCallable().futureCall(request); * // Do something @@ -446,50 +430,43 @@ public final Group createGroup(CreateGroupRequest request) { * } * */ - public final ApiCallable createGroupCallable() { + public final UnaryCallable createGroupCallable() { return createGroupCallable; } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Updates an existing group. You can change any group attributes except `name`. The project ID in - * the URL path must refer to a Stackdriver account. + * Updates an existing group. You can change any group attributes except `name`. * *

    Sample code: * *

    
        * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
        *   Group group = Group.newBuilder().build();
    -   *   boolean validateOnly = false;
    -   *   Group response = groupServiceApi.updateGroup(group, validateOnly);
    +   *   Group response = groupServiceApi.updateGroup(group);
        * }
        * 
    * * @param group The new definition of the group. All fields of the existing group, excepting * `name`, are replaced with the corresponding fields of this group. - * @param validateOnly If true, validate this request but do not update the existing group. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final Group updateGroup(Group group, boolean validateOnly) { - UpdateGroupRequest request = - UpdateGroupRequest.newBuilder().setGroup(group).setValidateOnly(validateOnly).build(); + public final Group updateGroup(Group group) { + UpdateGroupRequest request = UpdateGroupRequest.newBuilder().setGroup(group).build(); return updateGroup(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Updates an existing group. You can change any group attributes except `name`. The project ID in - * the URL path must refer to a Stackdriver account. + * Updates an existing group. You can change any group attributes except `name`. * *

    Sample code: * *

    
        * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
        *   Group group = Group.newBuilder().build();
    -   *   boolean validateOnly = false;
        *   UpdateGroupRequest request = UpdateGroupRequest.newBuilder()
        *     .setGroup(group)
    -   *     .setValidateOnly(validateOnly)
        *     .build();
        *   Group response = groupServiceApi.updateGroup(request);
        * }
    @@ -504,18 +481,15 @@ public final Group updateGroup(UpdateGroupRequest request) {
     
       // AUTO-GENERATED DOCUMENTATION AND METHOD
       /**
    -   * Updates an existing group. You can change any group attributes except `name`. The project ID in
    -   * the URL path must refer to a Stackdriver account.
    +   * Updates an existing group. You can change any group attributes except `name`.
        *
        * 

    Sample code: * *

    
        * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
        *   Group group = Group.newBuilder().build();
    -   *   boolean validateOnly = false;
        *   UpdateGroupRequest request = UpdateGroupRequest.newBuilder()
        *     .setGroup(group)
    -   *     .setValidateOnly(validateOnly)
        *     .build();
        *   ListenableFuture<Group> future = groupServiceApi.updateGroupCallable().futureCall(request);
        *   // Do something
    @@ -523,13 +497,13 @@ public final Group updateGroup(UpdateGroupRequest request) {
        * }
        * 
    */ - public final ApiCallable updateGroupCallable() { + public final UnaryCallable updateGroupCallable() { return updateGroupCallable; } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Deletes an existing group. The project ID in the URL path must refer to a Stackdriver account. + * Deletes an existing group. * *

    Sample code: * @@ -552,7 +526,7 @@ public final void deleteGroup(String name) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Deletes an existing group. The project ID in the URL path must refer to a Stackdriver account. + * Deletes an existing group. * *

    Sample code: * @@ -575,7 +549,7 @@ private final void deleteGroup(DeleteGroupRequest request) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Deletes an existing group. The project ID in the URL path must refer to a Stackdriver account. + * Deletes an existing group. * *

    Sample code: * @@ -591,23 +565,20 @@ private final void deleteGroup(DeleteGroupRequest request) { * } *

    */ - public final ApiCallable deleteGroupCallable() { + public final UnaryCallable deleteGroupCallable() { return deleteGroupCallable; } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Lists the monitored resources that are members of a group. The project ID in the URL path must - * refer to a Stackdriver account. + * Lists the monitored resources that are members of a group. * *

    Sample code: * *

    
        * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
        *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
    -   *   String filter = "";
    -   *   TimeInterval interval = TimeInterval.newBuilder().build();
    -   *   for (MonitoredResource element : groupServiceApi.listGroupMembers(formattedName, filter, interval).iterateAllElements()) {
    +   *   for (MonitoredResource element : groupServiceApi.listGroupMembers(formattedName).iterateAllElements()) {
        *     // doThingsWith(element);
        *   }
        * }
    @@ -615,45 +586,25 @@ public final ApiCallable deleteGroupCallable() {
        *
        * @param name The group whose members are listed. The format is
        *     `"projects/{project_id_or_number}/groups/{group_id}"`.
    -   * @param filter An optional [list filter](/monitoring/api/learn_more#filtering) describing the
    -   *     members to be returned. The filter may reference the type, labels, and metadata of
    -   *     monitored resources that comprise the group. For example, to return only resources
    -   *     representing Compute Engine VM instances, use this filter:
    -   *     

    resource.type = "gce_instance" - * @param interval An optional time interval for which results should be returned. Only members - * that were part of the group during the specified interval are included in the response. If - * no interval is provided then the group membership over the last minute is returned. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse< - ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource> - listGroupMembers(String name, String filter, TimeInterval interval) { + public final ListGroupMembersPagedResponse listGroupMembers(String name) { GROUP_PATH_TEMPLATE.validate(name, "listGroupMembers"); - ListGroupMembersRequest request = - ListGroupMembersRequest.newBuilder() - .setName(name) - .setFilter(filter) - .setInterval(interval) - .build(); + ListGroupMembersRequest request = ListGroupMembersRequest.newBuilder().setName(name).build(); return listGroupMembers(request); } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Lists the monitored resources that are members of a group. The project ID in the URL path must - * refer to a Stackdriver account. + * Lists the monitored resources that are members of a group. * *

    Sample code: * *

    
        * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
        *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
    -   *   String filter = "";
    -   *   TimeInterval interval = TimeInterval.newBuilder().build();
        *   ListGroupMembersRequest request = ListGroupMembersRequest.newBuilder()
        *     .setName(formattedName)
    -   *     .setFilter(filter)
    -   *     .setInterval(interval)
        *     .build();
        *   for (MonitoredResource element : groupServiceApi.listGroupMembers(request).iterateAllElements()) {
        *     // doThingsWith(element);
    @@ -664,30 +615,23 @@ public final ApiCallable deleteGroupCallable() {
        * @param request The request object containing all of the parameters for the API call.
        * @throws com.google.api.gax.grpc.ApiException if the remote call fails
        */
    -  public final PagedListResponse<
    -          ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource>
    -      listGroupMembers(ListGroupMembersRequest request) {
    +  public final ListGroupMembersPagedResponse listGroupMembers(ListGroupMembersRequest request) {
         return listGroupMembersPagedCallable().call(request);
       }
     
       // AUTO-GENERATED DOCUMENTATION AND METHOD
       /**
    -   * Lists the monitored resources that are members of a group. The project ID in the URL path must
    -   * refer to a Stackdriver account.
    +   * Lists the monitored resources that are members of a group.
        *
        * 

    Sample code: * *

    
        * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
        *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
    -   *   String filter = "";
    -   *   TimeInterval interval = TimeInterval.newBuilder().build();
        *   ListGroupMembersRequest request = ListGroupMembersRequest.newBuilder()
        *     .setName(formattedName)
    -   *     .setFilter(filter)
    -   *     .setInterval(interval)
        *     .build();
    -   *   ListenableFuture<PagedListResponse<ListGroupMembersRequest,ListGroupMembersResponse,MonitoredResource>> future = groupServiceApi.listGroupMembersPagedCallable().futureCall(request);
    +   *   ListenableFuture<ListGroupMembersPagedResponse> future = groupServiceApi.listGroupMembersPagedCallable().futureCall(request);
        *   // Do something
        *   for (MonitoredResource element : future.get().iterateAllElements()) {
        *     // doThingsWith(element);
    @@ -695,29 +639,22 @@ public final ApiCallable deleteGroupCallable() {
        * }
        * 
    */ - public final ApiCallable< - ListGroupMembersRequest, - PagedListResponse> + public final UnaryCallable listGroupMembersPagedCallable() { return listGroupMembersPagedCallable; } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Lists the monitored resources that are members of a group. The project ID in the URL path must - * refer to a Stackdriver account. + * Lists the monitored resources that are members of a group. * *

    Sample code: * *

    
        * try (GroupServiceApi groupServiceApi = GroupServiceApi.create()) {
        *   String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]");
    -   *   String filter = "";
    -   *   TimeInterval interval = TimeInterval.newBuilder().build();
        *   ListGroupMembersRequest request = ListGroupMembersRequest.newBuilder()
        *     .setName(formattedName)
    -   *     .setFilter(filter)
    -   *     .setInterval(interval)
        *     .build();
        *   while (true) {
        *     ListGroupMembersResponse response = groupServiceApi.listGroupMembersCallable().call(request);
    @@ -734,7 +671,7 @@ public final ApiCallable deleteGroupCallable() {
        * }
        * 
    */ - public final ApiCallable + public final UnaryCallable listGroupMembersCallable() { return listGroupMembersCallable; } diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceSettings.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceSettings.java index a5e1f1d06d73..28053d5a78fb 100644 --- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceSettings.java +++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/GroupServiceSettings.java @@ -13,14 +13,20 @@ */ package com.google.cloud.monitoring.spi.v3; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListGroupMembersPagedResponse; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListGroupsPagedResponse; + import com.google.api.MonitoredResource; import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; -import com.google.api.gax.grpc.PageStreamingCallSettings; -import com.google.api.gax.grpc.PageStreamingDescriptor; +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedCallSettings; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseFactory; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; +import com.google.api.gax.grpc.UnaryCallable; import com.google.auth.Credentials; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -83,26 +89,18 @@ public class GroupServiceSettings extends ServiceApiSettings { private static final ImmutableList DEFAULT_SERVICE_SCOPES = ImmutableList.builder().build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - - private final PageStreamingCallSettings + private final PagedCallSettings listGroupsSettings; private final SimpleCallSettings getGroupSettings; private final SimpleCallSettings createGroupSettings; private final SimpleCallSettings updateGroupSettings; private final SimpleCallSettings deleteGroupSettings; - private final PageStreamingCallSettings< - ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource> + private final PagedCallSettings< + ListGroupMembersRequest, ListGroupMembersResponse, ListGroupMembersPagedResponse> listGroupMembersSettings; /** Returns the object with the settings used for calls to listGroups. */ - public PageStreamingCallSettings + public PagedCallSettings listGroupsSettings() { return listGroupsSettings; } @@ -128,8 +126,8 @@ public SimpleCallSettings deleteGroupSettings() { } /** Returns the object with the settings used for calls to listGroupMembers. */ - public PageStreamingCallSettings< - ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource> + public PagedCallSettings< + ListGroupMembersRequest, ListGroupMembersResponse, ListGroupMembersPagedResponse> listGroupMembersSettings() { return listGroupMembersSettings; } @@ -181,9 +179,9 @@ private GroupServiceSettings(Builder settingsBuilder) throws IOException { listGroupMembersSettings = settingsBuilder.listGroupMembersSettings().build(); } - private static final PageStreamingDescriptor + private static final PagedListDescriptor LIST_GROUPS_PAGE_STR_DESC = - new PageStreamingDescriptor() { + new PagedListDescriptor() { @Override public Object emptyToken() { return ""; @@ -215,10 +213,10 @@ public Iterable extractResources(ListGroupsResponse payload) { } }; - private static final PageStreamingDescriptor< + private static final PagedListDescriptor< ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource> LIST_GROUP_MEMBERS_PAGE_STR_DESC = - new PageStreamingDescriptor< + new PagedListDescriptor< ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource>() { @Override public Object emptyToken() { @@ -255,18 +253,49 @@ public Iterable extractResources(ListGroupMembersResponse pay } }; + private static final PagedListResponseFactory< + ListGroupsRequest, ListGroupsResponse, ListGroupsPagedResponse> + LIST_GROUPS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListGroupsRequest, ListGroupsResponse, ListGroupsPagedResponse>() { + @Override + public ListGroupsPagedResponse createPagedListResponse( + UnaryCallable callable, + ListGroupsRequest request, + CallContext context) { + return new ListGroupsPagedResponse( + callable, LIST_GROUPS_PAGE_STR_DESC, request, context); + } + }; + + private static final PagedListResponseFactory< + ListGroupMembersRequest, ListGroupMembersResponse, ListGroupMembersPagedResponse> + LIST_GROUP_MEMBERS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListGroupMembersRequest, ListGroupMembersResponse, ListGroupMembersPagedResponse>() { + @Override + public ListGroupMembersPagedResponse createPagedListResponse( + UnaryCallable callable, + ListGroupMembersRequest request, + CallContext context) { + return new ListGroupMembersPagedResponse( + callable, LIST_GROUP_MEMBERS_PAGE_STR_DESC, request, context); + } + }; + /** Builder for GroupServiceSettings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; - private final PageStreamingCallSettings.Builder + private final PagedCallSettings.Builder< + ListGroupsRequest, ListGroupsResponse, ListGroupsPagedResponse> listGroupsSettings; private final SimpleCallSettings.Builder getGroupSettings; private final SimpleCallSettings.Builder createGroupSettings; private final SimpleCallSettings.Builder updateGroupSettings; private final SimpleCallSettings.Builder deleteGroupSettings; - private final PageStreamingCallSettings.Builder< - ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource> + private final PagedCallSettings.Builder< + ListGroupMembersRequest, ListGroupMembersResponse, ListGroupMembersPagedResponse> listGroupMembersSettings; private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS; @@ -301,11 +330,11 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); listGroupsSettings = - PageStreamingCallSettings.newBuilder( - GroupServiceGrpc.METHOD_LIST_GROUPS, LIST_GROUPS_PAGE_STR_DESC); + PagedCallSettings.newBuilder( + GroupServiceGrpc.METHOD_LIST_GROUPS, LIST_GROUPS_PAGE_STR_FACT); getGroupSettings = SimpleCallSettings.newBuilder(GroupServiceGrpc.METHOD_GET_GROUP); @@ -316,11 +345,11 @@ private Builder() { deleteGroupSettings = SimpleCallSettings.newBuilder(GroupServiceGrpc.METHOD_DELETE_GROUP); listGroupMembersSettings = - PageStreamingCallSettings.newBuilder( - GroupServiceGrpc.METHOD_LIST_GROUP_MEMBERS, LIST_GROUP_MEMBERS_PAGE_STR_DESC); + PagedCallSettings.newBuilder( + GroupServiceGrpc.METHOD_LIST_GROUP_MEMBERS, LIST_GROUP_MEMBERS_PAGE_STR_FACT); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( listGroupsSettings, getGroupSettings, createGroupSettings, @@ -375,8 +404,8 @@ private Builder(GroupServiceSettings settings) { deleteGroupSettings = settings.deleteGroupSettings.toBuilder(); listGroupMembersSettings = settings.listGroupMembersSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( listGroupsSettings, getGroupSettings, createGroupSettings, @@ -385,9 +414,16 @@ private Builder(GroupServiceSettings settings) { listGroupMembersSettings); } + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); + } + @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -433,16 +469,19 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } /** Returns the builder for the settings used for calls to listGroups. */ - public PageStreamingCallSettings.Builder + public PagedCallSettings.Builder listGroupsSettings() { return listGroupsSettings; } @@ -468,8 +507,8 @@ public SimpleCallSettings.Builder deleteGroupSettings } /** Returns the builder for the settings used for calls to listGroupMembers. */ - public PageStreamingCallSettings.Builder< - ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource> + public PagedCallSettings.Builder< + ListGroupMembersRequest, ListGroupMembersResponse, ListGroupMembersPagedResponse> listGroupMembersSettings() { return listGroupMembersSettings; } diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceApi.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceApi.java index bd3599c6d493..b88e28b7e8c4 100644 --- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceApi.java +++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceApi.java @@ -13,10 +13,13 @@ */ package com.google.cloud.monitoring.spi.v3; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListMetricDescriptorsPagedResponse; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListMonitoredResourceDescriptorsPagedResponse; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListTimeSeriesPagedResponse; + import com.google.api.MetricDescriptor; import com.google.api.MonitoredResourceDescriptor; -import com.google.api.gax.core.PagedListResponse; -import com.google.api.gax.grpc.ApiCallable; +import com.google.api.gax.grpc.UnaryCallable; import com.google.api.gax.protobuf.PathTemplate; import com.google.monitoring.v3.CreateMetricDescriptorRequest; import com.google.monitoring.v3.CreateTimeSeriesRequest; @@ -28,7 +31,9 @@ import com.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest; import com.google.monitoring.v3.ListMonitoredResourceDescriptorsResponse; import com.google.monitoring.v3.ListTimeSeriesRequest; +import com.google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView; import com.google.monitoring.v3.ListTimeSeriesResponse; +import com.google.monitoring.v3.TimeInterval; import com.google.monitoring.v3.TimeSeries; import com.google.protobuf.Empty; import io.grpc.ManagedChannel; @@ -68,8 +73,8 @@ *

  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -97,42 +102,34 @@ public class MetricServiceApi implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable< + private final UnaryCallable< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse> listMonitoredResourceDescriptorsCallable; - private final ApiCallable< - ListMonitoredResourceDescriptorsRequest, - PagedListResponse< - ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor>> + private final UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsPagedResponse> listMonitoredResourceDescriptorsPagedCallable; - private final ApiCallable + private final UnaryCallable getMonitoredResourceDescriptorCallable; - private final ApiCallable + private final UnaryCallable listMetricDescriptorsCallable; - private final ApiCallable< - ListMetricDescriptorsRequest, - PagedListResponse< - ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor>> + private final UnaryCallable listMetricDescriptorsPagedCallable; - private final ApiCallable + private final UnaryCallable getMetricDescriptorCallable; - private final ApiCallable + private final UnaryCallable createMetricDescriptorCallable; - private final ApiCallable deleteMetricDescriptorCallable; - private final ApiCallable listTimeSeriesCallable; - private final ApiCallable< - ListTimeSeriesRequest, - PagedListResponse> + private final UnaryCallable deleteMetricDescriptorCallable; + private final UnaryCallable listTimeSeriesCallable; + private final UnaryCallable listTimeSeriesPagedCallable; - private final ApiCallable createTimeSeriesCallable; + private final UnaryCallable createTimeSeriesCallable; private static final PathTemplate PROJECT_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding("projects/{project}"); - private static final PathTemplate METRIC_DESCRIPTOR_PATH_PATH_TEMPLATE = + private static final PathTemplate METRIC_DESCRIPTOR_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding( - "projects/{project}/metricDescriptors/{metric_descriptor_path=**}"); + "projects/{project}/metricDescriptors/{metric_descriptor=**}"); private static final PathTemplate MONITORED_RESOURCE_DESCRIPTOR_PATH_TEMPLATE = PathTemplate.createWithoutUrlEncoding( @@ -144,14 +141,12 @@ public static final String formatProjectName(String project) { } /** - * Formats a string containing the fully-qualified path to represent a metric_descriptor_path - * resource. + * Formats a string containing the fully-qualified path to represent a metric_descriptor resource. */ - public static final String formatMetricDescriptorPathName( - String project, String metricDescriptorPath) { - return METRIC_DESCRIPTOR_PATH_PATH_TEMPLATE.instantiate( + public static final String formatMetricDescriptorName(String project, String metricDescriptor) { + return METRIC_DESCRIPTOR_PATH_TEMPLATE.instantiate( "project", project, - "metric_descriptor_path", metricDescriptorPath); + "metric_descriptor", metricDescriptor); } /** @@ -171,23 +166,20 @@ public static final String parseProjectFromProjectName(String projectName) { } /** - * Parses the project from the given fully-qualified path which represents a metricDescriptorPath + * Parses the project from the given fully-qualified path which represents a metricDescriptor * resource. */ - public static final String parseProjectFromMetricDescriptorPathName( - String metricDescriptorPathName) { - return METRIC_DESCRIPTOR_PATH_PATH_TEMPLATE.parse(metricDescriptorPathName).get("project"); + public static final String parseProjectFromMetricDescriptorName(String metricDescriptorName) { + return METRIC_DESCRIPTOR_PATH_TEMPLATE.parse(metricDescriptorName).get("project"); } /** - * Parses the metric_descriptor_path from the given fully-qualified path which represents a - * metricDescriptorPath resource. + * Parses the metric_descriptor from the given fully-qualified path which represents a + * metricDescriptor resource. */ - public static final String parseMetricDescriptorPathFromMetricDescriptorPathName( - String metricDescriptorPathName) { - return METRIC_DESCRIPTOR_PATH_PATH_TEMPLATE - .parse(metricDescriptorPathName) - .get("metric_descriptor_path"); + public static final String parseMetricDescriptorFromMetricDescriptorName( + String metricDescriptorName) { + return METRIC_DESCRIPTOR_PATH_TEMPLATE.parse(metricDescriptorName).get("metric_descriptor"); } /** @@ -235,32 +227,34 @@ protected MetricServiceApi(MetricServiceSettings settings) throws IOException { this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.listMonitoredResourceDescriptorsCallable = - ApiCallable.create( + UnaryCallable.create( settings.listMonitoredResourceDescriptorsSettings(), this.channel, this.executor); this.listMonitoredResourceDescriptorsPagedCallable = - ApiCallable.createPagedVariant( + UnaryCallable.createPagedVariant( settings.listMonitoredResourceDescriptorsSettings(), this.channel, this.executor); this.getMonitoredResourceDescriptorCallable = - ApiCallable.create( + UnaryCallable.create( settings.getMonitoredResourceDescriptorSettings(), this.channel, this.executor); this.listMetricDescriptorsCallable = - ApiCallable.create(settings.listMetricDescriptorsSettings(), this.channel, this.executor); + UnaryCallable.create(settings.listMetricDescriptorsSettings(), this.channel, this.executor); this.listMetricDescriptorsPagedCallable = - ApiCallable.createPagedVariant( + UnaryCallable.createPagedVariant( settings.listMetricDescriptorsSettings(), this.channel, this.executor); this.getMetricDescriptorCallable = - ApiCallable.create(settings.getMetricDescriptorSettings(), this.channel, this.executor); + UnaryCallable.create(settings.getMetricDescriptorSettings(), this.channel, this.executor); this.createMetricDescriptorCallable = - ApiCallable.create(settings.createMetricDescriptorSettings(), this.channel, this.executor); + UnaryCallable.create( + settings.createMetricDescriptorSettings(), this.channel, this.executor); this.deleteMetricDescriptorCallable = - ApiCallable.create(settings.deleteMetricDescriptorSettings(), this.channel, this.executor); + UnaryCallable.create( + settings.deleteMetricDescriptorSettings(), this.channel, this.executor); this.listTimeSeriesCallable = - ApiCallable.create(settings.listTimeSeriesSettings(), this.channel, this.executor); + UnaryCallable.create(settings.listTimeSeriesSettings(), this.channel, this.executor); this.listTimeSeriesPagedCallable = - ApiCallable.createPagedVariant( + UnaryCallable.createPagedVariant( settings.listTimeSeriesSettings(), this.channel, this.executor); this.createTimeSeriesCallable = - ApiCallable.create(settings.createTimeSeriesSettings(), this.channel, this.executor); + UnaryCallable.create(settings.createTimeSeriesSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { closeables.add( @@ -296,8 +290,7 @@ public final MetricServiceSettings getSettings() { *

    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
        *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
    -   *   String filter = "";
    -   *   for (MonitoredResourceDescriptor element : metricServiceApi.listMonitoredResourceDescriptors(formattedName, filter).iterateAllElements()) {
    +   *   for (MonitoredResourceDescriptor element : metricServiceApi.listMonitoredResourceDescriptors(formattedName).iterateAllElements()) {
        *     // doThingsWith(element);
        *   }
        * }
    @@ -305,22 +298,13 @@ public final MetricServiceSettings getSettings() {
        *
        * @param name The project on which to execute the request. The format is
        *     `"projects/{project_id_or_number}"`.
    -   * @param filter An optional [filter](/monitoring/api/v3/filters) describing the descriptors to be
    -   *     returned. The filter can reference the descriptor's type and labels. For example, the
    -   *     following filter returns only Google Compute Engine descriptors that have an `id` label:
    -   *     

    resource.type = starts_with("gce_") AND resource.label:id * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse< - ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor> - listMonitoredResourceDescriptors(String name, String filter) { + public final ListMonitoredResourceDescriptorsPagedResponse listMonitoredResourceDescriptors( + String name) { PROJECT_PATH_TEMPLATE.validate(name, "listMonitoredResourceDescriptors"); ListMonitoredResourceDescriptorsRequest request = - ListMonitoredResourceDescriptorsRequest.newBuilder() - .setName(name) - .setFilter(filter) - .build(); + ListMonitoredResourceDescriptorsRequest.newBuilder().setName(name).build(); return listMonitoredResourceDescriptors(request); } @@ -334,10 +318,8 @@ public final MetricServiceSettings getSettings() { *

    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
        *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
    -   *   String filter = "";
        *   ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder()
        *     .setName(formattedName)
    -   *     .setFilter(filter)
        *     .build();
        *   for (MonitoredResourceDescriptor element : metricServiceApi.listMonitoredResourceDescriptors(request).iterateAllElements()) {
        *     // doThingsWith(element);
    @@ -348,10 +330,8 @@ public final MetricServiceSettings getSettings() {
        * @param request The request object containing all of the parameters for the API call.
        * @throws com.google.api.gax.grpc.ApiException if the remote call fails
        */
    -  public final PagedListResponse<
    -          ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse,
    -          MonitoredResourceDescriptor>
    -      listMonitoredResourceDescriptors(ListMonitoredResourceDescriptorsRequest request) {
    +  public final ListMonitoredResourceDescriptorsPagedResponse listMonitoredResourceDescriptors(
    +      ListMonitoredResourceDescriptorsRequest request) {
         return listMonitoredResourceDescriptorsPagedCallable().call(request);
       }
     
    @@ -365,12 +345,10 @@ public final MetricServiceSettings getSettings() {
        * 
    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
        *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
    -   *   String filter = "";
        *   ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder()
        *     .setName(formattedName)
    -   *     .setFilter(filter)
        *     .build();
    -   *   ListenableFuture<PagedListResponse<ListMonitoredResourceDescriptorsRequest,ListMonitoredResourceDescriptorsResponse,MonitoredResourceDescriptor>> future = metricServiceApi.listMonitoredResourceDescriptorsPagedCallable().futureCall(request);
    +   *   ListenableFuture<ListMonitoredResourceDescriptorsPagedResponse> future = metricServiceApi.listMonitoredResourceDescriptorsPagedCallable().futureCall(request);
        *   // Do something
        *   for (MonitoredResourceDescriptor element : future.get().iterateAllElements()) {
        *     // doThingsWith(element);
    @@ -378,11 +356,8 @@ public final MetricServiceSettings getSettings() {
        * }
        * 
    */ - public final ApiCallable< - ListMonitoredResourceDescriptorsRequest, - PagedListResponse< - ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor>> + public final UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsPagedResponse> listMonitoredResourceDescriptorsPagedCallable() { return listMonitoredResourceDescriptorsPagedCallable; } @@ -397,10 +372,8 @@ public final MetricServiceSettings getSettings() { *
    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
        *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
    -   *   String filter = "";
        *   ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder()
        *     .setName(formattedName)
    -   *     .setFilter(filter)
        *     .build();
        *   while (true) {
        *     ListMonitoredResourceDescriptorsResponse response = metricServiceApi.listMonitoredResourceDescriptorsCallable().call(request);
    @@ -417,7 +390,7 @@ public final MetricServiceSettings getSettings() {
        * }
        * 
    */ - public final ApiCallable< + public final UnaryCallable< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse> listMonitoredResourceDescriptorsCallable() { return listMonitoredResourceDescriptorsCallable; @@ -493,7 +466,7 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor( * } *
    */ - public final ApiCallable + public final UnaryCallable getMonitoredResourceDescriptorCallable() { return getMonitoredResourceDescriptorCallable; } @@ -508,8 +481,7 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor( *
    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
        *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
    -   *   String filter = "";
    -   *   for (MetricDescriptor element : metricServiceApi.listMetricDescriptors(formattedName, filter).iterateAllElements()) {
    +   *   for (MetricDescriptor element : metricServiceApi.listMetricDescriptors(formattedName).iterateAllElements()) {
        *     // doThingsWith(element);
        *   }
        * }
    @@ -517,19 +489,12 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor(
        *
        * @param name The project on which to execute the request. The format is
        *     `"projects/{project_id_or_number}"`.
    -   * @param filter If this field is empty, all custom and system-defined metric descriptors are
    -   *     returned. Otherwise, the [filter](/monitoring/api/v3/filters) specifies which metric
    -   *     descriptors are to be returned. For example, the following filter matches all [custom
    -   *     metrics](/monitoring/custom-metrics):
    -   *     

    metric.type = starts_with("custom.googleapis.com/") * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse< - ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor> - listMetricDescriptors(String name, String filter) { + public final ListMetricDescriptorsPagedResponse listMetricDescriptors(String name) { PROJECT_PATH_TEMPLATE.validate(name, "listMetricDescriptors"); ListMetricDescriptorsRequest request = - ListMetricDescriptorsRequest.newBuilder().setName(name).setFilter(filter).build(); + ListMetricDescriptorsRequest.newBuilder().setName(name).build(); return listMetricDescriptors(request); } @@ -543,10 +508,8 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor( *

    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
        *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
    -   *   String filter = "";
        *   ListMetricDescriptorsRequest request = ListMetricDescriptorsRequest.newBuilder()
        *     .setName(formattedName)
    -   *     .setFilter(filter)
        *     .build();
        *   for (MetricDescriptor element : metricServiceApi.listMetricDescriptors(request).iterateAllElements()) {
        *     // doThingsWith(element);
    @@ -557,9 +520,8 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor(
        * @param request The request object containing all of the parameters for the API call.
        * @throws com.google.api.gax.grpc.ApiException if the remote call fails
        */
    -  public final PagedListResponse<
    -          ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor>
    -      listMetricDescriptors(ListMetricDescriptorsRequest request) {
    +  public final ListMetricDescriptorsPagedResponse listMetricDescriptors(
    +      ListMetricDescriptorsRequest request) {
         return listMetricDescriptorsPagedCallable().call(request);
       }
     
    @@ -573,12 +535,10 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor(
        * 
    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
        *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
    -   *   String filter = "";
        *   ListMetricDescriptorsRequest request = ListMetricDescriptorsRequest.newBuilder()
        *     .setName(formattedName)
    -   *     .setFilter(filter)
        *     .build();
    -   *   ListenableFuture<PagedListResponse<ListMetricDescriptorsRequest,ListMetricDescriptorsResponse,MetricDescriptor>> future = metricServiceApi.listMetricDescriptorsPagedCallable().futureCall(request);
    +   *   ListenableFuture<ListMetricDescriptorsPagedResponse> future = metricServiceApi.listMetricDescriptorsPagedCallable().futureCall(request);
        *   // Do something
        *   for (MetricDescriptor element : future.get().iterateAllElements()) {
        *     // doThingsWith(element);
    @@ -586,10 +546,7 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor(
        * }
        * 
    */ - public final ApiCallable< - ListMetricDescriptorsRequest, - PagedListResponse< - ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor>> + public final UnaryCallable listMetricDescriptorsPagedCallable() { return listMetricDescriptorsPagedCallable; } @@ -604,10 +561,8 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor( *
    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
        *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
    -   *   String filter = "";
        *   ListMetricDescriptorsRequest request = ListMetricDescriptorsRequest.newBuilder()
        *     .setName(formattedName)
    -   *     .setFilter(filter)
        *     .build();
        *   while (true) {
        *     ListMetricDescriptorsResponse response = metricServiceApi.listMetricDescriptorsCallable().call(request);
    @@ -624,7 +579,7 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor(
        * }
        * 
    */ - public final ApiCallable + public final UnaryCallable listMetricDescriptorsCallable() { return listMetricDescriptorsCallable; } @@ -637,7 +592,7 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor( * *
    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    -   *   String formattedName = MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]");
    +   *   String formattedName = MetricServiceApi.formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
        *   MetricDescriptor response = metricServiceApi.getMetricDescriptor(formattedName);
        * }
        * 
    @@ -648,7 +603,7 @@ private final MonitoredResourceDescriptor getMonitoredResourceDescriptor( * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final MetricDescriptor getMetricDescriptor(String name) { - METRIC_DESCRIPTOR_PATH_PATH_TEMPLATE.validate(name, "getMetricDescriptor"); + METRIC_DESCRIPTOR_PATH_TEMPLATE.validate(name, "getMetricDescriptor"); GetMetricDescriptorRequest request = GetMetricDescriptorRequest.newBuilder().setName(name).build(); return getMetricDescriptor(request); @@ -662,7 +617,7 @@ public final MetricDescriptor getMetricDescriptor(String name) { * *
    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    -   *   String formattedName = MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]");
    +   *   String formattedName = MetricServiceApi.formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
        *   GetMetricDescriptorRequest request = GetMetricDescriptorRequest.newBuilder()
        *     .setName(formattedName)
        *     .build();
    @@ -685,7 +640,7 @@ private final MetricDescriptor getMetricDescriptor(GetMetricDescriptorRequest re
        *
        * 
    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    -   *   String formattedName = MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]");
    +   *   String formattedName = MetricServiceApi.formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
        *   GetMetricDescriptorRequest request = GetMetricDescriptorRequest.newBuilder()
        *     .setName(formattedName)
        *     .build();
    @@ -695,7 +650,7 @@ private final MetricDescriptor getMetricDescriptor(GetMetricDescriptorRequest re
        * }
        * 
    */ - public final ApiCallable + public final UnaryCallable getMetricDescriptorCallable() { return getMetricDescriptorCallable; } @@ -778,7 +733,7 @@ public final MetricDescriptor createMetricDescriptor(CreateMetricDescriptorReque * } *
    */ - public final ApiCallable + public final UnaryCallable createMetricDescriptorCallable() { return createMetricDescriptorCallable; } @@ -792,7 +747,7 @@ public final MetricDescriptor createMetricDescriptor(CreateMetricDescriptorReque * *
    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    -   *   String formattedName = MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]");
    +   *   String formattedName = MetricServiceApi.formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
        *   metricServiceApi.deleteMetricDescriptor(formattedName);
        * }
        * 
    @@ -803,7 +758,7 @@ public final MetricDescriptor createMetricDescriptor(CreateMetricDescriptorReque * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final void deleteMetricDescriptor(String name) { - METRIC_DESCRIPTOR_PATH_PATH_TEMPLATE.validate(name, "deleteMetricDescriptor"); + METRIC_DESCRIPTOR_PATH_TEMPLATE.validate(name, "deleteMetricDescriptor"); DeleteMetricDescriptorRequest request = DeleteMetricDescriptorRequest.newBuilder().setName(name).build(); deleteMetricDescriptor(request); @@ -818,7 +773,7 @@ public final void deleteMetricDescriptor(String name) { * *
    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    -   *   String formattedName = MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]");
    +   *   String formattedName = MetricServiceApi.formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
        *   DeleteMetricDescriptorRequest request = DeleteMetricDescriptorRequest.newBuilder()
        *     .setName(formattedName)
        *     .build();
    @@ -842,7 +797,7 @@ private final void deleteMetricDescriptor(DeleteMetricDescriptorRequest request)
        *
        * 
    
        * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    -   *   String formattedName = MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]");
    +   *   String formattedName = MetricServiceApi.formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]");
        *   DeleteMetricDescriptorRequest request = DeleteMetricDescriptorRequest.newBuilder()
        *     .setName(formattedName)
        *     .build();
    @@ -852,7 +807,8 @@ private final void deleteMetricDescriptor(DeleteMetricDescriptorRequest request)
        * }
        * 
    */ - public final ApiCallable deleteMetricDescriptorCallable() { + public final UnaryCallable + deleteMetricDescriptorCallable() { return deleteMetricDescriptorCallable; } @@ -867,15 +823,57 @@ public final ApiCallable deleteMetricDescr * String formattedName = MetricServiceApi.formatProjectName("[PROJECT]"); * String filter = ""; * TimeInterval interval = TimeInterval.newBuilder().build(); - * Aggregation aggregation = Aggregation.newBuilder().build(); - * String orderBy = ""; + * ListTimeSeriesRequest.TimeSeriesView view = ListTimeSeriesRequest.TimeSeriesView.FULL; + * for (TimeSeries element : metricServiceApi.listTimeSeries(formattedName, filter, interval, view).iterateAllElements()) { + * // doThingsWith(element); + * } + * } + *
    + * + * @param name The project on which to execute the request. The format is + * "projects/{project_id_or_number}". + * @param filter A [monitoring filter](/monitoring/api/v3/filters) that specifies which time + * series should be returned. The filter must specify a single metric type, and can + * additionally specify metric labels and other information. For example: + *

    metric.type = "compute.googleapis.com/instance/cpu/usage_time" AND + * metric.label.instance_name = "my-instance-name" + * @param interval The time interval for which results should be returned. Only time series that + * contain data points in the specified interval are included in the response. + * @param view Specifies which information is returned about the time series. + * @throws com.google.api.gax.grpc.ApiException if the remote call fails + */ + public final ListTimeSeriesPagedResponse listTimeSeries( + String name, + String filter, + TimeInterval interval, + ListTimeSeriesRequest.TimeSeriesView view) { + PROJECT_PATH_TEMPLATE.validate(name, "listTimeSeries"); + ListTimeSeriesRequest request = + ListTimeSeriesRequest.newBuilder() + .setName(name) + .setFilter(filter) + .setInterval(interval) + .setView(view) + .build(); + return listTimeSeries(request); + } + + // AUTO-GENERATED DOCUMENTATION AND METHOD + /** + * Lists time series that match a filter. This method does not require a Stackdriver account. + * + *

    Sample code: + * + *

    
    +   * try (MetricServiceApi metricServiceApi = MetricServiceApi.create()) {
    +   *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
    +   *   String filter = "";
    +   *   TimeInterval interval = TimeInterval.newBuilder().build();
        *   ListTimeSeriesRequest.TimeSeriesView view = ListTimeSeriesRequest.TimeSeriesView.FULL;
        *   ListTimeSeriesRequest request = ListTimeSeriesRequest.newBuilder()
        *     .setName(formattedName)
        *     .setFilter(filter)
        *     .setInterval(interval)
    -   *     .setAggregation(aggregation)
    -   *     .setOrderBy(orderBy)
        *     .setView(view)
        *     .build();
        *   for (TimeSeries element : metricServiceApi.listTimeSeries(request).iterateAllElements()) {
    @@ -887,8 +885,7 @@ public final ApiCallable deleteMetricDescr
        * @param request The request object containing all of the parameters for the API call.
        * @throws com.google.api.gax.grpc.ApiException if the remote call fails
        */
    -  public final PagedListResponse
    -      listTimeSeries(ListTimeSeriesRequest request) {
    +  public final ListTimeSeriesPagedResponse listTimeSeries(ListTimeSeriesRequest request) {
         return listTimeSeriesPagedCallable().call(request);
       }
     
    @@ -903,18 +900,14 @@ public final ApiCallable deleteMetricDescr
        *   String formattedName = MetricServiceApi.formatProjectName("[PROJECT]");
        *   String filter = "";
        *   TimeInterval interval = TimeInterval.newBuilder().build();
    -   *   Aggregation aggregation = Aggregation.newBuilder().build();
    -   *   String orderBy = "";
        *   ListTimeSeriesRequest.TimeSeriesView view = ListTimeSeriesRequest.TimeSeriesView.FULL;
        *   ListTimeSeriesRequest request = ListTimeSeriesRequest.newBuilder()
        *     .setName(formattedName)
        *     .setFilter(filter)
        *     .setInterval(interval)
    -   *     .setAggregation(aggregation)
    -   *     .setOrderBy(orderBy)
        *     .setView(view)
        *     .build();
    -   *   ListenableFuture<PagedListResponse<ListTimeSeriesRequest,ListTimeSeriesResponse,TimeSeries>> future = metricServiceApi.listTimeSeriesPagedCallable().futureCall(request);
    +   *   ListenableFuture<ListTimeSeriesPagedResponse> future = metricServiceApi.listTimeSeriesPagedCallable().futureCall(request);
        *   // Do something
        *   for (TimeSeries element : future.get().iterateAllElements()) {
        *     // doThingsWith(element);
    @@ -922,9 +915,7 @@ public final ApiCallable deleteMetricDescr
        * }
        * 
    */ - public final ApiCallable< - ListTimeSeriesRequest, - PagedListResponse> + public final UnaryCallable listTimeSeriesPagedCallable() { return listTimeSeriesPagedCallable; } @@ -940,15 +931,11 @@ public final ApiCallable deleteMetricDescr * String formattedName = MetricServiceApi.formatProjectName("[PROJECT]"); * String filter = ""; * TimeInterval interval = TimeInterval.newBuilder().build(); - * Aggregation aggregation = Aggregation.newBuilder().build(); - * String orderBy = ""; * ListTimeSeriesRequest.TimeSeriesView view = ListTimeSeriesRequest.TimeSeriesView.FULL; * ListTimeSeriesRequest request = ListTimeSeriesRequest.newBuilder() * .setName(formattedName) * .setFilter(filter) * .setInterval(interval) - * .setAggregation(aggregation) - * .setOrderBy(orderBy) * .setView(view) * .build(); * while (true) { @@ -966,7 +953,8 @@ public final ApiCallable deleteMetricDescr * } *
    */ - public final ApiCallable listTimeSeriesCallable() { + public final UnaryCallable + listTimeSeriesCallable() { return listTimeSeriesCallable; } @@ -1050,7 +1038,7 @@ public final void createTimeSeries(CreateTimeSeriesRequest request) { * } *
    */ - public final ApiCallable createTimeSeriesCallable() { + public final UnaryCallable createTimeSeriesCallable() { return createTimeSeriesCallable; } diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceSettings.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceSettings.java index c7c89badb66d..a2a86ed5c0ff 100644 --- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceSettings.java +++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/MetricServiceSettings.java @@ -13,15 +13,22 @@ */ package com.google.cloud.monitoring.spi.v3; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListMetricDescriptorsPagedResponse; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListMonitoredResourceDescriptorsPagedResponse; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListTimeSeriesPagedResponse; + import com.google.api.MetricDescriptor; import com.google.api.MonitoredResourceDescriptor; import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; -import com.google.api.gax.grpc.PageStreamingCallSettings; -import com.google.api.gax.grpc.PageStreamingDescriptor; +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedCallSettings; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseFactory; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; +import com.google.api.gax.grpc.UnaryCallable; import com.google.auth.Credentials; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -87,23 +94,16 @@ public class MetricServiceSettings extends ServiceApiSettings { private static final ImmutableList DEFAULT_SERVICE_SCOPES = ImmutableList.builder().build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - - private final PageStreamingCallSettings< + private final PagedCallSettings< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor> + ListMonitoredResourceDescriptorsPagedResponse> listMonitoredResourceDescriptorsSettings; private final SimpleCallSettings< GetMonitoredResourceDescriptorRequest, MonitoredResourceDescriptor> getMonitoredResourceDescriptorSettings; - private final PageStreamingCallSettings< - ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor> + private final PagedCallSettings< + ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, + ListMetricDescriptorsPagedResponse> listMetricDescriptorsSettings; private final SimpleCallSettings getMetricDescriptorSettings; @@ -111,14 +111,15 @@ public class MetricServiceSettings extends ServiceApiSettings { createMetricDescriptorSettings; private final SimpleCallSettings deleteMetricDescriptorSettings; - private final PageStreamingCallSettings + private final PagedCallSettings< + ListTimeSeriesRequest, ListTimeSeriesResponse, ListTimeSeriesPagedResponse> listTimeSeriesSettings; private final SimpleCallSettings createTimeSeriesSettings; /** Returns the object with the settings used for calls to listMonitoredResourceDescriptors. */ - public PageStreamingCallSettings< + public PagedCallSettings< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor> + ListMonitoredResourceDescriptorsPagedResponse> listMonitoredResourceDescriptorsSettings() { return listMonitoredResourceDescriptorsSettings; } @@ -130,8 +131,9 @@ public class MetricServiceSettings extends ServiceApiSettings { } /** Returns the object with the settings used for calls to listMetricDescriptors. */ - public PageStreamingCallSettings< - ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor> + public PagedCallSettings< + ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, + ListMetricDescriptorsPagedResponse> listMetricDescriptorsSettings() { return listMetricDescriptorsSettings; } @@ -154,7 +156,8 @@ public SimpleCallSettings deleteMetricDesc } /** Returns the object with the settings used for calls to listTimeSeries. */ - public PageStreamingCallSettings + public PagedCallSettings< + ListTimeSeriesRequest, ListTimeSeriesResponse, ListTimeSeriesPagedResponse> listTimeSeriesSettings() { return listTimeSeriesSettings; } @@ -215,11 +218,11 @@ private MetricServiceSettings(Builder settingsBuilder) throws IOException { createTimeSeriesSettings = settingsBuilder.createTimeSeriesSettings().build(); } - private static final PageStreamingDescriptor< + private static final PagedListDescriptor< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor> LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC = - new PageStreamingDescriptor< + new PagedListDescriptor< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, MonitoredResourceDescriptor>() { @Override @@ -260,10 +263,10 @@ public Iterable extractResources( } }; - private static final PageStreamingDescriptor< + private static final PagedListDescriptor< ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor> LIST_METRIC_DESCRIPTORS_PAGE_STR_DESC = - new PageStreamingDescriptor< + new PagedListDescriptor< ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor>() { @Override public Object emptyToken() { @@ -301,10 +304,10 @@ public Iterable extractResources( } }; - private static final PageStreamingDescriptor< + private static final PagedListDescriptor< ListTimeSeriesRequest, ListTimeSeriesResponse, TimeSeries> LIST_TIME_SERIES_PAGE_STR_DESC = - new PageStreamingDescriptor() { + new PagedListDescriptor() { @Override public Object emptyToken() { return ""; @@ -337,19 +340,72 @@ public Iterable extractResources(ListTimeSeriesResponse payload) { } }; + private static final PagedListResponseFactory< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, + ListMonitoredResourceDescriptorsPagedResponse> + LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, + ListMonitoredResourceDescriptorsPagedResponse>() { + @Override + public ListMonitoredResourceDescriptorsPagedResponse createPagedListResponse( + UnaryCallable< + ListMonitoredResourceDescriptorsRequest, + ListMonitoredResourceDescriptorsResponse> + callable, + ListMonitoredResourceDescriptorsRequest request, + CallContext context) { + return new ListMonitoredResourceDescriptorsPagedResponse( + callable, LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC, request, context); + } + }; + + private static final PagedListResponseFactory< + ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, + ListMetricDescriptorsPagedResponse> + LIST_METRIC_DESCRIPTORS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, + ListMetricDescriptorsPagedResponse>() { + @Override + public ListMetricDescriptorsPagedResponse createPagedListResponse( + UnaryCallable callable, + ListMetricDescriptorsRequest request, + CallContext context) { + return new ListMetricDescriptorsPagedResponse( + callable, LIST_METRIC_DESCRIPTORS_PAGE_STR_DESC, request, context); + } + }; + + private static final PagedListResponseFactory< + ListTimeSeriesRequest, ListTimeSeriesResponse, ListTimeSeriesPagedResponse> + LIST_TIME_SERIES_PAGE_STR_FACT = + new PagedListResponseFactory< + ListTimeSeriesRequest, ListTimeSeriesResponse, ListTimeSeriesPagedResponse>() { + @Override + public ListTimeSeriesPagedResponse createPagedListResponse( + UnaryCallable callable, + ListTimeSeriesRequest request, + CallContext context) { + return new ListTimeSeriesPagedResponse( + callable, LIST_TIME_SERIES_PAGE_STR_DESC, request, context); + } + }; + /** Builder for MetricServiceSettings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; - private final PageStreamingCallSettings.Builder< + private final PagedCallSettings.Builder< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor> + ListMonitoredResourceDescriptorsPagedResponse> listMonitoredResourceDescriptorsSettings; private final SimpleCallSettings.Builder< GetMonitoredResourceDescriptorRequest, MonitoredResourceDescriptor> getMonitoredResourceDescriptorSettings; - private final PageStreamingCallSettings.Builder< - ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor> + private final PagedCallSettings.Builder< + ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, + ListMetricDescriptorsPagedResponse> listMetricDescriptorsSettings; private final SimpleCallSettings.Builder getMetricDescriptorSettings; @@ -357,8 +413,8 @@ public static class Builder extends ServiceApiSettings.Builder { createMetricDescriptorSettings; private final SimpleCallSettings.Builder deleteMetricDescriptorSettings; - private final PageStreamingCallSettings.Builder< - ListTimeSeriesRequest, ListTimeSeriesResponse, TimeSeries> + private final PagedCallSettings.Builder< + ListTimeSeriesRequest, ListTimeSeriesResponse, ListTimeSeriesPagedResponse> listTimeSeriesSettings; private final SimpleCallSettings.Builder createTimeSeriesSettings; @@ -395,20 +451,20 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); listMonitoredResourceDescriptorsSettings = - PageStreamingCallSettings.newBuilder( + PagedCallSettings.newBuilder( MetricServiceGrpc.METHOD_LIST_MONITORED_RESOURCE_DESCRIPTORS, - LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_DESC); + LIST_MONITORED_RESOURCE_DESCRIPTORS_PAGE_STR_FACT); getMonitoredResourceDescriptorSettings = SimpleCallSettings.newBuilder(MetricServiceGrpc.METHOD_GET_MONITORED_RESOURCE_DESCRIPTOR); listMetricDescriptorsSettings = - PageStreamingCallSettings.newBuilder( + PagedCallSettings.newBuilder( MetricServiceGrpc.METHOD_LIST_METRIC_DESCRIPTORS, - LIST_METRIC_DESCRIPTORS_PAGE_STR_DESC); + LIST_METRIC_DESCRIPTORS_PAGE_STR_FACT); getMetricDescriptorSettings = SimpleCallSettings.newBuilder(MetricServiceGrpc.METHOD_GET_METRIC_DESCRIPTOR); @@ -420,14 +476,14 @@ private Builder() { SimpleCallSettings.newBuilder(MetricServiceGrpc.METHOD_DELETE_METRIC_DESCRIPTOR); listTimeSeriesSettings = - PageStreamingCallSettings.newBuilder( - MetricServiceGrpc.METHOD_LIST_TIME_SERIES, LIST_TIME_SERIES_PAGE_STR_DESC); + PagedCallSettings.newBuilder( + MetricServiceGrpc.METHOD_LIST_TIME_SERIES, LIST_TIME_SERIES_PAGE_STR_FACT); createTimeSeriesSettings = SimpleCallSettings.newBuilder(MetricServiceGrpc.METHOD_CREATE_TIME_SERIES); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( listMonitoredResourceDescriptorsSettings, getMonitoredResourceDescriptorSettings, listMetricDescriptorsSettings, @@ -498,8 +554,8 @@ private Builder(MetricServiceSettings settings) { listTimeSeriesSettings = settings.listTimeSeriesSettings.toBuilder(); createTimeSeriesSettings = settings.createTimeSeriesSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( listMonitoredResourceDescriptorsSettings, getMonitoredResourceDescriptorSettings, listMetricDescriptorsSettings, @@ -510,9 +566,16 @@ private Builder(MetricServiceSettings settings) { createTimeSeriesSettings); } + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); + } + @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -558,18 +621,21 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } /** Returns the builder for the settings used for calls to listMonitoredResourceDescriptors. */ - public PageStreamingCallSettings.Builder< + public PagedCallSettings.Builder< ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor> + ListMonitoredResourceDescriptorsPagedResponse> listMonitoredResourceDescriptorsSettings() { return listMonitoredResourceDescriptorsSettings; } @@ -582,8 +648,9 @@ public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) thr } /** Returns the builder for the settings used for calls to listMetricDescriptors. */ - public PageStreamingCallSettings.Builder< - ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor> + public PagedCallSettings.Builder< + ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, + ListMetricDescriptorsPagedResponse> listMetricDescriptorsSettings() { return listMetricDescriptorsSettings; } @@ -607,8 +674,8 @@ public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) thr } /** Returns the builder for the settings used for calls to listTimeSeries. */ - public PageStreamingCallSettings.Builder< - ListTimeSeriesRequest, ListTimeSeriesResponse, TimeSeries> + public PagedCallSettings.Builder< + ListTimeSeriesRequest, ListTimeSeriesResponse, ListTimeSeriesPagedResponse> listTimeSeriesSettings() { return listTimeSeriesSettings; } diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/PagedResponseWrappers.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/PagedResponseWrappers.java new file mode 100644 index 000000000000..17c4060a8297 --- /dev/null +++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/PagedResponseWrappers.java @@ -0,0 +1,117 @@ +/* + * 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.cloud.monitoring.spi.v3; + +import com.google.api.MetricDescriptor; +import com.google.api.MonitoredResource; +import com.google.api.MonitoredResourceDescriptor; +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseImpl; +import com.google.api.gax.grpc.UnaryCallable; +import com.google.monitoring.v3.Group; +import com.google.monitoring.v3.ListGroupMembersRequest; +import com.google.monitoring.v3.ListGroupMembersResponse; +import com.google.monitoring.v3.ListGroupsRequest; +import com.google.monitoring.v3.ListGroupsResponse; +import com.google.monitoring.v3.ListMetricDescriptorsRequest; +import com.google.monitoring.v3.ListMetricDescriptorsResponse; +import com.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest; +import com.google.monitoring.v3.ListMonitoredResourceDescriptorsResponse; +import com.google.monitoring.v3.ListTimeSeriesRequest; +import com.google.monitoring.v3.ListTimeSeriesResponse; +import com.google.monitoring.v3.TimeSeries; + +// AUTO-GENERATED DOCUMENTATION AND CLASS +/** + * Wrapper class to contain paged response types for page streaming methods. Each static class + * inside this wrapper class is used as the return type of one of an API method that implements the + * page streaming pattern. + */ +@javax.annotation.Generated("by GAPIC") +public class PagedResponseWrappers { + + public static class ListGroupsPagedResponse + extends PagedListResponseImpl { + + public ListGroupsPagedResponse( + UnaryCallable callable, + PagedListDescriptor pageDescriptor, + ListGroupsRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } + + public static class ListGroupMembersPagedResponse + extends PagedListResponseImpl< + ListGroupMembersRequest, ListGroupMembersResponse, MonitoredResource> { + + public ListGroupMembersPagedResponse( + UnaryCallable callable, + PagedListDescriptor + pageDescriptor, + ListGroupMembersRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } + + public static class ListMonitoredResourceDescriptorsPagedResponse + extends PagedListResponseImpl< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor> { + + public ListMonitoredResourceDescriptorsPagedResponse( + UnaryCallable< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse> + callable, + PagedListDescriptor< + ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, + MonitoredResourceDescriptor> + pageDescriptor, + ListMonitoredResourceDescriptorsRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } + + public static class ListMetricDescriptorsPagedResponse + extends PagedListResponseImpl< + ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor> { + + public ListMetricDescriptorsPagedResponse( + UnaryCallable callable, + PagedListDescriptor< + ListMetricDescriptorsRequest, ListMetricDescriptorsResponse, MetricDescriptor> + pageDescriptor, + ListMetricDescriptorsRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } + + public static class ListTimeSeriesPagedResponse + extends PagedListResponseImpl { + + public ListTimeSeriesPagedResponse( + UnaryCallable callable, + PagedListDescriptor + pageDescriptor, + ListTimeSeriesRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } +} diff --git a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/package-info.java b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/package-info.java index 9d1a0e61adb7..e1ea3fad62e0 100644 --- a/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/package-info.java +++ b/google-cloud-monitoring/src/main/java/com/google/cloud/monitoring/spi/v3/package-info.java @@ -15,7 +15,7 @@ /** * A client to Stackdriver Monitoring API. * - *

    The interfaces provided are listed below, along with a usage sample + *

    The interfaces provided are listed below, along with usage samples. * *

    =============== GroupServiceApi =============== * @@ -55,25 +55,5 @@ * } * *

    - * - * ========================== AgentTranslationServiceApi ========================== - * - *

    Service Description: The AgentTranslation API allows `collectd`-based agents to write time - * series data to Cloud Monitoring. See [google.monitoring.v3.MetricService.CreateTimeSeries] - * instead. - * - *

    Sample for AgentTranslationServiceApi: - * - *

    - * 
    - * try (AgentTranslationServiceApi agentTranslationServiceApi = AgentTranslationServiceApi.create()) {
    - *   String formattedName = AgentTranslationServiceApi.formatProjectName("[PROJECT]");
    - *   MonitoredResource resource = MonitoredResource.newBuilder().build();
    - *   String collectdVersion = "";
    - *   List<CollectdPayload> collectdPayloads = new ArrayList<>();
    - *   agentTranslationServiceApi.createCollectdTimeSeries(formattedName, resource, collectdVersion, collectdPayloads);
    - * }
    - * 
    - * 
    */ package com.google.cloud.monitoring.spi.v3; diff --git a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceTest.java b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceTest.java deleted file mode 100644 index 5e622b537d0e..000000000000 --- a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/AgentTranslationServiceTest.java +++ /dev/null @@ -1,101 +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.cloud.monitoring.spi.v3; - -import com.google.api.MonitoredResource; -import com.google.api.gax.testing.MockGrpcService; -import com.google.api.gax.testing.MockServiceHelper; -import com.google.monitoring.v3.CollectdPayload; -import com.google.monitoring.v3.CreateCollectdTimeSeriesRequest; -import com.google.protobuf.Empty; -import com.google.protobuf.GeneratedMessageV3; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; - -@javax.annotation.Generated("by GAPIC") -public class AgentTranslationServiceTest { - private static MockGroupService mockGroupService; - private static MockMetricService mockMetricService; - private static MockAgentTranslationService mockAgentTranslationService; - private static MockServiceHelper serviceHelper; - private AgentTranslationServiceApi api; - - @BeforeClass - public static void startStaticServer() { - mockGroupService = new MockGroupService(); - mockMetricService = new MockMetricService(); - mockAgentTranslationService = new MockAgentTranslationService(); - serviceHelper = - new MockServiceHelper( - "in-process-1", - Arrays.asList( - mockGroupService, mockMetricService, mockAgentTranslationService)); - serviceHelper.start(); - } - - @AfterClass - public static void stopServer() { - serviceHelper.stop(); - } - - @Before - public void setUp() throws IOException { - serviceHelper.reset(); - AgentTranslationServiceSettings settings = - AgentTranslationServiceSettings.defaultBuilder() - .provideChannelWith(serviceHelper.createChannel(), true) - .build(); - api = AgentTranslationServiceApi.create(settings); - } - - @After - public void tearDown() throws Exception { - api.close(); - } - - @Test - @SuppressWarnings("all") - public void createCollectdTimeSeriesTest() { - Empty expectedResponse = Empty.newBuilder().build(); - List expectedResponses = new ArrayList<>(); - expectedResponses.add(expectedResponse); - mockAgentTranslationService.setResponses(expectedResponses); - - String formattedName = AgentTranslationServiceApi.formatProjectName("[PROJECT]"); - MonitoredResource resource = MonitoredResource.newBuilder().build(); - String collectdVersion = "collectdVersion-177050093"; - List collectdPayloads = new ArrayList<>(); - - api.createCollectdTimeSeries(formattedName, resource, collectdVersion, collectdPayloads); - - List actualRequests = mockAgentTranslationService.getRequests(); - Assert.assertEquals(1, actualRequests.size()); - CreateCollectdTimeSeriesRequest actualRequest = - (CreateCollectdTimeSeriesRequest) actualRequests.get(0); - - Assert.assertEquals(formattedName, actualRequest.getName()); - Assert.assertEquals(resource, actualRequest.getResource()); - Assert.assertEquals(collectdVersion, actualRequest.getCollectdVersion()); - Assert.assertEquals(collectdPayloads, actualRequest.getCollectdPayloadsList()); - } -} diff --git a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/GroupServiceTest.java b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/GroupServiceTest.java index c3944b8cb0af..016bbc63b15b 100644 --- a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/GroupServiceTest.java +++ b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/GroupServiceTest.java @@ -14,8 +14,9 @@ package com.google.cloud.monitoring.spi.v3; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListGroupMembersPagedResponse; + import com.google.api.MonitoredResource; -import com.google.api.gax.core.PagedListResponse; import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; import com.google.common.collect.Lists; @@ -25,7 +26,6 @@ import com.google.monitoring.v3.Group; import com.google.monitoring.v3.ListGroupMembersRequest; import com.google.monitoring.v3.ListGroupMembersResponse; -import com.google.monitoring.v3.TimeInterval; import com.google.monitoring.v3.UpdateGroupRequest; import com.google.protobuf.Empty; import com.google.protobuf.GeneratedMessageV3; @@ -44,7 +44,6 @@ public class GroupServiceTest { private static MockGroupService mockGroupService; private static MockMetricService mockMetricService; - private static MockAgentTranslationService mockAgentTranslationService; private static MockServiceHelper serviceHelper; private GroupServiceApi api; @@ -52,12 +51,9 @@ public class GroupServiceTest { public static void startStaticServer() { mockGroupService = new MockGroupService(); mockMetricService = new MockMetricService(); - mockAgentTranslationService = new MockAgentTranslationService(); serviceHelper = new MockServiceHelper( - "in-process-1", - Arrays.asList( - mockGroupService, mockMetricService, mockAgentTranslationService)); + "in-process-1", Arrays.asList(mockGroupService, mockMetricService)); serviceHelper.start(); } @@ -135,9 +131,8 @@ public void createGroupTest() { String formattedName = GroupServiceApi.formatProjectName("[PROJECT]"); Group group = Group.newBuilder().build(); - boolean validateOnly = false; - Group actualResponse = api.createGroup(formattedName, group, validateOnly); + Group actualResponse = api.createGroup(formattedName, group); Assert.assertEquals(expectedResponse, actualResponse); List actualRequests = mockGroupService.getRequests(); @@ -146,7 +141,6 @@ public void createGroupTest() { Assert.assertEquals(formattedName, actualRequest.getName()); Assert.assertEquals(group, actualRequest.getGroup()); - Assert.assertEquals(validateOnly, actualRequest.getValidateOnly()); } @Test @@ -170,9 +164,8 @@ public void updateGroupTest() { mockGroupService.setResponses(expectedResponses); Group group = Group.newBuilder().build(); - boolean validateOnly = false; - Group actualResponse = api.updateGroup(group, validateOnly); + Group actualResponse = api.updateGroup(group); Assert.assertEquals(expectedResponse, actualResponse); List actualRequests = mockGroupService.getRequests(); @@ -180,7 +173,6 @@ public void updateGroupTest() { UpdateGroupRequest actualRequest = (UpdateGroupRequest) actualRequests.get(0); Assert.assertEquals(group, actualRequest.getGroup()); - Assert.assertEquals(validateOnly, actualRequest.getValidateOnly()); } @Test @@ -220,11 +212,8 @@ public void listGroupMembersTest() { mockGroupService.setResponses(expectedResponses); String formattedName = GroupServiceApi.formatGroupName("[PROJECT]", "[GROUP]"); - String filter = "filter-1274492040"; - TimeInterval interval = TimeInterval.newBuilder().build(); - PagedListResponse - pagedListResponse = api.listGroupMembers(formattedName, filter, interval); + ListGroupMembersPagedResponse pagedListResponse = api.listGroupMembers(formattedName); List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); Assert.assertEquals(1, resources.size()); @@ -235,7 +224,5 @@ public void listGroupMembersTest() { ListGroupMembersRequest actualRequest = (ListGroupMembersRequest) actualRequests.get(0); Assert.assertEquals(formattedName, actualRequest.getName()); - Assert.assertEquals(filter, actualRequest.getFilter()); - Assert.assertEquals(interval, actualRequest.getInterval()); } } diff --git a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MetricServiceTest.java b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MetricServiceTest.java index fa8034b62219..d3a671e3a5d5 100644 --- a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MetricServiceTest.java +++ b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MetricServiceTest.java @@ -14,9 +14,12 @@ package com.google.cloud.monitoring.spi.v3; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListMetricDescriptorsPagedResponse; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListMonitoredResourceDescriptorsPagedResponse; +import static com.google.cloud.monitoring.spi.v3.PagedResponseWrappers.ListTimeSeriesPagedResponse; + import com.google.api.MetricDescriptor; import com.google.api.MonitoredResourceDescriptor; -import com.google.api.gax.core.PagedListResponse; import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; import com.google.common.collect.Lists; @@ -29,6 +32,10 @@ import com.google.monitoring.v3.ListMetricDescriptorsResponse; import com.google.monitoring.v3.ListMonitoredResourceDescriptorsRequest; import com.google.monitoring.v3.ListMonitoredResourceDescriptorsResponse; +import com.google.monitoring.v3.ListTimeSeriesRequest; +import com.google.monitoring.v3.ListTimeSeriesRequest.TimeSeriesView; +import com.google.monitoring.v3.ListTimeSeriesResponse; +import com.google.monitoring.v3.TimeInterval; import com.google.monitoring.v3.TimeSeries; import com.google.protobuf.Empty; import com.google.protobuf.GeneratedMessageV3; @@ -47,7 +54,6 @@ public class MetricServiceTest { private static MockGroupService mockGroupService; private static MockMetricService mockMetricService; - private static MockAgentTranslationService mockAgentTranslationService; private static MockServiceHelper serviceHelper; private MetricServiceApi api; @@ -55,12 +61,9 @@ public class MetricServiceTest { public static void startStaticServer() { mockGroupService = new MockGroupService(); mockMetricService = new MockMetricService(); - mockAgentTranslationService = new MockAgentTranslationService(); serviceHelper = new MockServiceHelper( - "in-process-1", - Arrays.asList( - mockGroupService, mockMetricService, mockAgentTranslationService)); + "in-process-1", Arrays.asList(mockGroupService, mockMetricService)); serviceHelper.start(); } @@ -102,12 +105,9 @@ public void listMonitoredResourceDescriptorsTest() { mockMetricService.setResponses(expectedResponses); String formattedName = MetricServiceApi.formatProjectName("[PROJECT]"); - String filter = "filter-1274492040"; - PagedListResponse< - ListMonitoredResourceDescriptorsRequest, ListMonitoredResourceDescriptorsResponse, - MonitoredResourceDescriptor> - pagedListResponse = api.listMonitoredResourceDescriptors(formattedName, filter); + ListMonitoredResourceDescriptorsPagedResponse pagedListResponse = + api.listMonitoredResourceDescriptors(formattedName); List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); @@ -120,7 +120,6 @@ public void listMonitoredResourceDescriptorsTest() { (ListMonitoredResourceDescriptorsRequest) actualRequests.get(0); Assert.assertEquals(formattedName, actualRequest.getName()); - Assert.assertEquals(filter, actualRequest.getFilter()); } @Test @@ -174,10 +173,8 @@ public void listMetricDescriptorsTest() { mockMetricService.setResponses(expectedResponses); String formattedName = MetricServiceApi.formatProjectName("[PROJECT]"); - String filter = "filter-1274492040"; - PagedListResponse - pagedListResponse = api.listMetricDescriptors(formattedName, filter); + ListMetricDescriptorsPagedResponse pagedListResponse = api.listMetricDescriptors(formattedName); List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); Assert.assertEquals(1, resources.size()); @@ -189,14 +186,13 @@ public void listMetricDescriptorsTest() { (ListMetricDescriptorsRequest) actualRequests.get(0); Assert.assertEquals(formattedName, actualRequest.getName()); - Assert.assertEquals(filter, actualRequest.getFilter()); } @Test @SuppressWarnings("all") public void getMetricDescriptorTest() { String formattedName2 = - MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]"); + MetricServiceApi.formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); String type = "type3575610"; String unit = "unit3594628"; String description = "description-1724546052"; @@ -214,7 +210,7 @@ public void getMetricDescriptorTest() { mockMetricService.setResponses(expectedResponses); String formattedName = - MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]"); + MetricServiceApi.formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); MetricDescriptor actualResponse = api.getMetricDescriptor(formattedName); Assert.assertEquals(expectedResponse, actualResponse); @@ -270,7 +266,7 @@ public void deleteMetricDescriptorTest() { mockMetricService.setResponses(expectedResponses); String formattedName = - MetricServiceApi.formatMetricDescriptorPathName("[PROJECT]", "[METRIC_DESCRIPTOR_PATH]"); + MetricServiceApi.formatMetricDescriptorName("[PROJECT]", "[METRIC_DESCRIPTOR]"); api.deleteMetricDescriptor(formattedName); @@ -282,6 +278,43 @@ public void deleteMetricDescriptorTest() { Assert.assertEquals(formattedName, actualRequest.getName()); } + @Test + @SuppressWarnings("all") + public void listTimeSeriesTest() { + String nextPageToken = ""; + TimeSeries timeSeriesElement = TimeSeries.newBuilder().build(); + List timeSeries = Arrays.asList(timeSeriesElement); + ListTimeSeriesResponse expectedResponse = + ListTimeSeriesResponse.newBuilder() + .setNextPageToken(nextPageToken) + .addAllTimeSeries(timeSeries) + .build(); + List expectedResponses = new ArrayList<>(); + expectedResponses.add(expectedResponse); + mockMetricService.setResponses(expectedResponses); + + String formattedName = MetricServiceApi.formatProjectName("[PROJECT]"); + String filter = "filter-1274492040"; + TimeInterval interval = TimeInterval.newBuilder().build(); + ListTimeSeriesRequest.TimeSeriesView view = ListTimeSeriesRequest.TimeSeriesView.FULL; + + ListTimeSeriesPagedResponse pagedListResponse = + api.listTimeSeries(formattedName, filter, interval, view); + + List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); + Assert.assertEquals(1, resources.size()); + Assert.assertEquals(expectedResponse.getTimeSeriesList().get(0), resources.get(0)); + + List actualRequests = mockMetricService.getRequests(); + Assert.assertEquals(1, actualRequests.size()); + ListTimeSeriesRequest actualRequest = (ListTimeSeriesRequest) actualRequests.get(0); + + Assert.assertEquals(formattedName, actualRequest.getName()); + Assert.assertEquals(filter, actualRequest.getFilter()); + Assert.assertEquals(interval, actualRequest.getInterval()); + Assert.assertEquals(view, actualRequest.getView()); + } + @Test @SuppressWarnings("all") public void createTimeSeriesTest() { diff --git a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockAgentTranslationService.java b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockAgentTranslationService.java deleted file mode 100644 index 3455f64948c8..000000000000 --- a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockAgentTranslationService.java +++ /dev/null @@ -1,49 +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.cloud.monitoring.spi.v3; - -import com.google.api.gax.testing.MockGrpcService; -import com.google.protobuf.GeneratedMessageV3; -import io.grpc.ServerServiceDefinition; -import java.util.List; - -@javax.annotation.Generated("by GAPIC") -public class MockAgentTranslationService implements MockGrpcService { - private final MockAgentTranslationServiceImpl serviceImpl; - - public MockAgentTranslationService() { - serviceImpl = new MockAgentTranslationServiceImpl(); - } - - @Override - public List getRequests() { - return serviceImpl.getRequests(); - } - - @Override - public void setResponses(List responses) { - serviceImpl.setResponses(responses); - } - - @Override - public ServerServiceDefinition getServiceDefinition() { - return serviceImpl.bindService(); - } - - @Override - public void reset() { - serviceImpl.reset(); - } -} diff --git a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockAgentTranslationServiceImpl.java b/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockAgentTranslationServiceImpl.java deleted file mode 100644 index 9d1538556a69..000000000000 --- a/google-cloud-monitoring/src/test/java/com/google/cloud/monitoring/spi/v3/MockAgentTranslationServiceImpl.java +++ /dev/null @@ -1,59 +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.cloud.monitoring.spi.v3; - -import com.google.common.collect.Lists; -import com.google.monitoring.v3.AgentTranslationServiceGrpc.AgentTranslationServiceImplBase; -import com.google.monitoring.v3.CreateCollectdTimeSeriesRequest; -import com.google.protobuf.Empty; -import com.google.protobuf.GeneratedMessageV3; -import io.grpc.stub.StreamObserver; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Queue; - -@javax.annotation.Generated("by GAPIC") -public class MockAgentTranslationServiceImpl extends AgentTranslationServiceImplBase { - private ArrayList requests; - private Queue responses; - - public MockAgentTranslationServiceImpl() { - requests = new ArrayList<>(); - responses = new LinkedList<>(); - } - - public List getRequests() { - return requests; - } - - public void setResponses(List responses) { - this.responses = Lists.newLinkedList(responses); - } - - public void reset() { - requests = new ArrayList<>(); - responses = new LinkedList<>(); - } - - @Override - public void createCollectdTimeSeries( - CreateCollectdTimeSeriesRequest request, StreamObserver responseObserver) { - Empty response = (Empty) responses.remove(); - requests.add(request); - responseObserver.onNext(response); - responseObserver.onCompleted(); - } -} diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/DefaultPubSubRpc.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/DefaultPubSubRpc.java index ed59a2b90a72..ec82f6d46822 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/DefaultPubSubRpc.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/DefaultPubSubRpc.java @@ -19,7 +19,7 @@ import static com.google.common.base.MoreObjects.firstNonNull; import com.google.api.gax.core.ConnectionSettings; -import com.google.api.gax.grpc.ApiCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; import com.google.api.gax.grpc.ApiException; import com.google.cloud.AuthCredentials; import com.google.cloud.GrpcServiceOptions.ExecutorFactory; @@ -94,7 +94,7 @@ protected ExecutorFactory executorFactory() { } @Override - protected ApiCallSettings.Builder apiCallSettings() { + protected UnaryCallSettings.Builder apiCallSettings() { return super.apiCallSettings(); } @@ -154,7 +154,7 @@ public DefaultPubSubRpc(PubSubOptions options) throws IOException { pubBuilder.provideChannelWith(connectionSettings); subBuilder.provideChannelWith(connectionSettings); } - ApiCallSettings.Builder callSettingsBuilder = internalOptions.apiCallSettings(); + UnaryCallSettings.Builder callSettingsBuilder = internalOptions.apiCallSettings(); pubBuilder.applyToAllApiMethods(callSettingsBuilder); subBuilder.applyToAllApiMethods(callSettingsBuilder); publisherApi = PublisherApi.create(pubBuilder.build()); @@ -183,7 +183,7 @@ public V apply(ApiException exception) { @Override public Future create(Topic topic) { - // TODO: it would be nice if we can get the idempotent information from the ApiCallSettings + // TODO: it would be nice if we can get the idempotent information from the UnaryCallSettings // or from the exception return translate(publisherApi.createTopicCallable().futureCall(topic), true); } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PagedResponseWrappers.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PagedResponseWrappers.java new file mode 100644 index 000000000000..ba9627634656 --- /dev/null +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PagedResponseWrappers.java @@ -0,0 +1,77 @@ +/* + * 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.cloud.pubsub.spi.v1; + +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseImpl; +import com.google.api.gax.grpc.UnaryCallable; +import com.google.pubsub.v1.ListSubscriptionsRequest; +import com.google.pubsub.v1.ListSubscriptionsResponse; +import com.google.pubsub.v1.ListTopicSubscriptionsRequest; +import com.google.pubsub.v1.ListTopicSubscriptionsResponse; +import com.google.pubsub.v1.ListTopicsRequest; +import com.google.pubsub.v1.ListTopicsResponse; +import com.google.pubsub.v1.Subscription; +import com.google.pubsub.v1.Topic; + +// AUTO-GENERATED DOCUMENTATION AND CLASS +/** + * Wrapper class to contain paged response types for page streaming methods. Each static class + * inside this wrapper class is used as the return type of one of an API method that implements the + * page streaming pattern. + */ +@javax.annotation.Generated("by GAPIC") +public class PagedResponseWrappers { + + public static class ListTopicsPagedResponse + extends PagedListResponseImpl { + + public ListTopicsPagedResponse( + UnaryCallable callable, + PagedListDescriptor pageDescriptor, + ListTopicsRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } + + public static class ListTopicSubscriptionsPagedResponse + extends PagedListResponseImpl< + ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String> { + + public ListTopicSubscriptionsPagedResponse( + UnaryCallable callable, + PagedListDescriptor + pageDescriptor, + ListTopicSubscriptionsRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } + + public static class ListSubscriptionsPagedResponse + extends PagedListResponseImpl< + ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription> { + + public ListSubscriptionsPagedResponse( + UnaryCallable callable, + PagedListDescriptor + pageDescriptor, + ListSubscriptionsRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } +} diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherApi.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherApi.java index be922966c3c3..5edacae38bea 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherApi.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherApi.java @@ -13,8 +13,10 @@ */ package com.google.cloud.pubsub.spi.v1; -import com.google.api.gax.core.PagedListResponse; -import com.google.api.gax.grpc.ApiCallable; +import static com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicSubscriptionsPagedResponse; +import static com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicsPagedResponse; + +import com.google.api.gax.grpc.UnaryCallable; import com.google.api.gax.protobuf.PathTemplate; import com.google.iam.v1.GetIamPolicyRequest; import com.google.iam.v1.Policy; @@ -69,8 +71,8 @@ *
  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -98,23 +100,19 @@ public class PublisherApi implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable createTopicCallable; - private final ApiCallable publishCallable; - private final ApiCallable getTopicCallable; - private final ApiCallable listTopicsCallable; - private final ApiCallable< - ListTopicsRequest, PagedListResponse> - listTopicsPagedCallable; - private final ApiCallable + private final UnaryCallable createTopicCallable; + private final UnaryCallable publishCallable; + private final UnaryCallable getTopicCallable; + private final UnaryCallable listTopicsCallable; + private final UnaryCallable listTopicsPagedCallable; + private final UnaryCallable listTopicSubscriptionsCallable; - private final ApiCallable< - ListTopicSubscriptionsRequest, - PagedListResponse> + private final UnaryCallable listTopicSubscriptionsPagedCallable; - private final ApiCallable deleteTopicCallable; - private final ApiCallable setIamPolicyCallable; - private final ApiCallable getIamPolicyCallable; - private final ApiCallable + private final UnaryCallable deleteTopicCallable; + private final UnaryCallable setIamPolicyCallable; + private final UnaryCallable getIamPolicyCallable; + private final UnaryCallable testIamPermissionsCallable; private static final PathTemplate PROJECT_PATH_TEMPLATE = @@ -173,31 +171,33 @@ protected PublisherApi(PublisherSettings settings) throws IOException { this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.createTopicCallable = - ApiCallable.create(settings.createTopicSettings(), this.channel, this.executor); + UnaryCallable.create(settings.createTopicSettings(), this.channel, this.executor); this.publishCallable = - ApiCallable.create(settings.publishSettings(), this.channel, this.executor); + UnaryCallable.create(settings.publishSettings(), this.channel, this.executor); if (settings.publishSettings().getBundlerFactory() != null) { closeables.add(settings.publishSettings().getBundlerFactory()); } this.getTopicCallable = - ApiCallable.create(settings.getTopicSettings(), this.channel, this.executor); + UnaryCallable.create(settings.getTopicSettings(), this.channel, this.executor); this.listTopicsCallable = - ApiCallable.create(settings.listTopicsSettings(), this.channel, this.executor); + UnaryCallable.create(settings.listTopicsSettings(), this.channel, this.executor); this.listTopicsPagedCallable = - ApiCallable.createPagedVariant(settings.listTopicsSettings(), this.channel, this.executor); + UnaryCallable.createPagedVariant( + settings.listTopicsSettings(), this.channel, this.executor); this.listTopicSubscriptionsCallable = - ApiCallable.create(settings.listTopicSubscriptionsSettings(), this.channel, this.executor); + UnaryCallable.create( + settings.listTopicSubscriptionsSettings(), this.channel, this.executor); this.listTopicSubscriptionsPagedCallable = - ApiCallable.createPagedVariant( + UnaryCallable.createPagedVariant( settings.listTopicSubscriptionsSettings(), this.channel, this.executor); this.deleteTopicCallable = - ApiCallable.create(settings.deleteTopicSettings(), this.channel, this.executor); + UnaryCallable.create(settings.deleteTopicSettings(), this.channel, this.executor); this.setIamPolicyCallable = - ApiCallable.create(settings.setIamPolicySettings(), this.channel, this.executor); + UnaryCallable.create(settings.setIamPolicySettings(), this.channel, this.executor); this.getIamPolicyCallable = - ApiCallable.create(settings.getIamPolicySettings(), this.channel, this.executor); + UnaryCallable.create(settings.getIamPolicySettings(), this.channel, this.executor); this.testIamPermissionsCallable = - ApiCallable.create(settings.testIamPermissionsSettings(), this.channel, this.executor); + UnaryCallable.create(settings.testIamPermissionsSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { closeables.add( @@ -290,7 +290,7 @@ private final Topic createTopic(Topic request) { * } *

  • */ - public final ApiCallable createTopicCallable() { + public final UnaryCallable createTopicCallable() { return createTopicCallable; } @@ -382,7 +382,7 @@ public final PublishResponse publish(PublishRequest request) { * } *
    */ - public final ApiCallable publishCallable() { + public final UnaryCallable publishCallable() { return publishCallable; } @@ -449,7 +449,7 @@ private final Topic getTopic(GetTopicRequest request) { * } * */ - public final ApiCallable getTopicCallable() { + public final UnaryCallable getTopicCallable() { return getTopicCallable; } @@ -471,8 +471,7 @@ public final ApiCallable getTopicCallable() { * @param project The name of the cloud project that topics belong to. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse listTopics( - String project) { + public final ListTopicsPagedResponse listTopics(String project) { PROJECT_PATH_TEMPLATE.validate(project, "listTopics"); ListTopicsRequest request = ListTopicsRequest.newBuilder().setProject(project).build(); return listTopics(request); @@ -499,8 +498,7 @@ public final PagedListResponse lis * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse listTopics( - ListTopicsRequest request) { + public final ListTopicsPagedResponse listTopics(ListTopicsRequest request) { return listTopicsPagedCallable().call(request); } @@ -516,7 +514,7 @@ public final PagedListResponse lis * ListTopicsRequest request = ListTopicsRequest.newBuilder() * .setProject(formattedProject) * .build(); - * ListenableFuture<PagedListResponse<ListTopicsRequest,ListTopicsResponse,Topic>> future = publisherApi.listTopicsPagedCallable().futureCall(request); + * ListenableFuture<ListTopicsPagedResponse> future = publisherApi.listTopicsPagedCallable().futureCall(request); * // Do something * for (Topic element : future.get().iterateAllElements()) { * // doThingsWith(element); @@ -524,9 +522,7 @@ public final PagedListResponse lis * } * */ - public final ApiCallable< - ListTopicsRequest, PagedListResponse> - listTopicsPagedCallable() { + public final UnaryCallable listTopicsPagedCallable() { return listTopicsPagedCallable; } @@ -557,7 +553,7 @@ public final PagedListResponse lis * } * */ - public final ApiCallable listTopicsCallable() { + public final UnaryCallable listTopicsCallable() { return listTopicsCallable; } @@ -579,9 +575,7 @@ public final ApiCallable listTopicsCallab * @param topic The name of the topic that subscriptions are attached to. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse< - ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String> - listTopicSubscriptions(String topic) { + public final ListTopicSubscriptionsPagedResponse listTopicSubscriptions(String topic) { TOPIC_PATH_TEMPLATE.validate(topic, "listTopicSubscriptions"); ListTopicSubscriptionsRequest request = ListTopicSubscriptionsRequest.newBuilder().setTopic(topic).build(); @@ -609,9 +603,8 @@ public final ApiCallable listTopicsCallab * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse< - ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String> - listTopicSubscriptions(ListTopicSubscriptionsRequest request) { + public final ListTopicSubscriptionsPagedResponse listTopicSubscriptions( + ListTopicSubscriptionsRequest request) { return listTopicSubscriptionsPagedCallable().call(request); } @@ -627,7 +620,7 @@ public final ApiCallable listTopicsCallab * ListTopicSubscriptionsRequest request = ListTopicSubscriptionsRequest.newBuilder() * .setTopic(formattedTopic) * .build(); - * ListenableFuture<PagedListResponse<ListTopicSubscriptionsRequest,ListTopicSubscriptionsResponse,String>> future = publisherApi.listTopicSubscriptionsPagedCallable().futureCall(request); + * ListenableFuture<ListTopicSubscriptionsPagedResponse> future = publisherApi.listTopicSubscriptionsPagedCallable().futureCall(request); * // Do something * for (String element : future.get().iterateAllElements()) { * // doThingsWith(element); @@ -635,9 +628,7 @@ public final ApiCallable listTopicsCallab * } * */ - public final ApiCallable< - ListTopicSubscriptionsRequest, - PagedListResponse> + public final UnaryCallable listTopicSubscriptionsPagedCallable() { return listTopicSubscriptionsPagedCallable; } @@ -669,7 +660,7 @@ public final ApiCallable listTopicsCallab * } * */ - public final ApiCallable + public final UnaryCallable listTopicSubscriptionsCallable() { return listTopicSubscriptionsCallable; } @@ -746,7 +737,7 @@ private final void deleteTopic(DeleteTopicRequest request) { * } * */ - public final ApiCallable deleteTopicCallable() { + public final UnaryCallable deleteTopicCallable() { return deleteTopicCallable; } @@ -764,11 +755,12 @@ public final ApiCallable deleteTopicCallable() { * } * * - * @param resource REQUIRED: The resource for which policy is being specified. Resource is usually - * specified as a path, such as, projects/{project}/zones/{zone}/disks/{disk}. - * @param policy REQUIRED: The complete policy to be applied to the 'resource'. The size of the - * policy is limited to a few 10s of KB. An empty policy is in general a valid policy but - * certain services (like Projects) might reject them. + * @param resource REQUIRED: The resource for which the policy is being specified. `resource` is + * usually specified as a path. For example, a Project resource is specified as + * `projects/{project}`. + * @param policy REQUIRED: The complete policy to be applied to the `resource`. The size of the + * policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud + * Platform services (such as Projects) might reject them. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final Policy setIamPolicy(String resource, Policy policy) { @@ -823,14 +815,14 @@ public final Policy setIamPolicy(SetIamPolicyRequest request) { * } * */ - public final ApiCallable setIamPolicyCallable() { + public final UnaryCallable setIamPolicyCallable() { return setIamPolicyCallable; } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets the access control policy for a resource. Is empty if the policy or the resource does not - * exist. + * Gets the access control policy for a resource. Returns an empty policy if the resource exists + * and does not have a policy set. * *

    Sample code: * @@ -841,8 +833,9 @@ public final ApiCallable setIamPolicyCallable() { * } * * - * @param resource REQUIRED: The resource for which policy is being requested. Resource is usually - * specified as a path, such as, projects/{project}. + * @param resource REQUIRED: The resource for which the policy is being requested. `resource` is + * usually specified as a path. For example, a Project resource is specified as + * `projects/{project}`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final Policy getIamPolicy(String resource) { @@ -853,8 +846,8 @@ public final Policy getIamPolicy(String resource) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets the access control policy for a resource. Is empty if the policy or the resource does not - * exist. + * Gets the access control policy for a resource. Returns an empty policy if the resource exists + * and does not have a policy set. * *

    Sample code: * @@ -877,8 +870,8 @@ private final Policy getIamPolicy(GetIamPolicyRequest request) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets the access control policy for a resource. Is empty if the policy or the resource does not - * exist. + * Gets the access control policy for a resource. Returns an empty policy if the resource exists + * and does not have a policy set. * *

    Sample code: * @@ -894,7 +887,7 @@ private final Policy getIamPolicy(GetIamPolicyRequest request) { * } * */ - public final ApiCallable getIamPolicyCallable() { + public final UnaryCallable getIamPolicyCallable() { return getIamPolicyCallable; } @@ -912,10 +905,12 @@ public final ApiCallable getIamPolicyCallable() { * } * * - * @param resource REQUIRED: The resource for which policy detail is being requested. Resource is - * usually specified as a path, such as, projects/{project}. - * @param permissions The set of permissions to check for the 'resource'. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. + * @param resource REQUIRED: The resource for which the policy detail is being requested. + * `resource` is usually specified as a path. For example, a Project resource is specified as + * `projects/{project}`. + * @param permissions The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final TestIamPermissionsResponse testIamPermissions( @@ -974,7 +969,7 @@ public final TestIamPermissionsResponse testIamPermissions(TestIamPermissionsReq * } * */ - public final ApiCallable + public final UnaryCallable testIamPermissionsCallable() { return testIamPermissionsCallable; } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherSettings.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherSettings.java index 8c50b07d0d06..f225e27a2523 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherSettings.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/PublisherSettings.java @@ -13,17 +13,23 @@ */ package com.google.cloud.pubsub.spi.v1; +import static com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicSubscriptionsPagedResponse; +import static com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicsPagedResponse; + import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; import com.google.api.gax.grpc.BundlingCallSettings; import com.google.api.gax.grpc.BundlingDescriptor; import com.google.api.gax.grpc.BundlingSettings; -import com.google.api.gax.grpc.PageStreamingCallSettings; -import com.google.api.gax.grpc.PageStreamingDescriptor; +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedCallSettings; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseFactory; import com.google.api.gax.grpc.RequestIssuer; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; +import com.google.api.gax.grpc.UnaryCallable; import com.google.auth.Credentials; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -98,21 +104,14 @@ public class PublisherSettings extends ServiceApiSettings { .add("https://www.googleapis.com/auth/pubsub") .build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - private final SimpleCallSettings createTopicSettings; private final BundlingCallSettings publishSettings; private final SimpleCallSettings getTopicSettings; - private final PageStreamingCallSettings + private final PagedCallSettings listTopicsSettings; - private final PageStreamingCallSettings< - ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String> + private final PagedCallSettings< + ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> listTopicSubscriptionsSettings; private final SimpleCallSettings deleteTopicSettings; private final SimpleCallSettings setIamPolicySettings; @@ -136,14 +135,15 @@ public SimpleCallSettings getTopicSettings() { } /** Returns the object with the settings used for calls to listTopics. */ - public PageStreamingCallSettings + public PagedCallSettings listTopicsSettings() { return listTopicsSettings; } /** Returns the object with the settings used for calls to listTopicSubscriptions. */ - public PageStreamingCallSettings< - ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String> + public PagedCallSettings< + ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> listTopicSubscriptionsSettings() { return listTopicSubscriptionsSettings; } @@ -219,9 +219,9 @@ private PublisherSettings(Builder settingsBuilder) throws IOException { testIamPermissionsSettings = settingsBuilder.testIamPermissionsSettings().build(); } - private static final PageStreamingDescriptor + private static final PagedListDescriptor LIST_TOPICS_PAGE_STR_DESC = - new PageStreamingDescriptor() { + new PagedListDescriptor() { @Override public Object emptyToken() { return ""; @@ -253,10 +253,10 @@ public Iterable extractResources(ListTopicsResponse payload) { } }; - private static final PageStreamingDescriptor< + private static final PagedListDescriptor< ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String> LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_DESC = - new PageStreamingDescriptor< + new PagedListDescriptor< ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String>() { @Override public Object emptyToken() { @@ -295,6 +295,39 @@ public Iterable extractResources(ListTopicSubscriptionsResponse payload) } }; + private static final PagedListResponseFactory< + ListTopicsRequest, ListTopicsResponse, ListTopicsPagedResponse> + LIST_TOPICS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListTopicsRequest, ListTopicsResponse, ListTopicsPagedResponse>() { + @Override + public ListTopicsPagedResponse createPagedListResponse( + UnaryCallable callable, + ListTopicsRequest request, + CallContext context) { + return new ListTopicsPagedResponse( + callable, LIST_TOPICS_PAGE_STR_DESC, request, context); + } + }; + + private static final PagedListResponseFactory< + ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> + LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse>() { + @Override + public ListTopicSubscriptionsPagedResponse createPagedListResponse( + UnaryCallable + callable, + ListTopicSubscriptionsRequest request, + CallContext context) { + return new ListTopicSubscriptionsPagedResponse( + callable, LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_DESC, request, context); + } + }; + private static final BundlingDescriptor PUBLISH_BUNDLING_DESC = new BundlingDescriptor() { @Override @@ -359,15 +392,17 @@ public long countBytes(PublishRequest request) { /** Builder for PublisherSettings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; private final SimpleCallSettings.Builder createTopicSettings; private final BundlingCallSettings.Builder publishSettings; private final SimpleCallSettings.Builder getTopicSettings; - private final PageStreamingCallSettings.Builder + private final PagedCallSettings.Builder< + ListTopicsRequest, ListTopicsResponse, ListTopicsPagedResponse> listTopicsSettings; - private final PageStreamingCallSettings.Builder< - ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String> + private final PagedCallSettings.Builder< + ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> listTopicSubscriptionsSettings; private final SimpleCallSettings.Builder deleteTopicSettings; private final SimpleCallSettings.Builder setIamPolicySettings; @@ -422,7 +457,7 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); createTopicSettings = SimpleCallSettings.newBuilder(PublisherGrpc.METHOD_CREATE_TOPIC); @@ -433,13 +468,12 @@ private Builder() { getTopicSettings = SimpleCallSettings.newBuilder(PublisherGrpc.METHOD_GET_TOPIC); listTopicsSettings = - PageStreamingCallSettings.newBuilder( - PublisherGrpc.METHOD_LIST_TOPICS, LIST_TOPICS_PAGE_STR_DESC); + PagedCallSettings.newBuilder(PublisherGrpc.METHOD_LIST_TOPICS, LIST_TOPICS_PAGE_STR_FACT); listTopicSubscriptionsSettings = - PageStreamingCallSettings.newBuilder( + PagedCallSettings.newBuilder( PublisherGrpc.METHOD_LIST_TOPIC_SUBSCRIPTIONS, - LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_DESC); + LIST_TOPIC_SUBSCRIPTIONS_PAGE_STR_FACT); deleteTopicSettings = SimpleCallSettings.newBuilder(PublisherGrpc.METHOD_DELETE_TOPIC); @@ -450,8 +484,8 @@ private Builder() { testIamPermissionsSettings = SimpleCallSettings.newBuilder(IAMPolicyGrpc.METHOD_TEST_IAM_PERMISSIONS); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( createTopicSettings, publishSettings, getTopicSettings, @@ -536,8 +570,8 @@ private Builder(PublisherSettings settings) { getIamPolicySettings = settings.getIamPolicySettings.toBuilder(); testIamPermissionsSettings = settings.testIamPermissionsSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( createTopicSettings, publishSettings, getTopicSettings, @@ -549,9 +583,16 @@ private Builder(PublisherSettings settings) { testIamPermissionsSettings); } + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); + } + @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -597,11 +638,14 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } @@ -621,14 +665,15 @@ public SimpleCallSettings.Builder getTopicSettings() { } /** Returns the builder for the settings used for calls to listTopics. */ - public PageStreamingCallSettings.Builder + public PagedCallSettings.Builder listTopicsSettings() { return listTopicsSettings; } /** Returns the builder for the settings used for calls to listTopicSubscriptions. */ - public PageStreamingCallSettings.Builder< - ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, String> + public PagedCallSettings.Builder< + ListTopicSubscriptionsRequest, ListTopicSubscriptionsResponse, + ListTopicSubscriptionsPagedResponse> listTopicSubscriptionsSettings() { return listTopicSubscriptionsSettings; } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberApi.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberApi.java index 3505cd9d1825..6f07efb8d75d 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberApi.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberApi.java @@ -13,8 +13,9 @@ */ package com.google.cloud.pubsub.spi.v1; -import com.google.api.gax.core.PagedListResponse; -import com.google.api.gax.grpc.ApiCallable; +import static com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListSubscriptionsPagedResponse; + +import com.google.api.gax.grpc.UnaryCallable; import com.google.api.gax.protobuf.PathTemplate; import com.google.iam.v1.GetIamPolicyRequest; import com.google.iam.v1.Policy; @@ -73,8 +74,8 @@ *

  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -102,22 +103,20 @@ public class SubscriberApi implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable createSubscriptionCallable; - private final ApiCallable getSubscriptionCallable; - private final ApiCallable + private final UnaryCallable createSubscriptionCallable; + private final UnaryCallable getSubscriptionCallable; + private final UnaryCallable listSubscriptionsCallable; - private final ApiCallable< - ListSubscriptionsRequest, - PagedListResponse> + private final UnaryCallable listSubscriptionsPagedCallable; - private final ApiCallable deleteSubscriptionCallable; - private final ApiCallable modifyAckDeadlineCallable; - private final ApiCallable acknowledgeCallable; - private final ApiCallable pullCallable; - private final ApiCallable modifyPushConfigCallable; - private final ApiCallable setIamPolicyCallable; - private final ApiCallable getIamPolicyCallable; - private final ApiCallable + private final UnaryCallable deleteSubscriptionCallable; + private final UnaryCallable modifyAckDeadlineCallable; + private final UnaryCallable acknowledgeCallable; + private final UnaryCallable pullCallable; + private final UnaryCallable modifyPushConfigCallable; + private final UnaryCallable setIamPolicyCallable; + private final UnaryCallable getIamPolicyCallable; + private final UnaryCallable testIamPermissionsCallable; private static final PathTemplate PROJECT_PATH_TEMPLATE = @@ -202,29 +201,29 @@ protected SubscriberApi(SubscriberSettings settings) throws IOException { this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.createSubscriptionCallable = - ApiCallable.create(settings.createSubscriptionSettings(), this.channel, this.executor); + UnaryCallable.create(settings.createSubscriptionSettings(), this.channel, this.executor); this.getSubscriptionCallable = - ApiCallable.create(settings.getSubscriptionSettings(), this.channel, this.executor); + UnaryCallable.create(settings.getSubscriptionSettings(), this.channel, this.executor); this.listSubscriptionsCallable = - ApiCallable.create(settings.listSubscriptionsSettings(), this.channel, this.executor); + UnaryCallable.create(settings.listSubscriptionsSettings(), this.channel, this.executor); this.listSubscriptionsPagedCallable = - ApiCallable.createPagedVariant( + UnaryCallable.createPagedVariant( settings.listSubscriptionsSettings(), this.channel, this.executor); this.deleteSubscriptionCallable = - ApiCallable.create(settings.deleteSubscriptionSettings(), this.channel, this.executor); + UnaryCallable.create(settings.deleteSubscriptionSettings(), this.channel, this.executor); this.modifyAckDeadlineCallable = - ApiCallable.create(settings.modifyAckDeadlineSettings(), this.channel, this.executor); + UnaryCallable.create(settings.modifyAckDeadlineSettings(), this.channel, this.executor); this.acknowledgeCallable = - ApiCallable.create(settings.acknowledgeSettings(), this.channel, this.executor); - this.pullCallable = ApiCallable.create(settings.pullSettings(), this.channel, this.executor); + UnaryCallable.create(settings.acknowledgeSettings(), this.channel, this.executor); + this.pullCallable = UnaryCallable.create(settings.pullSettings(), this.channel, this.executor); this.modifyPushConfigCallable = - ApiCallable.create(settings.modifyPushConfigSettings(), this.channel, this.executor); + UnaryCallable.create(settings.modifyPushConfigSettings(), this.channel, this.executor); this.setIamPolicyCallable = - ApiCallable.create(settings.setIamPolicySettings(), this.channel, this.executor); + UnaryCallable.create(settings.setIamPolicySettings(), this.channel, this.executor); this.getIamPolicyCallable = - ApiCallable.create(settings.getIamPolicySettings(), this.channel, this.executor); + UnaryCallable.create(settings.getIamPolicySettings(), this.channel, this.executor); this.testIamPermissionsCallable = - ApiCallable.create(settings.testIamPermissionsSettings(), this.channel, this.executor); + UnaryCallable.create(settings.testIamPermissionsSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { closeables.add( @@ -365,7 +364,7 @@ public final Subscription createSubscription(Subscription request) { * } * */ - public final ApiCallable createSubscriptionCallable() { + public final UnaryCallable createSubscriptionCallable() { return createSubscriptionCallable; } @@ -433,7 +432,7 @@ private final Subscription getSubscription(GetSubscriptionRequest request) { * } * */ - public final ApiCallable getSubscriptionCallable() { + public final UnaryCallable getSubscriptionCallable() { return getSubscriptionCallable; } @@ -455,8 +454,7 @@ public final ApiCallable getSubscriptionCa * @param project The name of the cloud project that subscriptions belong to. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse - listSubscriptions(String project) { + public final ListSubscriptionsPagedResponse listSubscriptions(String project) { PROJECT_PATH_TEMPLATE.validate(project, "listSubscriptions"); ListSubscriptionsRequest request = ListSubscriptionsRequest.newBuilder().setProject(project).build(); @@ -484,8 +482,7 @@ public final ApiCallable getSubscriptionCa * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse - listSubscriptions(ListSubscriptionsRequest request) { + public final ListSubscriptionsPagedResponse listSubscriptions(ListSubscriptionsRequest request) { return listSubscriptionsPagedCallable().call(request); } @@ -501,7 +498,7 @@ public final ApiCallable getSubscriptionCa * ListSubscriptionsRequest request = ListSubscriptionsRequest.newBuilder() * .setProject(formattedProject) * .build(); - * ListenableFuture<PagedListResponse<ListSubscriptionsRequest,ListSubscriptionsResponse,Subscription>> future = subscriberApi.listSubscriptionsPagedCallable().futureCall(request); + * ListenableFuture<ListSubscriptionsPagedResponse> future = subscriberApi.listSubscriptionsPagedCallable().futureCall(request); * // Do something * for (Subscription element : future.get().iterateAllElements()) { * // doThingsWith(element); @@ -509,9 +506,7 @@ public final ApiCallable getSubscriptionCa * } * */ - public final ApiCallable< - ListSubscriptionsRequest, - PagedListResponse> + public final UnaryCallable listSubscriptionsPagedCallable() { return listSubscriptionsPagedCallable; } @@ -543,7 +538,7 @@ public final ApiCallable getSubscriptionCa * } * */ - public final ApiCallable + public final UnaryCallable listSubscriptionsCallable() { return listSubscriptionsCallable; } @@ -621,7 +616,7 @@ private final void deleteSubscription(DeleteSubscriptionRequest request) { * } * */ - public final ApiCallable deleteSubscriptionCallable() { + public final UnaryCallable deleteSubscriptionCallable() { return deleteSubscriptionCallable; } @@ -718,7 +713,7 @@ public final void modifyAckDeadline(ModifyAckDeadlineRequest request) { * } * */ - public final ApiCallable modifyAckDeadlineCallable() { + public final UnaryCallable modifyAckDeadlineCallable() { return modifyAckDeadlineCallable; } @@ -805,7 +800,7 @@ public final void acknowledge(AcknowledgeRequest request) { * } * */ - public final ApiCallable acknowledgeCallable() { + public final UnaryCallable acknowledgeCallable() { return acknowledgeCallable; } @@ -895,7 +890,7 @@ public final PullResponse pull(PullRequest request) { * } * */ - public final ApiCallable pullCallable() { + public final UnaryCallable pullCallable() { return pullCallable; } @@ -990,7 +985,7 @@ public final void modifyPushConfig(ModifyPushConfigRequest request) { * } * */ - public final ApiCallable modifyPushConfigCallable() { + public final UnaryCallable modifyPushConfigCallable() { return modifyPushConfigCallable; } @@ -1008,11 +1003,12 @@ public final ApiCallable modifyPushConfigCallabl * } * * - * @param resource REQUIRED: The resource for which policy is being specified. Resource is usually - * specified as a path, such as, projects/{project}/zones/{zone}/disks/{disk}. - * @param policy REQUIRED: The complete policy to be applied to the 'resource'. The size of the - * policy is limited to a few 10s of KB. An empty policy is in general a valid policy but - * certain services (like Projects) might reject them. + * @param resource REQUIRED: The resource for which the policy is being specified. `resource` is + * usually specified as a path. For example, a Project resource is specified as + * `projects/{project}`. + * @param policy REQUIRED: The complete policy to be applied to the `resource`. The size of the + * policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud + * Platform services (such as Projects) might reject them. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final Policy setIamPolicy(String resource, Policy policy) { @@ -1067,14 +1063,14 @@ public final Policy setIamPolicy(SetIamPolicyRequest request) { * } * */ - public final ApiCallable setIamPolicyCallable() { + public final UnaryCallable setIamPolicyCallable() { return setIamPolicyCallable; } // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets the access control policy for a resource. Is empty if the policy or the resource does not - * exist. + * Gets the access control policy for a resource. Returns an empty policy if the resource exists + * and does not have a policy set. * *

    Sample code: * @@ -1085,8 +1081,9 @@ public final ApiCallable setIamPolicyCallable() { * } * * - * @param resource REQUIRED: The resource for which policy is being requested. Resource is usually - * specified as a path, such as, projects/{project}. + * @param resource REQUIRED: The resource for which the policy is being requested. `resource` is + * usually specified as a path. For example, a Project resource is specified as + * `projects/{project}`. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final Policy getIamPolicy(String resource) { @@ -1097,8 +1094,8 @@ public final Policy getIamPolicy(String resource) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets the access control policy for a resource. Is empty if the policy or the resource does not - * exist. + * Gets the access control policy for a resource. Returns an empty policy if the resource exists + * and does not have a policy set. * *

    Sample code: * @@ -1121,8 +1118,8 @@ private final Policy getIamPolicy(GetIamPolicyRequest request) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Gets the access control policy for a resource. Is empty if the policy or the resource does not - * exist. + * Gets the access control policy for a resource. Returns an empty policy if the resource exists + * and does not have a policy set. * *

    Sample code: * @@ -1138,7 +1135,7 @@ private final Policy getIamPolicy(GetIamPolicyRequest request) { * } * */ - public final ApiCallable getIamPolicyCallable() { + public final UnaryCallable getIamPolicyCallable() { return getIamPolicyCallable; } @@ -1156,10 +1153,12 @@ public final ApiCallable getIamPolicyCallable() { * } * * - * @param resource REQUIRED: The resource for which policy detail is being requested. Resource is - * usually specified as a path, such as, projects/{project}. - * @param permissions The set of permissions to check for the 'resource'. Permissions with - * wildcards (such as '*' or 'storage.*') are not allowed. + * @param resource REQUIRED: The resource for which the policy detail is being requested. + * `resource` is usually specified as a path. For example, a Project resource is specified as + * `projects/{project}`. + * @param permissions The set of permissions to check for the `resource`. Permissions with + * wildcards (such as '*' or 'storage.*') are not allowed. For more information see + * [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ public final TestIamPermissionsResponse testIamPermissions( @@ -1218,7 +1217,7 @@ public final TestIamPermissionsResponse testIamPermissions(TestIamPermissionsReq * } * */ - public final ApiCallable + public final UnaryCallable testIamPermissionsCallable() { return testIamPermissionsCallable; } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberSettings.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberSettings.java index 4396e5b692f9..b8f949f1a6e2 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberSettings.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/SubscriberSettings.java @@ -13,13 +13,18 @@ */ package com.google.cloud.pubsub.spi.v1; +import static com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListSubscriptionsPagedResponse; + import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; -import com.google.api.gax.grpc.PageStreamingCallSettings; -import com.google.api.gax.grpc.PageStreamingDescriptor; +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedCallSettings; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseFactory; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; +import com.google.api.gax.grpc.UnaryCallable; import com.google.auth.Credentials; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -92,18 +97,10 @@ public class SubscriberSettings extends ServiceApiSettings { .add("https://www.googleapis.com/auth/pubsub") .build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - private final SimpleCallSettings createSubscriptionSettings; private final SimpleCallSettings getSubscriptionSettings; - private final PageStreamingCallSettings< - ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription> + private final PagedCallSettings< + ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse> listSubscriptionsSettings; private final SimpleCallSettings deleteSubscriptionSettings; private final SimpleCallSettings modifyAckDeadlineSettings; @@ -126,8 +123,8 @@ public SimpleCallSettings getSubscriptionS } /** Returns the object with the settings used for calls to listSubscriptions. */ - public PageStreamingCallSettings< - ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription> + public PagedCallSettings< + ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse> listSubscriptionsSettings() { return listSubscriptionsSettings; } @@ -225,10 +222,10 @@ private SubscriberSettings(Builder settingsBuilder) throws IOException { testIamPermissionsSettings = settingsBuilder.testIamPermissionsSettings().build(); } - private static final PageStreamingDescriptor< + private static final PagedListDescriptor< ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription> LIST_SUBSCRIPTIONS_PAGE_STR_DESC = - new PageStreamingDescriptor< + new PagedListDescriptor< ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription>() { @Override public Object emptyToken() { @@ -265,15 +262,31 @@ public Iterable extractResources(ListSubscriptionsResponse payload } }; + private static final PagedListResponseFactory< + ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse> + LIST_SUBSCRIPTIONS_PAGE_STR_FACT = + new PagedListResponseFactory< + ListSubscriptionsRequest, ListSubscriptionsResponse, + ListSubscriptionsPagedResponse>() { + @Override + public ListSubscriptionsPagedResponse createPagedListResponse( + UnaryCallable callable, + ListSubscriptionsRequest request, + CallContext context) { + return new ListSubscriptionsPagedResponse( + callable, LIST_SUBSCRIPTIONS_PAGE_STR_DESC, request, context); + } + }; + /** Builder for SubscriberSettings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; private final SimpleCallSettings.Builder createSubscriptionSettings; private final SimpleCallSettings.Builder getSubscriptionSettings; - private final PageStreamingCallSettings.Builder< - ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription> + private final PagedCallSettings.Builder< + ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse> listSubscriptionsSettings; private final SimpleCallSettings.Builder deleteSubscriptionSettings; @@ -330,7 +343,7 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); createSubscriptionSettings = SimpleCallSettings.newBuilder(SubscriberGrpc.METHOD_CREATE_SUBSCRIPTION); @@ -339,8 +352,8 @@ private Builder() { SimpleCallSettings.newBuilder(SubscriberGrpc.METHOD_GET_SUBSCRIPTION); listSubscriptionsSettings = - PageStreamingCallSettings.newBuilder( - SubscriberGrpc.METHOD_LIST_SUBSCRIPTIONS, LIST_SUBSCRIPTIONS_PAGE_STR_DESC); + PagedCallSettings.newBuilder( + SubscriberGrpc.METHOD_LIST_SUBSCRIPTIONS, LIST_SUBSCRIPTIONS_PAGE_STR_FACT); deleteSubscriptionSettings = SimpleCallSettings.newBuilder(SubscriberGrpc.METHOD_DELETE_SUBSCRIPTION); @@ -362,8 +375,8 @@ private Builder() { testIamPermissionsSettings = SimpleCallSettings.newBuilder(IAMPolicyGrpc.METHOD_TEST_IAM_PERMISSIONS); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( createSubscriptionSettings, getSubscriptionSettings, listSubscriptionsSettings, @@ -453,8 +466,8 @@ private Builder(SubscriberSettings settings) { getIamPolicySettings = settings.getIamPolicySettings.toBuilder(); testIamPermissionsSettings = settings.testIamPermissionsSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( createSubscriptionSettings, getSubscriptionSettings, listSubscriptionsSettings, @@ -468,9 +481,16 @@ private Builder(SubscriberSettings settings) { testIamPermissionsSettings); } + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); + } + @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -516,11 +536,14 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } @@ -536,8 +559,8 @@ public SimpleCallSettings.Builder createSubscription } /** Returns the builder for the settings used for calls to listSubscriptions. */ - public PageStreamingCallSettings.Builder< - ListSubscriptionsRequest, ListSubscriptionsResponse, Subscription> + public PagedCallSettings.Builder< + ListSubscriptionsRequest, ListSubscriptionsResponse, ListSubscriptionsPagedResponse> listSubscriptionsSettings() { return listSubscriptionsSettings; } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/package-info.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/package-info.java index 99a7c0144671..da182b630ccb 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/package-info.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/v1/package-info.java @@ -15,7 +15,7 @@ /** * A client to Google Cloud Pub/Sub API. * - *

    The interfaces provided are listed below, along with a usage sample + *

    The interfaces provided are listed below, along with usage samples. * *

    ============ PublisherApi ============ * diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/PublisherTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/PublisherTest.java index 7d76c1a27111..54b07c63362d 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/PublisherTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/PublisherTest.java @@ -14,7 +14,9 @@ package com.google.cloud.pubsub.spi.v1; -import com.google.api.gax.core.PagedListResponse; +import static com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicSubscriptionsPagedResponse; +import static com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicsPagedResponse; + import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; import com.google.common.collect.Lists; @@ -173,8 +175,7 @@ public void listTopicsTest() { String formattedProject = PublisherApi.formatProjectName("[PROJECT]"); - PagedListResponse pagedListResponse = - api.listTopics(formattedProject); + ListTopicsPagedResponse pagedListResponse = api.listTopics(formattedProject); List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); Assert.assertEquals(1, resources.size()); @@ -204,8 +205,8 @@ public void listTopicSubscriptionsTest() { String formattedTopic = PublisherApi.formatTopicName("[PROJECT]", "[TOPIC]"); - PagedListResponse - pagedListResponse = api.listTopicSubscriptions(formattedTopic); + ListTopicSubscriptionsPagedResponse pagedListResponse = + api.listTopicSubscriptions(formattedTopic); List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); Assert.assertEquals(1, resources.size()); diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/SubscriberTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/SubscriberTest.java index 28e25b421ac7..1fa6597ab0db 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/SubscriberTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/spi/v1/SubscriberTest.java @@ -14,7 +14,8 @@ package com.google.cloud.pubsub.spi.v1; -import com.google.api.gax.core.PagedListResponse; +import static com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListSubscriptionsPagedResponse; + import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; import com.google.common.collect.Lists; @@ -169,8 +170,7 @@ public void listSubscriptionsTest() { String formattedProject = SubscriberApi.formatProjectName("[PROJECT]"); - PagedListResponse - pagedListResponse = api.listSubscriptions(formattedProject); + ListSubscriptionsPagedResponse pagedListResponse = api.listSubscriptions(formattedProject); List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); Assert.assertEquals(1, resources.size()); diff --git a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/PagedResponseWrappers.java b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/PagedResponseWrappers.java new file mode 100644 index 000000000000..1a294b7d2870 --- /dev/null +++ b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/PagedResponseWrappers.java @@ -0,0 +1,24 @@ +/* + * 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.cloud.speech.spi.v1beta1; + + +// AUTO-GENERATED DOCUMENTATION AND CLASS +/** + * Wrapper class to contain paged response types for page streaming methods. Each static class + * inside this wrapper class is used as the return type of one of an API method that implements the + * page streaming pattern. + */ +@javax.annotation.Generated("by GAPIC") +public class PagedResponseWrappers {} diff --git a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechApi.java b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechApi.java index 9ce5e2917edc..1423c4d3afa7 100644 --- a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechApi.java +++ b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechApi.java @@ -13,10 +13,13 @@ */ package com.google.cloud.speech.spi.v1beta1; -import com.google.api.gax.grpc.ApiCallable; +import com.google.api.gax.grpc.StreamingCallable; +import com.google.api.gax.grpc.UnaryCallable; import com.google.cloud.speech.v1beta1.AsyncRecognizeRequest; import com.google.cloud.speech.v1beta1.RecognitionAudio; import com.google.cloud.speech.v1beta1.RecognitionConfig; +import com.google.cloud.speech.v1beta1.StreamingRecognizeRequest; +import com.google.cloud.speech.v1beta1.StreamingRecognizeResponse; import com.google.cloud.speech.v1beta1.SyncRecognizeRequest; import com.google.cloud.speech.v1beta1.SyncRecognizeResponse; import com.google.longrunning.Operation; @@ -57,8 +60,8 @@ *

  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -86,8 +89,10 @@ public class SpeechApi implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable syncRecognizeCallable; - private final ApiCallable asyncRecognizeCallable; + private final UnaryCallable syncRecognizeCallable; + private final UnaryCallable asyncRecognizeCallable; + private final StreamingCallable + streamingRecognizeCallable; /** Constructs an instance of SpeechApi with default settings. */ public static final SpeechApi create() throws IOException { @@ -112,9 +117,11 @@ protected SpeechApi(SpeechSettings settings) throws IOException { this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.syncRecognizeCallable = - ApiCallable.create(settings.syncRecognizeSettings(), this.channel, this.executor); + UnaryCallable.create(settings.syncRecognizeSettings(), this.channel, this.executor); this.asyncRecognizeCallable = - ApiCallable.create(settings.asyncRecognizeSettings(), this.channel, this.executor); + UnaryCallable.create(settings.asyncRecognizeSettings(), this.channel, this.executor); + this.streamingRecognizeCallable = + StreamingCallable.create(settings.streamingRecognizeSettings(), this.channel); if (settings.getChannelProvider().shouldAutoClose()) { closeables.add( @@ -214,7 +221,7 @@ public final SyncRecognizeResponse syncRecognize(SyncRecognizeRequest request) { * } * */ - public final ApiCallable syncRecognizeCallable() { + public final UnaryCallable syncRecognizeCallable() { return syncRecognizeCallable; } @@ -294,10 +301,49 @@ public final Operation asyncRecognize(AsyncRecognizeRequest request) { * } * */ - public final ApiCallable asyncRecognizeCallable() { + public final UnaryCallable asyncRecognizeCallable() { return asyncRecognizeCallable; } + // AUTO-GENERATED DOCUMENTATION AND METHOD + /** + * Perform bidirectional streaming speech-recognition: receive results while sending audio. This + * method is only available via the gRPC API (not REST). + * + *

    Sample code: + * + *

    
    +   * try (SpeechApi speechApi = SpeechApi.create()) {
    +   *   StreamObserver<StreamingRecognizeResponse> responseObserver =
    +   *       new StreamObserver<StreamingRecognizeResponse>() {
    +   *         @Override
    +   *         public void onNext(StreamingRecognizeResponse response) {
    +   *           // Do something when receive a response
    +   *         }
    +   *
    +   *         @Override
    +   *         public void onError(Throwable t) {
    +   *           // Add error-handling
    +   *         }
    +   *
    +   *         @Override
    +   *         public void onCompleted() {
    +   *           // Do something when complete.
    +   *         }
    +   *       };
    +   *   StreamObserver<StreamingRecognizeRequest> requestObserver =
    +   *       speechApi.streamingRecognizeCallable().bidiStreamingCall(responseObserver)});
    +   *
    +   *   StreamingRecognizeRequest request = StreamingRecognizeRequest.newBuilder().build();
    +   *   requestObserver.onNext(request);
    +   * }
    +   * 
    + */ + public final StreamingCallable + streamingRecognizeCallable() { + return streamingRecognizeCallable; + } + /** * Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately * cancelled. diff --git a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechSettings.java b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechSettings.java index ed78555815e4..ffe6c6adfede 100644 --- a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechSettings.java +++ b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/SpeechSettings.java @@ -15,12 +15,15 @@ import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.StreamingCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; import com.google.auth.Credentials; import com.google.cloud.speech.v1beta1.AsyncRecognizeRequest; import com.google.cloud.speech.v1beta1.SpeechGrpc; +import com.google.cloud.speech.v1beta1.StreamingRecognizeRequest; +import com.google.cloud.speech.v1beta1.StreamingRecognizeResponse; import com.google.cloud.speech.v1beta1.SyncRecognizeRequest; import com.google.cloud.speech.v1beta1.SyncRecognizeResponse; import com.google.common.collect.ImmutableList; @@ -74,17 +77,11 @@ public class SpeechSettings extends ServiceApiSettings { private static final ImmutableList DEFAULT_SERVICE_SCOPES = ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - private final SimpleCallSettings syncRecognizeSettings; private final SimpleCallSettings asyncRecognizeSettings; + private final StreamingCallSettings + streamingRecognizeSettings; /** Returns the object with the settings used for calls to syncRecognize. */ public SimpleCallSettings syncRecognizeSettings() { @@ -96,6 +93,12 @@ public SimpleCallSettings asyncRecognizeSettin return asyncRecognizeSettings; } + /** Returns the object with the settings used for calls to streamingRecognize. */ + public StreamingCallSettings + streamingRecognizeSettings() { + return streamingRecognizeSettings; + } + /** Returns the default service address. */ public static String getDefaultServiceAddress() { return DEFAULT_SERVICE_ADDRESS; @@ -137,16 +140,20 @@ private SpeechSettings(Builder settingsBuilder) throws IOException { syncRecognizeSettings = settingsBuilder.syncRecognizeSettings().build(); asyncRecognizeSettings = settingsBuilder.asyncRecognizeSettings().build(); + streamingRecognizeSettings = settingsBuilder.streamingRecognizeSettings().build(); } /** Builder for SpeechSettings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; private final SimpleCallSettings.Builder syncRecognizeSettings; private final SimpleCallSettings.Builder asyncRecognizeSettings; + private final StreamingCallSettings.Builder< + StreamingRecognizeRequest, StreamingRecognizeResponse> + streamingRecognizeSettings; private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS; @@ -180,14 +187,18 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); syncRecognizeSettings = SimpleCallSettings.newBuilder(SpeechGrpc.METHOD_SYNC_RECOGNIZE); asyncRecognizeSettings = SimpleCallSettings.newBuilder(SpeechGrpc.METHOD_ASYNC_RECOGNIZE); - methodSettingsBuilders = - ImmutableList.of(syncRecognizeSettings, asyncRecognizeSettings); + streamingRecognizeSettings = + StreamingCallSettings.newBuilder(SpeechGrpc.METHOD_STREAMING_RECOGNIZE); + + unaryMethodSettingsBuilders = + ImmutableList.of( + syncRecognizeSettings, asyncRecognizeSettings); } private static Builder createDefault() { @@ -211,14 +222,23 @@ private Builder(SpeechSettings settings) { syncRecognizeSettings = settings.syncRecognizeSettings.toBuilder(); asyncRecognizeSettings = settings.asyncRecognizeSettings.toBuilder(); + streamingRecognizeSettings = settings.streamingRecognizeSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of(syncRecognizeSettings, asyncRecognizeSettings); + unaryMethodSettingsBuilders = + ImmutableList.of( + syncRecognizeSettings, asyncRecognizeSettings); + } + + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); } @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -264,11 +284,14 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } @@ -283,6 +306,12 @@ public SimpleCallSettings.Builder asyncRecogni return asyncRecognizeSettings; } + /** Returns the builder for the settings used for calls to streamingRecognize. */ + public StreamingCallSettings.Builder + streamingRecognizeSettings() { + return streamingRecognizeSettings; + } + @Override public SpeechSettings build() throws IOException { return new SpeechSettings(this); diff --git a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/package-info.java b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/package-info.java index e7348c17639b..392ceaa0b50b 100644 --- a/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/package-info.java +++ b/google-cloud-speech/src/main/java/com/google/cloud/speech/spi/v1beta1/package-info.java @@ -15,7 +15,7 @@ /** * A client to Google Cloud Speech API. * - *

    The interfaces provided are listed below, along with a usage sample + *

    The interfaces provided are listed below, along with usage samples. * *

    ========= SpeechApi ========= * diff --git a/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/MockSpeechImpl.java b/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/MockSpeechImpl.java index a33911f8274b..5ac9a8fe8f21 100644 --- a/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/MockSpeechImpl.java +++ b/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/MockSpeechImpl.java @@ -72,8 +72,25 @@ public void asyncRecognize( @Override public StreamObserver streamingRecognize( - StreamObserver responseObserver) { - System.err.println("Streaming method is not supported."); - return null; + final StreamObserver responseObserver) { + final StreamingRecognizeResponse response = (StreamingRecognizeResponse) responses.remove(); + StreamObserver requestObserver = + new StreamObserver() { + @Override + public void onNext(StreamingRecognizeRequest value) { + responseObserver.onNext(response); + } + + @Override + public void onError(Throwable t) { + responseObserver.onError(t); + } + + @Override + public void onCompleted() { + responseObserver.onCompleted(); + } + }; + return requestObserver; } } diff --git a/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/SpeechTest.java b/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/SpeechTest.java index c59e64f80ddc..d75176903fdf 100644 --- a/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/SpeechTest.java +++ b/google-cloud-speech/src/test/java/com/google/cloud/speech/spi/v1beta1/SpeechTest.java @@ -14,15 +14,20 @@ package com.google.cloud.speech.spi.v1beta1; +import com.google.api.gax.grpc.StreamingCallable; import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; +import com.google.api.gax.testing.MockStreamObserver; import com.google.cloud.speech.v1beta1.AsyncRecognizeRequest; import com.google.cloud.speech.v1beta1.RecognitionAudio; import com.google.cloud.speech.v1beta1.RecognitionConfig; +import com.google.cloud.speech.v1beta1.StreamingRecognizeRequest; +import com.google.cloud.speech.v1beta1.StreamingRecognizeResponse; import com.google.cloud.speech.v1beta1.SyncRecognizeRequest; import com.google.cloud.speech.v1beta1.SyncRecognizeResponse; import com.google.longrunning.Operation; import com.google.protobuf.GeneratedMessageV3; +import io.grpc.stub.StreamObserver; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -113,4 +118,31 @@ public void asyncRecognizeTest() { Assert.assertEquals(config, actualRequest.getConfig()); Assert.assertEquals(audio, actualRequest.getAudio()); } + + @Test + @SuppressWarnings("all") + public void streamingRecognizeTest() throws Exception { + int resultIndex = 520358448; + StreamingRecognizeResponse expectedResponse = + StreamingRecognizeResponse.newBuilder().setResultIndex(resultIndex).build(); + List expectedResponses = new ArrayList<>(); + expectedResponses.add(expectedResponse); + mockSpeech.setResponses(expectedResponses); + StreamingRecognizeRequest request = StreamingRecognizeRequest.newBuilder().build(); + + MockStreamObserver responseObserver = new MockStreamObserver<>(); + + StreamingCallable callable = + api.streamingRecognizeCallable(); + StreamObserver requestObserver = + callable.bidiStreamingCall(responseObserver); + + requestObserver.onNext(request); + requestObserver.onCompleted(); + + List actualResponses = responseObserver.future().get(); + Assert.assertEquals(1, actualResponses.size()); + Assert.assertEquals(expectedResponse, actualResponses.get(0)); + Assert.assertEquals(0, responseObserver.errors().size()); + } } diff --git a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/PagedResponseWrappers.java b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/PagedResponseWrappers.java new file mode 100644 index 000000000000..a13a250ba1e8 --- /dev/null +++ b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/PagedResponseWrappers.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.cloud.trace.spi.v1; + +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseImpl; +import com.google.api.gax.grpc.UnaryCallable; +import com.google.devtools.cloudtrace.v1.ListTracesRequest; +import com.google.devtools.cloudtrace.v1.ListTracesResponse; +import com.google.devtools.cloudtrace.v1.Trace; + +// AUTO-GENERATED DOCUMENTATION AND CLASS +/** + * Wrapper class to contain paged response types for page streaming methods. Each static class + * inside this wrapper class is used as the return type of one of an API method that implements the + * page streaming pattern. + */ +@javax.annotation.Generated("by GAPIC") +public class PagedResponseWrappers { + + public static class ListTracesPagedResponse + extends PagedListResponseImpl { + + public ListTracesPagedResponse( + UnaryCallable callable, + PagedListDescriptor pageDescriptor, + ListTracesRequest request, + CallContext context) { + super(callable, pageDescriptor, request, context); + } + } +} diff --git a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceApi.java b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceApi.java index d990e788a3b6..681bdcb89548 100644 --- a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceApi.java +++ b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceApi.java @@ -13,8 +13,9 @@ */ package com.google.cloud.trace.spi.v1; -import com.google.api.gax.core.PagedListResponse; -import com.google.api.gax.grpc.ApiCallable; +import static com.google.cloud.trace.spi.v1.PagedResponseWrappers.ListTracesPagedResponse; + +import com.google.api.gax.grpc.UnaryCallable; import com.google.devtools.cloudtrace.v1.GetTraceRequest; import com.google.devtools.cloudtrace.v1.ListTracesRequest; import com.google.devtools.cloudtrace.v1.ListTracesResponse; @@ -62,8 +63,8 @@ *

  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -91,12 +92,10 @@ public class TraceServiceApi implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable patchTracesCallable; - private final ApiCallable getTraceCallable; - private final ApiCallable listTracesCallable; - private final ApiCallable< - ListTracesRequest, PagedListResponse> - listTracesPagedCallable; + private final UnaryCallable patchTracesCallable; + private final UnaryCallable getTraceCallable; + private final UnaryCallable listTracesCallable; + private final UnaryCallable listTracesPagedCallable; /** Constructs an instance of TraceServiceApi with default settings. */ public static final TraceServiceApi create() throws IOException { @@ -121,13 +120,14 @@ protected TraceServiceApi(TraceServiceSettings settings) throws IOException { this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.patchTracesCallable = - ApiCallable.create(settings.patchTracesSettings(), this.channel, this.executor); + UnaryCallable.create(settings.patchTracesSettings(), this.channel, this.executor); this.getTraceCallable = - ApiCallable.create(settings.getTraceSettings(), this.channel, this.executor); + UnaryCallable.create(settings.getTraceSettings(), this.channel, this.executor); this.listTracesCallable = - ApiCallable.create(settings.listTracesSettings(), this.channel, this.executor); + UnaryCallable.create(settings.listTracesSettings(), this.channel, this.executor); this.listTracesPagedCallable = - ApiCallable.createPagedVariant(settings.listTracesSettings(), this.channel, this.executor); + UnaryCallable.createPagedVariant( + settings.listTracesSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { closeables.add( @@ -155,8 +155,8 @@ public final TraceServiceSettings getSettings() { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Sends new traces to Cloud Trace or updates existing traces. If the ID of a trace that you send - * matches that of an existing trace, any fields in the existing trace and its spans are + * Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you + * send matches that of an existing trace, any fields in the existing trace and its spans are * overwritten by the provided values, and any new fields provided are merged with the existing * trace data. If the ID does not match, a new trace is created. * @@ -182,8 +182,8 @@ public final void patchTraces(String projectId, Traces traces) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Sends new traces to Cloud Trace or updates existing traces. If the ID of a trace that you send - * matches that of an existing trace, any fields in the existing trace and its spans are + * Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you + * send matches that of an existing trace, any fields in the existing trace and its spans are * overwritten by the provided values, and any new fields provided are merged with the existing * trace data. If the ID does not match, a new trace is created. * @@ -210,8 +210,8 @@ public final void patchTraces(PatchTracesRequest request) { // AUTO-GENERATED DOCUMENTATION AND METHOD /** - * Sends new traces to Cloud Trace or updates existing traces. If the ID of a trace that you send - * matches that of an existing trace, any fields in the existing trace and its spans are + * Sends new traces to Stackdriver Trace or updates existing traces. If the ID of a trace that you + * send matches that of an existing trace, any fields in the existing trace and its spans are * overwritten by the provided values, and any new fields provided are merged with the existing * trace data. If the ID does not match, a new trace is created. * @@ -231,7 +231,7 @@ public final void patchTraces(PatchTracesRequest request) { * } * */ - public final ApiCallable patchTracesCallable() { + public final UnaryCallable patchTracesCallable() { return patchTracesCallable; } @@ -304,7 +304,7 @@ private final Trace getTrace(GetTraceRequest request) { * } * */ - public final ApiCallable getTraceCallable() { + public final UnaryCallable getTraceCallable() { return getTraceCallable; } @@ -326,8 +326,7 @@ public final ApiCallable getTraceCallable() { * @param projectId ID of the Cloud project where the trace data is stored. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse listTraces( - String projectId) { + public final ListTracesPagedResponse listTraces(String projectId) { ListTracesRequest request = ListTracesRequest.newBuilder().setProjectId(projectId).build(); return listTraces(request); } @@ -353,8 +352,7 @@ public final PagedListResponse lis * @param request The request object containing all of the parameters for the API call. * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final PagedListResponse listTraces( - ListTracesRequest request) { + public final ListTracesPagedResponse listTraces(ListTracesRequest request) { return listTracesPagedCallable().call(request); } @@ -370,7 +368,7 @@ public final PagedListResponse lis * ListTracesRequest request = ListTracesRequest.newBuilder() * .setProjectId(projectId) * .build(); - * ListenableFuture<PagedListResponse<ListTracesRequest,ListTracesResponse,Trace>> future = traceServiceApi.listTracesPagedCallable().futureCall(request); + * ListenableFuture<ListTracesPagedResponse> future = traceServiceApi.listTracesPagedCallable().futureCall(request); * // Do something * for (Trace element : future.get().iterateAllElements()) { * // doThingsWith(element); @@ -378,9 +376,7 @@ public final PagedListResponse lis * } * */ - public final ApiCallable< - ListTracesRequest, PagedListResponse> - listTracesPagedCallable() { + public final UnaryCallable listTracesPagedCallable() { return listTracesPagedCallable; } @@ -411,7 +407,7 @@ public final PagedListResponse lis * } * */ - public final ApiCallable listTracesCallable() { + public final UnaryCallable listTracesCallable() { return listTracesCallable; } diff --git a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java index 698295f4b86b..68d5f9a45025 100644 --- a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java +++ b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/TraceServiceSettings.java @@ -13,13 +13,18 @@ */ package com.google.cloud.trace.spi.v1; +import static com.google.cloud.trace.spi.v1.PagedResponseWrappers.ListTracesPagedResponse; + import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; -import com.google.api.gax.grpc.PageStreamingCallSettings; -import com.google.api.gax.grpc.PageStreamingDescriptor; +import com.google.api.gax.grpc.CallContext; +import com.google.api.gax.grpc.PagedCallSettings; +import com.google.api.gax.grpc.PagedListDescriptor; +import com.google.api.gax.grpc.PagedListResponseFactory; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; +import com.google.api.gax.grpc.UnaryCallable; import com.google.auth.Credentials; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; @@ -82,17 +87,9 @@ public class TraceServiceSettings extends ServiceApiSettings { .add("https://www.googleapis.com/auth/trace.readonly") .build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - private final SimpleCallSettings patchTracesSettings; private final SimpleCallSettings getTraceSettings; - private final PageStreamingCallSettings + private final PagedCallSettings listTracesSettings; /** Returns the object with the settings used for calls to patchTraces. */ @@ -106,7 +103,7 @@ public SimpleCallSettings getTraceSettings() { } /** Returns the object with the settings used for calls to listTraces. */ - public PageStreamingCallSettings + public PagedCallSettings listTracesSettings() { return listTracesSettings; } @@ -155,9 +152,9 @@ private TraceServiceSettings(Builder settingsBuilder) throws IOException { listTracesSettings = settingsBuilder.listTracesSettings().build(); } - private static final PageStreamingDescriptor + private static final PagedListDescriptor LIST_TRACES_PAGE_STR_DESC = - new PageStreamingDescriptor() { + new PagedListDescriptor() { @Override public Object emptyToken() { return ""; @@ -191,13 +188,29 @@ public Iterable extractResources(ListTracesResponse payload) { } }; + private static final PagedListResponseFactory< + ListTracesRequest, ListTracesResponse, ListTracesPagedResponse> + LIST_TRACES_PAGE_STR_FACT = + new PagedListResponseFactory< + ListTracesRequest, ListTracesResponse, ListTracesPagedResponse>() { + @Override + public ListTracesPagedResponse createPagedListResponse( + UnaryCallable callable, + ListTracesRequest request, + CallContext context) { + return new ListTracesPagedResponse( + callable, LIST_TRACES_PAGE_STR_DESC, request, context); + } + }; + /** Builder for TraceServiceSettings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; private final SimpleCallSettings.Builder patchTracesSettings; private final SimpleCallSettings.Builder getTraceSettings; - private final PageStreamingCallSettings.Builder + private final PagedCallSettings.Builder< + ListTracesRequest, ListTracesResponse, ListTracesPagedResponse> listTracesSettings; private static final ImmutableMap> RETRYABLE_CODE_DEFINITIONS; @@ -232,18 +245,18 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); patchTracesSettings = SimpleCallSettings.newBuilder(TraceServiceGrpc.METHOD_PATCH_TRACES); getTraceSettings = SimpleCallSettings.newBuilder(TraceServiceGrpc.METHOD_GET_TRACE); listTracesSettings = - PageStreamingCallSettings.newBuilder( - TraceServiceGrpc.METHOD_LIST_TRACES, LIST_TRACES_PAGE_STR_DESC); + PagedCallSettings.newBuilder( + TraceServiceGrpc.METHOD_LIST_TRACES, LIST_TRACES_PAGE_STR_FACT); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( patchTracesSettings, getTraceSettings, listTracesSettings); } @@ -252,7 +265,7 @@ private static Builder createDefault() { builder .patchTracesSettings() - .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("non_idempotent")) + .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent")) .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default")); builder @@ -275,14 +288,21 @@ private Builder(TraceServiceSettings settings) { getTraceSettings = settings.getTraceSettings.toBuilder(); listTracesSettings = settings.listTracesSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of( + unaryMethodSettingsBuilders = + ImmutableList.of( patchTracesSettings, getTraceSettings, listTracesSettings); } + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); + } + @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -328,11 +348,14 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } @@ -347,7 +370,7 @@ public SimpleCallSettings.Builder getTraceSettings() { } /** Returns the builder for the settings used for calls to listTraces. */ - public PageStreamingCallSettings.Builder + public PagedCallSettings.Builder listTracesSettings() { return listTracesSettings; } diff --git a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/package-info.java b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/package-info.java index ade6ff07dc7a..73666c4ec0f8 100644 --- a/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/package-info.java +++ b/google-cloud-trace/src/main/java/com/google/cloud/trace/spi/v1/package-info.java @@ -15,7 +15,7 @@ /** * A client to Stackdriver Trace API. * - *

    The interfaces provided are listed below, along with a usage sample + *

    The interfaces provided are listed below, along with usage samples. * *

    =============== TraceServiceApi =============== * diff --git a/google-cloud-trace/src/test/java/com/google/cloud/trace/spi/v1/TraceServiceTest.java b/google-cloud-trace/src/test/java/com/google/cloud/trace/spi/v1/TraceServiceTest.java index c11b05b0c269..043d10f8f639 100644 --- a/google-cloud-trace/src/test/java/com/google/cloud/trace/spi/v1/TraceServiceTest.java +++ b/google-cloud-trace/src/test/java/com/google/cloud/trace/spi/v1/TraceServiceTest.java @@ -14,7 +14,8 @@ package com.google.cloud.trace.spi.v1; -import com.google.api.gax.core.PagedListResponse; +import static com.google.cloud.trace.spi.v1.PagedResponseWrappers.ListTracesPagedResponse; + import com.google.api.gax.testing.MockGrpcService; import com.google.api.gax.testing.MockServiceHelper; import com.google.common.collect.Lists; @@ -134,8 +135,7 @@ public void listTracesTest() { String projectId = "projectId-1969970175"; - PagedListResponse pagedListResponse = - api.listTraces(projectId); + ListTracesPagedResponse pagedListResponse = api.listTraces(projectId); List resources = Lists.newArrayList(pagedListResponse.iterateAllElements()); Assert.assertEquals(1, resources.size()); diff --git a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorApi.java b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorApi.java index 58672211034a..05843467f51d 100644 --- a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorApi.java +++ b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorApi.java @@ -13,7 +13,7 @@ */ package com.google.cloud.vision.spi.v1; -import com.google.api.gax.grpc.ApiCallable; +import com.google.api.gax.grpc.UnaryCallable; import com.google.cloud.vision.v1.AnnotateImageRequest; import com.google.cloud.vision.v1.BatchAnnotateImagesRequest; import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; @@ -55,8 +55,8 @@ *

  • A "request object" method. This type of method only takes one parameter, a request object, * which must be constructed before the call. Not every API method will have a request object * method. - *
  • A "callable" method. This type of method takes no parameters and returns an immutable - * ApiCallable object, which can be used to initiate calls to the service. + *
  • A "callable" method. This type of method takes no parameters and returns an immutable API + * callable object, which can be used to initiate calls to the service. * * *

    See the individual methods for example code. @@ -84,7 +84,7 @@ public class ImageAnnotatorApi implements AutoCloseable { private final ScheduledExecutorService executor; private final List closeables = new ArrayList<>(); - private final ApiCallable + private final UnaryCallable batchAnnotateImagesCallable; /** Constructs an instance of ImageAnnotatorApi with default settings. */ @@ -110,7 +110,7 @@ protected ImageAnnotatorApi(ImageAnnotatorSettings settings) throws IOException this.channel = settings.getChannelProvider().getOrBuildChannel(this.executor); this.batchAnnotateImagesCallable = - ApiCallable.create(settings.batchAnnotateImagesSettings(), this.channel, this.executor); + UnaryCallable.create(settings.batchAnnotateImagesSettings(), this.channel, this.executor); if (settings.getChannelProvider().shouldAutoClose()) { closeables.add( @@ -201,7 +201,7 @@ private final BatchAnnotateImagesResponse batchAnnotateImages( * } * */ - public final ApiCallable + public final UnaryCallable batchAnnotateImagesCallable() { return batchAnnotateImagesCallable; } diff --git a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorSettings.java b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorSettings.java index e23eb9a78f52..9d4177ce5642 100644 --- a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorSettings.java +++ b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/ImageAnnotatorSettings.java @@ -15,9 +15,9 @@ import com.google.api.gax.core.ConnectionSettings; import com.google.api.gax.core.RetrySettings; -import com.google.api.gax.grpc.ApiCallSettings; import com.google.api.gax.grpc.ServiceApiSettings; import com.google.api.gax.grpc.SimpleCallSettings; +import com.google.api.gax.grpc.UnaryCallSettings; import com.google.auth.Credentials; import com.google.cloud.vision.v1.BatchAnnotateImagesRequest; import com.google.cloud.vision.v1.BatchAnnotateImagesResponse; @@ -72,14 +72,6 @@ public class ImageAnnotatorSettings extends ServiceApiSettings { private static final ImmutableList DEFAULT_SERVICE_SCOPES = ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build(); - /** The default connection settings of the service. */ - public static final ConnectionSettings DEFAULT_CONNECTION_SETTINGS = - ConnectionSettings.newBuilder() - .setServiceAddress(DEFAULT_SERVICE_ADDRESS) - .setPort(DEFAULT_SERVICE_PORT) - .provideCredentialsWith(DEFAULT_SERVICE_SCOPES) - .build(); - private final SimpleCallSettings batchAnnotateImagesSettings; @@ -133,7 +125,7 @@ private ImageAnnotatorSettings(Builder settingsBuilder) throws IOException { /** Builder for ImageAnnotatorSettings. */ public static class Builder extends ServiceApiSettings.Builder { - private final ImmutableList methodSettingsBuilders; + private final ImmutableList unaryMethodSettingsBuilders; private final SimpleCallSettings.Builder< BatchAnnotateImagesRequest, BatchAnnotateImagesResponse> @@ -171,13 +163,13 @@ public static class Builder extends ServiceApiSettings.Builder { } private Builder() { - super(DEFAULT_CONNECTION_SETTINGS); + super(s_getDefaultConnectionSettingsBuilder().build()); batchAnnotateImagesSettings = SimpleCallSettings.newBuilder(ImageAnnotatorGrpc.METHOD_BATCH_ANNOTATE_IMAGES); - methodSettingsBuilders = - ImmutableList.of(batchAnnotateImagesSettings); + unaryMethodSettingsBuilders = + ImmutableList.of(batchAnnotateImagesSettings); } private static Builder createDefault() { @@ -196,13 +188,20 @@ private Builder(ImageAnnotatorSettings settings) { batchAnnotateImagesSettings = settings.batchAnnotateImagesSettings.toBuilder(); - methodSettingsBuilders = - ImmutableList.of(batchAnnotateImagesSettings); + unaryMethodSettingsBuilders = + ImmutableList.of(batchAnnotateImagesSettings); + } + + private static ConnectionSettings.Builder s_getDefaultConnectionSettingsBuilder() { + return ConnectionSettings.newBuilder() + .setServiceAddress(DEFAULT_SERVICE_ADDRESS) + .setPort(DEFAULT_SERVICE_PORT) + .provideCredentialsWith(DEFAULT_SERVICE_SCOPES); } @Override - protected ConnectionSettings getDefaultConnectionSettings() { - return DEFAULT_CONNECTION_SETTINGS; + protected ConnectionSettings.Builder getDefaultConnectionSettingsBuilder() { + return s_getDefaultConnectionSettingsBuilder(); } @Override @@ -248,11 +247,14 @@ public Builder setClientLibHeader(String name, String version) { } /** - * Applies the given settings to all of the API methods in this service. Only values that are - * non-null will be applied, so this method is not capable of un-setting any values. + * Applies the given settings to all of the unary API methods in this service. Only values that + * are non-null will be applied, so this method is not capable of un-setting any values. + * + *

    Note: This method does not support applying settings to streaming methods. */ - public Builder applyToAllApiMethods(ApiCallSettings.Builder apiCallSettings) throws Exception { - super.applyToAllApiMethods(methodSettingsBuilders, apiCallSettings); + public Builder applyToAllApiMethods(UnaryCallSettings.Builder apiCallSettings) + throws Exception { + super.applyToAllApiMethods(unaryMethodSettingsBuilders, apiCallSettings); return this; } diff --git a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/PagedResponseWrappers.java b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/PagedResponseWrappers.java new file mode 100644 index 000000000000..c6501d1fba69 --- /dev/null +++ b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/PagedResponseWrappers.java @@ -0,0 +1,24 @@ +/* + * 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.cloud.vision.spi.v1; + + +// AUTO-GENERATED DOCUMENTATION AND CLASS +/** + * Wrapper class to contain paged response types for page streaming methods. Each static class + * inside this wrapper class is used as the return type of one of an API method that implements the + * page streaming pattern. + */ +@javax.annotation.Generated("by GAPIC") +public class PagedResponseWrappers {} diff --git a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/package-info.java b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/package-info.java index 96458058a2f6..078a9a31bb4b 100644 --- a/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/package-info.java +++ b/google-cloud-vision/src/main/java/com/google/cloud/vision/spi/v1/package-info.java @@ -15,7 +15,7 @@ /** * A client to Google Cloud Vision API. * - *

    The interfaces provided are listed below, along with a usage sample + *

    The interfaces provided are listed below, along with usage samples. * *

    ================= ImageAnnotatorApi ================= * From 76c3a480fb750063bfcd3eb2d969c9cd86e7bfe5 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Fri, 28 Oct 2016 21:26:21 +0200 Subject: [PATCH 27/32] Fix regression in storage url signing of objects with slashes in names (#1348) * Fix regression in storage url signing of objects with slashes in names * Add special characters to signUrl integration test --- .../com/google/cloud/storage/StorageImpl.java | 3 +- .../google/cloud/storage/StorageImplTest.java | 35 +++++++++++++++++-- .../cloud/storage/it/ITStorageTest.java | 2 +- 3 files changed, 36 insertions(+), 4 deletions(-) diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java index 7cdda52aad0d..49cf62baca71 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java @@ -528,7 +528,8 @@ public URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, SignUrlOptio if (blobInfo.getName().startsWith("/")) { path.setLength(path.length() - 1); } - path.append(UrlEscapers.urlPathSegmentEscaper().escape(blobInfo.getName())); + String escapedName = UrlEscapers.urlFragmentEscaper().escape(blobInfo.getName()); + path.append(escapedName.replace("?", "%3F")); stBuilder.append(path); try { byte[] signatureBytes = authCredentials.sign(stBuilder.toString().getBytes(UTF_8)); diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java index 261bfa31512a..7a64a1021ced 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java @@ -1259,7 +1259,7 @@ public void testSignUrlLeadingSlash() throws NoSuchAlgorithmException, InvalidKe storage = options.toBuilder().authCredentials(authCredentials).build().service(); URL url = storage.signUrl(BlobInfo.newBuilder(BUCKET_NAME1, blobName).build(), 14, TimeUnit.DAYS); - String escapedBlobName = UrlEscapers.urlPathSegmentEscaper().escape(blobName); + String escapedBlobName = UrlEscapers.urlFragmentEscaper().escape(blobName); String stringUrl = url.toString(); String expectedUrl = new StringBuilder("https://storage.googleapis.com/").append(BUCKET_NAME1) .append(escapedBlobName).append("?GoogleAccessId=").append(ACCOUNT).append("&Expires=") @@ -1323,7 +1323,8 @@ public void testSignUrlForBlobWithSpecialChars() throws NoSuchAlgorithmException String blobName = "/a" + specialChar + "b"; URL url = storage.signUrl(BlobInfo.newBuilder(BUCKET_NAME1, blobName).build(), 14, TimeUnit.DAYS); - String escapedBlobName = UrlEscapers.urlPathSegmentEscaper().escape(blobName); + String escapedBlobName = + UrlEscapers.urlFragmentEscaper().escape(blobName).replace("?", "%3F"); String stringUrl = url.toString(); String expectedUrl = new StringBuilder("https://storage.googleapis.com/").append(BUCKET_NAME1) .append(escapedBlobName).append("?GoogleAccessId=").append(ACCOUNT).append("&Expires=") @@ -1343,6 +1344,36 @@ public void testSignUrlForBlobWithSpecialChars() throws NoSuchAlgorithmException } } + @Test + public void testSignUrlForBlobWithSlashes() throws NoSuchAlgorithmException, + InvalidKeyException, SignatureException, UnsupportedEncodingException { + EasyMock.replay(storageRpcMock); + ServiceAccountAuthCredentials authCredentials = + ServiceAccountAuthCredentials.createFor(ACCOUNT, privateKey); + storage = options.toBuilder().authCredentials(authCredentials).build().service(); + + String blobName = "/foo/bar/baz #%20other cool stuff.txt"; + URL url = + storage.signUrl(BlobInfo.newBuilder(BUCKET_NAME1, blobName).build(), 14, TimeUnit.DAYS); + String escapedBlobName = UrlEscapers.urlFragmentEscaper().escape(blobName); + String stringUrl = url.toString(); + String expectedUrl = new StringBuilder("https://storage.googleapis.com/").append(BUCKET_NAME1) + .append(escapedBlobName).append("?GoogleAccessId=").append(ACCOUNT).append("&Expires=") + .append(42L + 1209600).append("&Signature=").toString(); + assertTrue(stringUrl.startsWith(expectedUrl)); + String signature = stringUrl.substring(expectedUrl.length()); + + StringBuilder signedMessageBuilder = new StringBuilder(); + signedMessageBuilder.append(HttpMethod.GET).append("\n\n\n").append(42L + 1209600) + .append("\n/").append(BUCKET_NAME1).append(escapedBlobName); + + Signature signer = Signature.getInstance("SHA256withRSA"); + signer.initVerify(publicKey); + signer.update(signedMessageBuilder.toString().getBytes(UTF_8)); + assertTrue(signer.verify(BaseEncoding.base64().decode( + URLDecoder.decode(signature, UTF_8.name())))); + } + @Test public void testGetAllArray() { BlobId blobId1 = BlobId.of(BUCKET_NAME1, BLOB_NAME1); diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java index 3a9b7c16c93c..6a06b3abcd77 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java @@ -1193,7 +1193,7 @@ public void testWriteChannelExistingBlob() throws IOException { @Test public void testGetSignedUrl() throws IOException { - String blobName = "test-get-signed-url-blob"; + String blobName = "test-get-signed-url-blob/with/slashes/and?special=!#$&'()*+,:;=?@[]"; BlobInfo blob = BlobInfo.newBuilder(BUCKET, blobName).build(); Blob remoteBlob = storage.create(blob, BLOB_BYTE_CONTENT); assertNotNull(remoteBlob); From 0a5a27f067ee4b649148ea90974b6536a7f5b671 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Fri, 28 Oct 2016 22:15:39 +0200 Subject: [PATCH 28/32] Rename setters/getters/builders for core classes to meet proto conventions (#1341) * Rename setters/getters/builders for core classes to meet proto conventions * Update examples, snippets and READMEs to use renamed core getters/setters/builders --- README.md | 52 +- TESTING.md | 38 +- google-cloud-bigquery/README.md | 2 +- .../com/google/cloud/bigquery/BigQuery.java | 18 + .../cloud/bigquery/BigQueryException.java | 6 +- .../google/cloud/bigquery/BigQueryImpl.java | 136 ++- .../cloud/bigquery/BigQueryOptions.java | 18 +- .../com/google/cloud/bigquery/Dataset.java | 4 +- .../java/com/google/cloud/bigquery/Job.java | 8 +- .../google/cloud/bigquery/QueryResult.java | 20 +- .../java/com/google/cloud/bigquery/Table.java | 4 +- .../cloud/bigquery/TableDataWriteChannel.java | 10 +- .../google/cloud/bigquery/package-info.java | 4 +- .../bigquery/spi/DefaultBigQueryRpc.java | 28 +- .../testing/RemoteBigQueryHelper.java | 45 +- .../cloud/bigquery/testing/package-info.java | 2 +- .../cloud/bigquery/BigQueryExceptionTest.java | 76 +- .../cloud/bigquery/BigQueryImplTest.java | 216 ++-- .../cloud/bigquery/DatasetInfoTest.java | 3 +- .../google/cloud/bigquery/DatasetTest.java | 46 +- .../cloud/bigquery/InsertAllRequestTest.java | 3 +- .../com/google/cloud/bigquery/JobTest.java | 45 +- .../cloud/bigquery/QueryResponseTest.java | 6 + .../cloud/bigquery/QueryResultTest.java | 20 +- .../cloud/bigquery/SerializationTest.java | 14 +- .../bigquery/StandardTableDefinitionTest.java | 3 +- .../bigquery/TableDataWriteChannelTest.java | 28 +- .../com/google/cloud/bigquery/TableTest.java | 50 +- .../bigquery/UserDefinedFunctionTest.java | 4 +- .../cloud/bigquery/it/ITBigQueryTest.java | 30 +- .../testing/RemoteBigQueryHelperTest.java | 17 +- google-cloud-compute/README.md | 8 +- .../com/google/cloud/compute/Address.java | 4 +- .../com/google/cloud/compute/Compute.java | 102 +- .../cloud/compute/ComputeException.java | 2 +- .../com/google/cloud/compute/ComputeImpl.java | 389 ++++--- .../google/cloud/compute/ComputeOptions.java | 18 +- .../java/com/google/cloud/compute/Disk.java | 4 +- .../java/com/google/cloud/compute/Image.java | 4 +- .../com/google/cloud/compute/Instance.java | 4 +- .../com/google/cloud/compute/Network.java | 4 +- .../com/google/cloud/compute/Operation.java | 8 +- .../com/google/cloud/compute/Snapshot.java | 4 +- .../com/google/cloud/compute/Subnetwork.java | 4 +- .../google/cloud/compute/package-info.java | 4 +- .../cloud/compute/spi/DefaultComputeRpc.java | 145 +-- .../compute/testing/RemoteComputeHelper.java | 45 +- .../cloud/compute/testing/package-info.java | 2 +- .../com/google/cloud/compute/AddressTest.java | 18 +- .../cloud/compute/ComputeExceptionTest.java | 42 +- .../google/cloud/compute/ComputeImplTest.java | 993 +++++++++--------- .../com/google/cloud/compute/DiskTest.java | 41 +- .../com/google/cloud/compute/ImageTest.java | 22 +- .../google/cloud/compute/InstanceTest.java | 112 +- .../com/google/cloud/compute/NetworkTest.java | 22 +- .../google/cloud/compute/OperationTest.java | 44 +- .../cloud/compute/SerializationTest.java | 14 +- .../google/cloud/compute/SnapshotTest.java | 18 +- .../StorageImageConfigurationTest.java | 6 +- .../google/cloud/compute/SubnetworkTest.java | 18 +- .../cloud/compute/it/ITComputeTest.java | 2 +- .../testing/RemoteComputeHelperTest.java | 16 +- .../nio/CloudStorageFileSystemProvider.java | 8 +- .../CloudStorageFileAttributeViewTest.java | 2 +- .../nio/CloudStorageFileAttributesTest.java | 2 +- .../CloudStorageFileSystemProviderTest.java | 2 +- .../nio/CloudStorageFileSystemTest.java | 4 +- .../CloudStorageLateInitializationTest.java | 8 +- .../contrib/nio/CloudStorageOptionsTest.java | 2 +- .../contrib/nio/CloudStoragePathTest.java | 2 +- .../contrib/nio/LocalStorageHelper.java | 16 +- .../storage/contrib/nio/it/ITGcsNio.java | 2 +- .../main/java/com/google/cloud/AsyncPage.java | 11 +- .../java/com/google/cloud/AsyncPageImpl.java | 20 +- .../com/google/cloud/AuthCredentials.java | 64 +- .../java/com/google/cloud/BaseService.java | 12 +- .../google/cloud/BaseServiceException.java | 86 +- .../com/google/cloud/BaseWriteChannel.java | 92 +- .../main/java/com/google/cloud/ByteArray.java | 7 +- .../com/google/cloud/ExceptionHandler.java | 36 +- .../java/com/google/cloud/FieldSelector.java | 9 +- .../com/google/cloud/GrpcServiceOptions.java | 125 ++- .../com/google/cloud/HttpServiceOptions.java | 74 +- .../main/java/com/google/cloud/Identity.java | 22 +- .../src/main/java/com/google/cloud/Page.java | 21 +- .../main/java/com/google/cloud/PageImpl.java | 29 +- .../main/java/com/google/cloud/Policy.java | 101 +- .../java/com/google/cloud/ReadChannel.java | 7 + .../java/com/google/cloud/RetryHelper.java | 16 +- .../java/com/google/cloud/RetryParams.java | 150 ++- .../src/main/java/com/google/cloud/Role.java | 11 +- .../main/java/com/google/cloud/Service.java | 3 + .../google/cloud/ServiceAccountSigner.java | 6 + .../java/com/google/cloud/ServiceOptions.java | 201 +++- .../java/com/google/cloud/WaitForOption.java | 28 +- .../java/com/google/cloud/WriteChannel.java | 7 + .../com/google/cloud/AsyncPageImplTest.java | 102 +- .../com/google/cloud/AuthCredentialsTest.java | 40 + .../cloud/BaseServiceExceptionTest.java | 96 +- .../google/cloud/BaseWriteChannelTest.java | 38 +- .../google/cloud/ExceptionHandlerTest.java | 14 +- .../google/cloud/FieldSelectorHelperTest.java | 15 + .../google/cloud/GrpcServiceOptionsTest.java | 86 +- .../google/cloud/HttpServiceOptionsTest.java | 52 +- .../java/com/google/cloud/IdentityTest.java | 40 +- .../java/com/google/cloud/PageImplTest.java | 46 +- .../java/com/google/cloud/PolicyTest.java | 105 +- .../com/google/cloud/RetryHelperTest.java | 123 ++- .../com/google/cloud/RetryParamsTest.java | 56 +- .../test/java/com/google/cloud/RoleTest.java | 18 +- .../com/google/cloud/SerializationTest.java | 6 +- .../com/google/cloud/ServiceOptionsTest.java | 58 +- .../com/google/cloud/WaitForOptionTest.java | 19 +- google-cloud-datastore/README.md | 2 +- .../cloud/datastore/DatastoreException.java | 2 +- .../cloud/datastore/DatastoreHelper.java | 2 +- .../google/cloud/datastore/DatastoreImpl.java | 18 +- .../cloud/datastore/DatastoreOptions.java | 41 +- .../com/google/cloud/datastore/GqlQuery.java | 7 +- .../com/google/cloud/datastore/Query.java | 7 +- .../cloud/datastore/QueryResultsImpl.java | 12 +- .../cloud/datastore/StructuredQuery.java | 10 +- .../google/cloud/datastore/package-info.java | 4 +- .../datastore/spi/DefaultDatastoreRpc.java | 10 +- .../testing/LocalDatastoreHelper.java | 10 +- .../testing/RemoteDatastoreHelper.java | 43 +- .../cloud/datastore/testing/package-info.java | 2 +- .../datastore/DatastoreExceptionTest.java | 62 +- .../cloud/datastore/DatastoreHelperTest.java | 4 +- .../cloud/datastore/DatastoreOptionsTest.java | 28 +- .../google/cloud/datastore/DatastoreTest.java | 34 +- .../cloud/datastore/SerializationTest.java | 8 +- .../cloud/datastore/StructuredQueryTest.java | 13 +- .../cloud/datastore/it/ITDatastoreTest.java | 28 +- .../testing/LocalDatastoreHelperTest.java | 16 +- google-cloud-dns/README.md | 2 +- .../com/google/cloud/dns/ChangeRequest.java | 6 +- .../main/java/com/google/cloud/dns/Dns.java | 24 + .../java/com/google/cloud/dns/DnsBatch.java | 19 +- .../com/google/cloud/dns/DnsException.java | 2 +- .../java/com/google/cloud/dns/DnsImpl.java | 56 +- .../java/com/google/cloud/dns/DnsOptions.java | 22 +- .../main/java/com/google/cloud/dns/Zone.java | 4 +- .../com/google/cloud/dns/package-info.java | 4 +- .../google/cloud/dns/spi/DefaultDnsRpc.java | 34 +- .../cloud/dns/testing/LocalDnsHelper.java | 8 +- .../cloud/dns/testing/package-info.java | 2 +- .../google/cloud/dns/ChangeRequestTest.java | 24 +- .../com/google/cloud/dns/DnsBatchTest.java | 88 +- .../google/cloud/dns/DnsExceptionTest.java | 68 +- .../com/google/cloud/dns/DnsImplTest.java | 108 +- .../java/com/google/cloud/dns/DnsTest.java | 32 +- .../google/cloud/dns/SerializationTest.java | 16 +- .../java/com/google/cloud/dns/ZoneTest.java | 10 +- .../com/google/cloud/dns/it/ITDnsTest.java | 121 +-- .../cloud/dns/testing/LocalDnsHelperTest.java | 42 +- .../examples/bigquery/BigQueryExample.java | 6 +- .../snippets/CreateTableAndLoadData.java | 2 +- .../snippets/InsertDataAndQueryTable.java | 2 +- .../examples/compute/ComputeExample.java | 6 +- .../CreateAddressDiskAndInstance.java | 8 +- .../compute/snippets/CreateInstance.java | 2 +- .../compute/snippets/CreateSnapshot.java | 2 +- .../examples/datastore/DatastoreExample.java | 13 +- .../snippets/AddEntitiesAndRunQuery.java | 2 +- .../datastore/snippets/CreateEntity.java | 2 +- .../datastore/snippets/UpdateEntity.java | 2 +- .../google/cloud/examples/dns/DnsExample.java | 8 +- .../snippets/CreateOrUpdateRecordSets.java | 2 +- .../examples/dns/snippets/CreateZone.java | 2 +- .../examples/dns/snippets/DeleteZone.java | 2 +- .../ManipulateZonesAndRecordSets.java | 2 +- .../examples/logging/LoggingExample.java | 8 +- .../snippets/CreateAndListMetrics.java | 2 +- .../logging/snippets/CreateAndListSinks.java | 2 +- .../logging/snippets/LoggingSnippets.java | 4 +- .../snippets/WriteAndListLogEntries.java | 8 +- .../cloud/examples/pubsub/PubSubExample.java | 6 +- .../CreateSubscriptionAndPullMessages.java | 2 +- .../CreateTopicAndPublishMessages.java | 2 +- .../ResourceManagerExample.java | 6 +- .../snippets/GetOrCreateProject.java | 2 +- .../snippets/ModifyPolicy.java | 2 +- .../snippets/UpdateAndListProjects.java | 2 +- .../examples/storage/StorageExample.java | 6 +- .../CreateAndListBucketsAndBlobs.java | 2 +- .../examples/storage/snippets/CreateBlob.java | 2 +- .../examples/storage/snippets/UpdateBlob.java | 2 +- .../examples/translate/TranslateExample.java | 12 +- .../snippets/DetectLanguageAndTranslate.java | 2 +- .../translate/snippets/TranslateSnippets.java | 2 +- .../bigquery/snippets/ITBigQuerySnippets.java | 10 +- .../bigquery/snippets/ITDatasetSnippets.java | 2 +- .../bigquery/snippets/ITJobSnippets.java | 2 +- .../bigquery/snippets/ITTableSnippets.java | 18 +- .../snippets/ITDatastoreSnippets.java | 2 +- .../datastore/snippets/ITQuerySnippets.java | 6 +- .../snippets/ITTransactionSnippets.java | 2 +- .../logging/snippets/ITLoggingSnippets.java | 6 +- .../logging/snippets/ITMetricSnippets.java | 12 +- .../logging/snippets/ITSinkSnippets.java | 15 +- .../pubsub/snippets/ITPubSubSnippets.java | 88 +- .../snippets/ITSubscriptionSnippets.java | 18 +- .../pubsub/snippets/ITTopicSnippets.java | 16 +- .../storage/snippets/ITBlobSnippets.java | 2 +- .../storage/snippets/ITBucketSnippets.java | 2 +- .../storage/snippets/ITStorageSnippets.java | 2 +- .../snippets/ITTranslateSnippets.java | 2 +- google-cloud-logging/README.md | 8 +- .../com/google/cloud/logging/Logging.java | 4 +- .../cloud/logging/LoggingException.java | 2 +- .../google/cloud/logging/LoggingHandler.java | 6 +- .../com/google/cloud/logging/LoggingImpl.java | 79 +- .../google/cloud/logging/LoggingOptions.java | 27 +- .../java/com/google/cloud/logging/Metric.java | 4 +- .../java/com/google/cloud/logging/Sink.java | 4 +- .../google/cloud/logging/package-info.java | 8 +- .../cloud/logging/spi/DefaultLoggingRpc.java | 28 +- .../logging/testing/RemoteLoggingHelper.java | 43 +- .../cloud/logging/testing/package-info.java | 2 +- .../logging/AsyncLoggingHandlerTest.java | 4 +- .../google/cloud/logging/BaseSystemTest.java | 22 +- .../cloud/logging/LoggingHandlerTest.java | 32 +- .../google/cloud/logging/LoggingImplTest.java | 330 +++--- .../com/google/cloud/logging/MetricTest.java | 22 +- .../cloud/logging/SerializationTest.java | 16 +- .../com/google/cloud/logging/SinkTest.java | 22 +- .../cloud/logging/it/ITLoggingTest.java | 2 +- google-cloud-pubsub/README.md | 2 +- .../cloud/pubsub/AckDeadlineRenewer.java | 6 +- .../java/com/google/cloud/pubsub/Message.java | 6 +- .../cloud/pubsub/MessageConsumerImpl.java | 12 +- .../google/cloud/pubsub/PubSubException.java | 2 +- .../com/google/cloud/pubsub/PubSubImpl.java | 95 +- .../google/cloud/pubsub/PubSubOptions.java | 27 +- .../google/cloud/pubsub/ReceivedMessage.java | 4 +- .../com/google/cloud/pubsub/Subscription.java | 4 +- .../google/cloud/pubsub/SubscriptionInfo.java | 37 +- .../java/com/google/cloud/pubsub/Topic.java | 4 +- .../java/com/google/cloud/pubsub/TopicId.java | 4 +- .../com/google/cloud/pubsub/package-info.java | 4 +- .../cloud/pubsub/spi/DefaultPubSubRpc.java | 28 +- .../pubsub/testing/LocalPubsubHelper.java | 10 +- .../cloud/pubsub/testing/package-info.java | 2 +- .../cloud/pubsub/AckDeadlineRenewerTest.java | 22 +- .../google/cloud/pubsub/BaseSystemTest.java | 30 +- .../google/cloud/pubsub/LocalSystemTest.java | 2 +- .../cloud/pubsub/MessageConsumerImplTest.java | 60 +- .../google/cloud/pubsub/PubSubImplTest.java | 190 ++-- .../cloud/pubsub/ReceivedMessageTest.java | 10 +- .../cloud/pubsub/SerializationTest.java | 20 +- .../google/cloud/pubsub/SubscriptionTest.java | 54 +- .../com/google/cloud/pubsub/TopicTest.java | 62 +- .../google/cloud/pubsub/it/ITPubSubTest.java | 18 +- google-cloud-resourcemanager/README.md | 2 +- .../resourcemanager/PolicyMarshaller.java | 14 +- .../google/cloud/resourcemanager/Project.java | 4 +- .../resourcemanager/ResourceManager.java | 6 + .../ResourceManagerException.java | 2 +- .../resourcemanager/ResourceManagerImpl.java | 32 +- .../ResourceManagerOptions.java | 23 +- .../cloud/resourcemanager/package-info.java | 6 +- .../spi/DefaultResourceManagerRpc.java | 12 +- .../testing/LocalResourceManagerHelper.java | 6 +- .../resourcemanager/testing/package-info.java | 2 +- .../resourcemanager/PolicyMarshallerTest.java | 8 +- .../resourcemanager/ProjectInfoTest.java | 3 +- .../cloud/resourcemanager/ProjectTest.java | 33 +- .../ResourceManagerExceptionTest.java | 58 +- .../ResourceManagerImplTest.java | 81 +- .../resourcemanager/SerializationTest.java | 6 +- .../LocalResourceManagerHelperTest.java | 34 +- google-cloud-storage/README.md | 2 +- .../java/com/google/cloud/storage/Blob.java | 11 +- .../google/cloud/storage/BlobReadChannel.java | 33 +- .../cloud/storage/BlobWriteChannel.java | 10 +- .../java/com/google/cloud/storage/Bucket.java | 4 +- .../com/google/cloud/storage/CopyWriter.java | 7 +- .../java/com/google/cloud/storage/Cors.java | 7 +- .../com/google/cloud/storage/Storage.java | 19 +- .../google/cloud/storage/StorageBatch.java | 18 +- .../cloud/storage/StorageException.java | 2 +- .../com/google/cloud/storage/StorageImpl.java | 100 +- .../google/cloud/storage/StorageOptions.java | 21 +- .../google/cloud/storage/package-info.java | 4 +- .../cloud/storage/spi/DefaultStorageRpc.java | 34 +- .../storage/testing/RemoteStorageHelper.java | 49 +- .../cloud/storage/testing/package-info.java | 2 +- .../cloud/storage/BlobReadChannelTest.java | 10 +- .../com/google/cloud/storage/BlobTest.java | 62 +- .../cloud/storage/BlobWriteChannelTest.java | 18 +- .../com/google/cloud/storage/BucketTest.java | 94 +- .../google/cloud/storage/CopyWriterTest.java | 10 +- .../com/google/cloud/storage/CorsTest.java | 2 +- .../cloud/storage/SerializationTest.java | 14 +- .../cloud/storage/StorageBatchTest.java | 16 +- .../cloud/storage/StorageExceptionTest.java | 88 +- .../google/cloud/storage/StorageImplTest.java | 89 +- .../cloud/storage/it/ITStorageTest.java | 17 +- .../testing/RemoteStorageHelperTest.java | 34 +- google-cloud-translate/README.md | 4 +- .../com/google/cloud/translate/Translate.java | 8 +- .../cloud/translate/TranslateException.java | 2 +- .../google/cloud/translate/TranslateImpl.java | 9 +- .../cloud/translate/TranslateOptions.java | 99 +- .../google/cloud/translate/package-info.java | 6 +- .../translate/spi/DefaultTranslateRpc.java | 19 +- .../testing/RemoteTranslateHelper.java | 45 +- .../cloud/translate/testing/package-info.java | 2 +- .../cloud/translate/SerializationTest.java | 8 +- .../translate/TranslateExceptionTest.java | 42 +- .../cloud/translate/TranslateImplTest.java | 21 +- .../cloud/translate/it/ITTranslateTest.java | 3 +- src/site/resources/index.html | 15 +- 314 files changed, 5749 insertions(+), 3595 deletions(-) diff --git a/README.md b/README.md index b51d76f147fd..fddbf051442a 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ Most `google-cloud` libraries require a project ID. There are multiple ways to * Supply the project ID when building the service options. For example, to use Datastore from a project with ID "PROJECT_ID", you can write: ```java - Datastore datastore = DatastoreOptions.builder().projectId("PROJECT_ID").build().service(); + Datastore datastore = DatastoreOptions.newBuilder().setProjectId("PROJECT_ID").build().getService(); ``` * Specify the environment variable `GOOGLE_CLOUD_PROJECT` to be your desired project ID. * Set the project ID using the [Google Cloud SDK](https://cloud.google.com/sdk/?hl=en). To use the SDK, [download the SDK](https://cloud.google.com/sdk/?hl=en) if you haven't already, and set the project ID from the command line. For example: @@ -128,18 +128,18 @@ Next, choose a method for authenticating API requests from within your project: ``` * Supply the JSON credentials file when building the service options. For example, this Storage object has the necessary permissions to interact with your Google Cloud Storage data: ```java - Storage storage = StorageOptions.builder() - .authCredentials(AuthCredentials.createForJson(new FileInputStream("/path/to/my/key.json")) + Storage storage = StorageOptions.newBuilder() + .setAuthCredentials(AuthCredentials.createForJson(new FileInputStream("/path/to/my/key.json")) .build() - .service(); + .getService(); ``` * If running locally for development/testing, you can use Google Cloud SDK. Download the SDK if you haven't already, then login using the SDK (`gcloud auth login` in command line). Be sure to set your project ID as described above. * If you already have an OAuth2 access token, you can use it to authenticate (notice that in this case the access token will not be automatically refreshed): ```java - Storage storage = StorageOptions.builder() - .authCredentials(AuthCredentials.createFor("your_access_token")) + Storage storage = StorageOptions.newBuilder() + .setAuthCredentials(AuthCredentials.createFor("your_access_token")) .build() - .service(); + .getService(); ``` `google-cloud` looks for credentials in the following order, stopping once it finds credentials: @@ -175,7 +175,7 @@ import com.google.cloud.bigquery.Table; import com.google.cloud.bigquery.TableId; import com.google.cloud.bigquery.TableInfo; -BigQuery bigquery = BigQueryOptions.defaultInstance().service(); +BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); TableId tableId = TableId.of("dataset", "table"); Table table = bigquery.getTable(tableId); if (table == null) { @@ -216,7 +216,7 @@ import com.google.cloud.compute.Disk; import com.google.cloud.compute.DiskId; import com.google.cloud.compute.Snapshot; -Compute compute = ComputeOptions.defaultInstance().service(); +Compute compute = ComputeOptions.getDefaultInstance().getService(); DiskId diskId = DiskId.of("us-central1-a", "disk-name"); Disk disk = compute.getDisk(diskId, Compute.DiskOption.fields()); if (disk != null) { @@ -243,7 +243,7 @@ import com.google.cloud.compute.InstanceInfo; import com.google.cloud.compute.MachineTypeId; import com.google.cloud.compute.NetworkId; -Compute compute = ComputeOptions.defaultInstance().service(); +Compute compute = ComputeOptions.getDefaultInstance().getService(); ImageId imageId = ImageId.of("debian-cloud", "debian-8-jessie-v20160329"); NetworkId networkId = NetworkId.of("default"); AttachedDisk attachedDisk = AttachedDisk.of(AttachedDisk.CreateDiskConfiguration.of(imageId)); @@ -282,7 +282,7 @@ import com.google.cloud.datastore.Entity; import com.google.cloud.datastore.Key; import com.google.cloud.datastore.KeyFactory; -Datastore datastore = DatastoreOptions.defaultInstance().service(); +Datastore datastore = DatastoreOptions.getDefaultInstance().getService(); KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind"); Key key = keyFactory.newKey("keyName"); Entity entity = Entity.newBuilder(key) @@ -303,7 +303,7 @@ import com.google.cloud.datastore.Entity; import com.google.cloud.datastore.Key; import com.google.cloud.datastore.KeyFactory; -Datastore datastore = DatastoreOptions.defaultInstance().service(); +Datastore datastore = DatastoreOptions.getDefaultInstance().getService(); KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind"); Key key = keyFactory.newKey("keyName"); Entity entity = datastore.get(key); @@ -336,7 +336,7 @@ import com.google.cloud.dns.DnsOptions; import com.google.cloud.dns.Zone; import com.google.cloud.dns.ZoneInfo; -Dns dns = DnsOptions.defaultInstance().service(); +Dns dns = DnsOptions.getDefaultInstance().getService(); String zoneName = "my-unique-zone"; String domainName = "someexampledomain.com."; String description = "This is a google-cloud-dns sample zone."; @@ -356,7 +356,7 @@ import com.google.cloud.dns.Zone; import java.util.Iterator; import java.util.concurrent.TimeUnit; -Dns dns = DnsOptions.defaultInstance().service(); +Dns dns = DnsOptions.getDefaultInstance().getService(); String zoneName = "my-unique-zone"; Zone zone = dns.getZone(zoneName); String ip = "12.13.14.15"; @@ -371,8 +371,8 @@ ChangeRequestInfo.Builder changeBuilder = ChangeRequestInfo.newBuilder().add(toC Iterator recordSetIterator = zone.listRecordSets().iterateAll(); while (recordSetIterator.hasNext()) { RecordSet current = recordSetIterator.next(); - if (toCreate.name().equals(current.getName()) && - toCreate.type().equals(current.getType())) { + if (toCreate.getName().equals(current.getName()) && + toCreate.getType().equals(current.getType())) { changeBuilder.delete(current); } } @@ -410,19 +410,19 @@ import com.google.cloud.logging.Payload.StringPayload; import java.util.Collections; import java.util.Iterator; -LoggingOptions options = LoggingOptions.defaultInstance(); -try(Logging logging = options.service()) { +LoggingOptions options = LoggingOptions.getDefaultInstance(); +try(Logging logging = options.getService()) { LogEntry firstEntry = LogEntry.newBuilder(StringPayload.of("message")) .setLogName("test-log") - .setResource(MonitoredResource.builder("global") - .addLabel("project_id", options.projectId()) + .setResource(MonitoredResource.newBuilder("global") + .addLabel("project_id", options.getProjectId()) .build()) .build(); logging.write(Collections.singleton(firstEntry)); Page entries = logging.listLogEntries( - EntryListOption.filter("logName=projects/" + options.projectId() + "/logs/test-log")); + EntryListOption.filter("logName=projects/" + options.getProjectId() + "/logs/test-log")); Iterator entryIterator = entries.iterateAll(); while (entryIterator.hasNext()) { System.out.println(entryIterator.next()); @@ -472,7 +472,7 @@ import com.google.cloud.pubsub.PubSubOptions; import com.google.cloud.pubsub.Subscription; import com.google.cloud.pubsub.SubscriptionInfo; -try (PubSub pubsub = PubSubOptions.defaultInstance().service()) { +try (PubSub pubsub = PubSubOptions.getDefaultInstance().getService()) { Subscription subscription = pubsub.create(SubscriptionInfo.of("test-topic", "test-subscription")); MessageProcessor callback = new MessageProcessor() { @@ -506,7 +506,7 @@ import com.google.cloud.resourcemanager.ResourceManagerOptions; import java.util.Iterator; -ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service(); +ResourceManager resourceManager = ResourceManagerOptions.getDefaultInstance().getService(); Project project = resourceManager.get("some-project-id"); // Use an existing project's ID if (project != null) { Project newProject = project.toBuilder() @@ -547,7 +547,7 @@ import com.google.cloud.storage.BlobInfo; import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageOptions; -Storage storage = StorageOptions.defaultInstance().service(); +Storage storage = StorageOptions.getDefaultInstance().getService(); BlobId blobId = BlobId.of("bucket", "blob_name"); BlobInfo blobInfo = BlobInfo.newBuiler(blobId).setContentType("text/plain").build(); Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8)); @@ -566,7 +566,7 @@ import com.google.cloud.storage.StorageOptions; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; -Storage storage = StorageOptions.defaultInstance().service(); +Storage storage = StorageOptions.getDefaultInstance().getService(); BlobId blobId = BlobId.of("bucket", "blob_name"); Blob blob = storage.get(blobId); if (blob != null) { @@ -599,7 +599,7 @@ import com.google.cloud.translate.Translate.TranslateOption; import com.google.cloud.translate.TranslateOptions; import com.google.cloud.translate.Translation; -Translate translate = TranslateOptions.defaultInstance().service(); +Translate translate = TranslateOptions.getDefaultInstance().getService(); Detection detection = translate.detect("Hola"); String detectedLanguage = detection.getLanguage(); diff --git a/TESTING.md b/TESTING.md index 249936c1cf0b..ebb0ee08570b 100644 --- a/TESTING.md +++ b/TESTING.md @@ -27,7 +27,7 @@ Here is an example that uses the `RemoteBigQueryHelper` to create a dataset. ```java RemoteBigQueryHelper bigqueryHelper = RemoteBigQueryHelper.create(PROJECT_ID, new FileInputStream("/path/to/my/JSON/key.json")); - BigQuery bigquery = bigqueryHelper.getOptions().service(); + BigQuery bigquery = bigqueryHelper.getOptions().getService(); String dataset = RemoteBigQueryHelper.generateDatasetName(); bigquery.create(DatasetInfo.newBuilder(dataset).build()); ``` @@ -56,7 +56,7 @@ uses the `RemoteComputeHelper` to create an address. ```java RemoteComputeHelper computeHelper = RemoteBigQueryHelper.create(PROJECT_ID, new FileInputStream("/path/to/my/JSON/key.json")); - Compute compute = computeHelper.options().service(); + Compute compute = computeHelper.getOptions().getService(); // Pick a name for the resource with low probability of clashing String addressName = RemoteComputeHelper.baseResourceName() + "address"; AddressId addressId = RegionAddressId.of(REGION, addressName); @@ -84,7 +84,7 @@ You can test against a temporary local Datastore by following these steps: 2. Create and use a `Datastore` object with the options given by the `LocalDatastoreHelper` instance. For example: ```java - Datastore localDatastore = helper.getOptions().service(); + Datastore localDatastore = helper.getOptions().getService(); ``` 3. Run your tests. @@ -99,12 +99,12 @@ You can test against a temporary local Datastore by following these steps: You can test against a remote Datastore emulator as well. To do this, set the `DatastoreOptions` project endpoint to the hostname of the remote machine, like the example below. ```java - DatastoreOptions options = DatastoreOptions.builder() - .projectId("my-project-id") // must match project ID specified on remote machine - .host("http://:") - .authCredentials(AuthCredentials.noAuth()) + DatastoreOptions options = DatastoreOptions.newBuilder() + .setProjectId("my-project-id") // must match project ID specified on remote machine + .setHost("http://:") + .setAuthCredentials(AuthCredentials.noAuth()) .build(); - Datastore localDatastore = options.service(); + Datastore localDatastore = options.getService(); ``` We recommend that you start the emulator on the remote machine using the [Google Cloud SDK](https://cloud.google.com/sdk/gcloud/reference/beta/emulators/datastore/) from command line, as shown below: @@ -135,7 +135,7 @@ You can test against an in-memory local DNS by following these steps: For example: ```java - Dns dns = LocalDnsHelper.getOptions().service(); + Dns dns = LocalDnsHelper.getOptions().getService(); ``` 3. Run your tests. @@ -164,7 +164,7 @@ uses the `RemoteLoggingHelper` to create a metric. ```java RemoteLoggingHelper loggingHelper = RemoteLoggingHelper.create(PROJECT_ID, new FileInputStream("/path/to/my/JSON/key.json")); - Logging logging = loggingHelper.getOptions().service(); + Logging logging = loggingHelper.getOptions().getService(); // Pick a name for the resource with low probability of clashing String metricName = RemoteLoggingHelper.formatForTest("test-metric"); MetricInfo metricInfo = MetricInfo.of(name, "logName:syslog"); @@ -190,7 +190,7 @@ and `start` methods. This will bind a port for communication with the local Pub/ 2. Create and use a `PubSub` object with the options given by the `LocalPubSubHelper` instance. For example: ```java - PubSub localPubsub = helper.getOptions().service(); + PubSub localPubsub = helper.getOptions().getService(); ``` 3. Run your tests. @@ -206,12 +206,12 @@ You can test against a remote Pub/Sub emulator as well. To do this, set the `Pub endpoint to the hostname of the remote machine, like the example below. ```java - PubSubOptions options = PubSubOptions.builder() - .projectId("my-project-id") // must match project ID specified on remote machine - .host(":") - .authCredentials(AuthCredentials.noAuth()) + PubSubOptions options = PubSubOptions.newBuilder() + .setProjectId("my-project-id") // must match project ID specified on remote machine + .setHost(":") + .setAuthCredentials(AuthCredentials.noAuth()) .build(); - PubSub localPubsub= options.service(); + PubSub localPubsub = options.getService(); ``` ### Testing code that uses Resource Manager @@ -232,7 +232,7 @@ You can test against an in-memory local Resource Manager by following these step 2. In your program, create and use a Resource Manager service object whose host is set to `localhost` at the appropriate port. For example: ```java - ResourceManager resourceManager = LocalResourceManagerHelper.options().service(); + ResourceManager resourceManager = LocalResourceManagerHelper.getOptions().getService(); ``` 3. Run your tests. @@ -258,7 +258,7 @@ Here is an example that uses the `RemoteStorageHelper` to create a bucket. ```java RemoteStorageHelper helper = RemoteStorageHelper.create(PROJECT_ID, new FileInputStream("/path/to/my/JSON/key.json")); - Storage storage = helper.getOptions().service(); + Storage storage = helper.getOptions().getService(); String bucket = RemoteStorageHelper.generateBucketName(); storage.create(BucketInfo.of(bucket)); ``` @@ -285,7 +285,7 @@ key. that uses the `RemoteTranslateHelper` to list supported languages. ```java RemoteTranslateHelper translateHelper = RemoteTranslateHelper.create(PROJECT_ID, API_KEY); - Translate translate = translateHelper.getOptions().service(); + Translate translate = translateHelper.getOptions().getService(); List languages = translate.listSupportedLanguages(); ``` diff --git a/google-cloud-bigquery/README.md b/google-cloud-bigquery/README.md index 0dec46bdb8e0..b31f8706666b 100644 --- a/google-cloud-bigquery/README.md +++ b/google-cloud-bigquery/README.md @@ -85,7 +85,7 @@ code to create your service object: import com.google.cloud.bigquery.BigQuery; import com.google.cloud.bigquery.BigQueryOptions; -BigQuery bigquery = BigQueryOptions.defaultInstance().service(); +BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); ``` For other authentication options, see the diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQuery.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQuery.java index d7a53401aeb7..47a30cfd32aa 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQuery.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQuery.java @@ -65,7 +65,13 @@ enum DatasetField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -106,7 +112,13 @@ enum TableField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -137,7 +149,13 @@ enum JobField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryException.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryException.java index 230527116517..c2ca9fa43d73 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryException.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryException.java @@ -60,8 +60,8 @@ public BigQueryException(int code, String message, BigQueryError error) { public BigQueryException(IOException exception) { super(exception, true); BigQueryError error = null; - if (reason() != null) { - error = new BigQueryError(reason(), location(), getMessage(), debugInfo()); + if (getReason() != null) { + error = new BigQueryError(getReason(), getLocation(), getMessage(), getDebugInfo()); } this.error = error; } @@ -84,7 +84,7 @@ public BigQueryError getError() { } @Override - protected Set retryableErrors() { + protected Set getRetryableErrors() { return RETRYABLE_ERRORS; } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryImpl.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryImpl.java index da8897dfd6cb..238db6c79fb2 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryImpl.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryImpl.java @@ -59,7 +59,13 @@ private static class DatasetPageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listDatasets(projectId, serviceOptions, requestOptions); } } @@ -80,7 +86,13 @@ private static class TablePageFetcher implements NextPageFetcher

  • { } @Override + @Deprecated public Page
    nextPage() { + return getNextPage(); + } + + @Override + public Page
    getNextPage() { return listTables(datasetId, serviceOptions, requestOptions); } } @@ -99,7 +111,13 @@ private static class JobPageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listJobs(serviceOptions, requestOptions); } } @@ -120,7 +138,13 @@ private static class TableDataPageFetcher implements NextPageFetcher> nextPage() { + return getNextPage(); + } + + @Override + public Page> getNextPage() { return listTableData(table, serviceOptions, requestOptions); } } @@ -142,7 +166,13 @@ private static class QueryResultsPageFetcherImpl } @Override + @Deprecated public QueryResult nextPage() { + return getNextPage(); + } + + @Override + public QueryResult getNextPage() { return getQueryResults(job, serviceOptions, requestOptions).getResult(); } } @@ -151,13 +181,13 @@ public QueryResult nextPage() { BigQueryImpl(BigQueryOptions options) { super(options); - bigQueryRpc = options.rpc(); + bigQueryRpc = options.getRpc(); } @Override public Dataset create(DatasetInfo datasetInfo, DatasetOption... options) { final com.google.api.services.bigquery.model.Dataset datasetPb = - datasetInfo.setProjectId(options().projectId()).toPb(); + datasetInfo.setProjectId(getOptions().getProjectId()).toPb(); final Map optionsMap = optionMap(options); try { return Dataset.fromPb(this, @@ -166,7 +196,7 @@ public Dataset create(DatasetInfo datasetInfo, DatasetOption... options) { public com.google.api.services.bigquery.model.Dataset call() { return bigQueryRpc.create(datasetPb, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); } @@ -175,7 +205,7 @@ public com.google.api.services.bigquery.model.Dataset call() { @Override public Table create(TableInfo tableInfo, TableOption... options) { final com.google.api.services.bigquery.model.Table tablePb = - tableInfo.setProjectId(options().projectId()).toPb(); + tableInfo.setProjectId(getOptions().getProjectId()).toPb(); final Map optionsMap = optionMap(options); try { return Table.fromPb(this, @@ -184,7 +214,7 @@ public Table create(TableInfo tableInfo, TableOption... options) { public com.google.api.services.bigquery.model.Table call() { return bigQueryRpc.create(tablePb, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); } @@ -193,7 +223,7 @@ public com.google.api.services.bigquery.model.Table call() { @Override public Job create(JobInfo jobInfo, JobOption... options) { final com.google.api.services.bigquery.model.Job jobPb = - jobInfo.setProjectId(options().projectId()).toPb(); + jobInfo.setProjectId(getOptions().getProjectId()).toPb(); final Map optionsMap = optionMap(options); try { return Job.fromPb(this, @@ -202,7 +232,7 @@ public Job create(JobInfo jobInfo, JobOption... options) { public com.google.api.services.bigquery.model.Job call() { return bigQueryRpc.create(jobPb, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); } @@ -215,7 +245,7 @@ public Dataset getDataset(String datasetId, DatasetOption... options) { @Override public Dataset getDataset(final DatasetId datasetId, DatasetOption... options) { - final DatasetId completeDatasetId = datasetId.setProjectId(options().projectId()); + final DatasetId completeDatasetId = datasetId.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { com.google.api.services.bigquery.model.Dataset answer = @@ -225,7 +255,7 @@ public com.google.api.services.bigquery.model.Dataset call() { return bigQueryRpc.getDataset( completeDatasetId.getProject(), completeDatasetId.getDataset(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Dataset.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); @@ -234,12 +264,12 @@ public com.google.api.services.bigquery.model.Dataset call() { @Override public Page listDatasets(DatasetListOption... options) { - return listDatasets(options().projectId(), options); + return listDatasets(getOptions().getProjectId(), options); } @Override public Page listDatasets(String projectId, DatasetListOption... options) { - return listDatasets(projectId, options(), optionMap(options)); + return listDatasets(projectId, getOptions(), optionMap(options)); } private static Page listDatasets(final String projectId, @@ -251,16 +281,16 @@ private static Page listDatasets(final String projectId, @Override public BigQueryRpc.Tuple> call() { - return serviceOptions.rpc().listDatasets(projectId, optionsMap); + return serviceOptions.getRpc().listDatasets(projectId, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); return new PageImpl<>(new DatasetPageFetcher(projectId, serviceOptions, cursor, optionsMap), cursor, Iterables.transform(result.y(), new Function() { @Override public Dataset apply(com.google.api.services.bigquery.model.Dataset dataset) { - return Dataset.fromPb(serviceOptions.service(), dataset); + return Dataset.fromPb(serviceOptions.getService(), dataset); } })); } catch (RetryHelper.RetryHelperException e) { @@ -275,7 +305,7 @@ public boolean delete(String datasetId, DatasetDeleteOption... options) { @Override public boolean delete(DatasetId datasetId, DatasetDeleteOption... options) { - final DatasetId completeDatasetId = datasetId.setProjectId(options().projectId()); + final DatasetId completeDatasetId = datasetId.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { return runWithRetries(new Callable() { @@ -284,7 +314,7 @@ public Boolean call() { return bigQueryRpc.deleteDataset( completeDatasetId.getProject(), completeDatasetId.getDataset(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); } @@ -297,7 +327,7 @@ public boolean delete(String datasetId, String tableId) { @Override public boolean delete(TableId tableId) { - final TableId completeTableId = tableId.setProjectId(options().projectId()); + final TableId completeTableId = tableId.setProjectId(getOptions().getProjectId()); try { return runWithRetries(new Callable() { @Override @@ -305,7 +335,7 @@ public Boolean call() { return bigQueryRpc.deleteTable(completeTableId.getProject(), completeTableId.getDataset(), completeTableId.getTable()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); } @@ -314,7 +344,7 @@ public Boolean call() { @Override public Dataset update(DatasetInfo datasetInfo, DatasetOption... options) { final com.google.api.services.bigquery.model.Dataset datasetPb = - datasetInfo.setProjectId(options().projectId()).toPb(); + datasetInfo.setProjectId(getOptions().getProjectId()).toPb(); final Map optionsMap = optionMap(options); try { return Dataset.fromPb(this, @@ -323,7 +353,7 @@ public Dataset update(DatasetInfo datasetInfo, DatasetOption... options) { public com.google.api.services.bigquery.model.Dataset call() { return bigQueryRpc.patch(datasetPb, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); } @@ -332,7 +362,7 @@ public com.google.api.services.bigquery.model.Dataset call() { @Override public Table update(TableInfo tableInfo, TableOption... options) { final com.google.api.services.bigquery.model.Table tablePb = - tableInfo.setProjectId(options().projectId()).toPb(); + tableInfo.setProjectId(getOptions().getProjectId()).toPb(); final Map optionsMap = optionMap(options); try { return Table.fromPb(this, @@ -341,7 +371,7 @@ public Table update(TableInfo tableInfo, TableOption... options) { public com.google.api.services.bigquery.model.Table call() { return bigQueryRpc.patch(tablePb, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); } @@ -354,7 +384,7 @@ public Table getTable(final String datasetId, final String tableId, TableOption. @Override public Table getTable(TableId tableId, TableOption... options) { - final TableId completeTableId = tableId.setProjectId(options().projectId()); + final TableId completeTableId = tableId.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { com.google.api.services.bigquery.model.Table answer = @@ -364,7 +394,7 @@ public com.google.api.services.bigquery.model.Table call() { return bigQueryRpc.getTable(completeTableId.getProject(), completeTableId.getDataset(), completeTableId.getTable(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Table.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); @@ -374,13 +404,13 @@ public com.google.api.services.bigquery.model.Table call() { @Override public Page
    listTables(String datasetId, TableListOption... options) { return listTables( - DatasetId.of(options().projectId(), datasetId), options(), optionMap(options)); + DatasetId.of(getOptions().getProjectId(), datasetId), getOptions(), optionMap(options)); } @Override public Page
    listTables(DatasetId datasetId, TableListOption... options) { - DatasetId completeDatasetId = datasetId.setProjectId(options().projectId()); - return listTables(completeDatasetId, options(), optionMap(options)); + DatasetId completeDatasetId = datasetId.setProjectId(getOptions().getProjectId()); + return listTables(completeDatasetId, getOptions(), optionMap(options)); } private static Page
    listTables(final DatasetId datasetId, @@ -392,16 +422,16 @@ private static Page
    listTables(final DatasetId datasetId, @Override public BigQueryRpc.Tuple> call() { - return serviceOptions.rpc().listTables( + return serviceOptions.getRpc().listTables( datasetId.getProject(), datasetId.getDataset(), optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable
    tables = Iterables.transform(result.y(), new Function() { @Override public Table apply(com.google.api.services.bigquery.model.Table table) { - return Table.fromPb(serviceOptions.service(), table); + return Table.fromPb(serviceOptions.getService(), table); } }); return new PageImpl<>(new TablePageFetcher(datasetId, serviceOptions, cursor, optionsMap), @@ -413,7 +443,7 @@ public Table apply(com.google.api.services.bigquery.model.Table table) { @Override public InsertAllResponse insertAll(InsertAllRequest request) { - final TableId tableId = request.getTable().setProjectId(options().projectId()); + final TableId tableId = request.getTable().setProjectId(getOptions().getProjectId()); final TableDataInsertAllRequest requestPb = new TableDataInsertAllRequest(); requestPb.setIgnoreUnknownValues(request.ignoreUnknownValues()); requestPb.setSkipInvalidRows(request.skipInvalidRows()); @@ -433,27 +463,27 @@ public Rows apply(RowToInsert rowToInsert) { @Override public Page> listTableData(String datasetId, String tableId, TableDataListOption... options) { - return listTableData(TableId.of(datasetId, tableId), options(), optionMap(options)); + return listTableData(TableId.of(datasetId, tableId), getOptions(), optionMap(options)); } @Override public Page> listTableData(TableId tableId, TableDataListOption... options) { - return listTableData(tableId, options(), optionMap(options)); + return listTableData(tableId, getOptions(), optionMap(options)); } private static Page> listTableData(final TableId tableId, final BigQueryOptions serviceOptions, final Map optionsMap) { try { - final TableId completeTableId = tableId.setProjectId(serviceOptions.projectId()); + final TableId completeTableId = tableId.setProjectId(serviceOptions.getProjectId()); BigQueryRpc.Tuple> result = runWithRetries(new Callable>>() { @Override public BigQueryRpc.Tuple> call() { - return serviceOptions.rpc() + return serviceOptions.getRpc() .listTableData(completeTableId.getProject(), completeTableId.getDataset(), completeTableId.getTable(), optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); return new PageImpl<>(new TableDataPageFetcher(tableId, serviceOptions, cursor, optionsMap), cursor, transformTableData(result.y())); @@ -481,7 +511,7 @@ public Job getJob(String jobId, JobOption... options) { @Override public Job getJob(JobId jobId, JobOption... options) { final Map optionsMap = optionMap(options); - final JobId completeJobId = jobId.setProjectId(options().projectId()); + final JobId completeJobId = jobId.setProjectId(getOptions().getProjectId()); try { com.google.api.services.bigquery.model.Job answer = runWithRetries(new Callable() { @@ -490,7 +520,7 @@ public com.google.api.services.bigquery.model.Job call() { return bigQueryRpc.getJob(completeJobId.getProject(), completeJobId.getJob(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Job.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); @@ -499,7 +529,7 @@ public com.google.api.services.bigquery.model.Job call() { @Override public Page listJobs(JobListOption... options) { - return listJobs(options(), optionMap(options)); + return listJobs(getOptions(), optionMap(options)); } private static Page listJobs(final BigQueryOptions serviceOptions, @@ -510,15 +540,15 @@ private static Page listJobs(final BigQueryOptions serviceOptions, @Override public BigQueryRpc.Tuple> call() { - return serviceOptions.rpc().listJobs(serviceOptions.projectId(), optionsMap); + return serviceOptions.getRpc().listJobs(serviceOptions.getProjectId(), optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable jobs = Iterables.transform(result.y(), new Function() { @Override public Job apply(com.google.api.services.bigquery.model.Job job) { - return Job.fromPb(serviceOptions.service(), job); + return Job.fromPb(serviceOptions.getService(), job); } }); return new PageImpl<>(new JobPageFetcher(serviceOptions, cursor, optionsMap), cursor, jobs); @@ -531,14 +561,14 @@ public boolean cancel(String jobId) { @Override public boolean cancel(JobId jobId) { - final JobId completeJobId = jobId.setProjectId(options().projectId()); + final JobId completeJobId = jobId.setProjectId(getOptions().getProjectId()); try { return runWithRetries(new Callable() { @Override public Boolean call() { return bigQueryRpc.cancel(completeJobId.getProject(), completeJobId.getJob()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); } @@ -551,9 +581,9 @@ public QueryResponse query(final QueryRequest request) { runWithRetries(new Callable() { @Override public com.google.api.services.bigquery.model.QueryResponse call() { - return bigQueryRpc.query(request.setProjectId(options().projectId()).toPb()); + return bigQueryRpc.query(request.setProjectId(getOptions().getProjectId()).toPb()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); QueryResponse.Builder builder = QueryResponse.newBuilder(); JobId completeJobId = JobId.fromPb(results.getJobReference()); builder.setJobId(completeJobId); @@ -562,7 +592,7 @@ public com.google.api.services.bigquery.model.QueryResponse call() { if (results.getJobComplete()) { builder.setJobCompleted(true); QueryResult.Builder resultBuilder = transformQueryResults(completeJobId, rowsPb, - results.getPageToken(), options(), ImmutableMap.of()); + results.getPageToken(), getOptions(), ImmutableMap.of()); resultBuilder.setTotalBytesProcessed(results.getTotalBytesProcessed()); resultBuilder.setCacheHit(results.getCacheHit()); if (results.getSchema() != null) { @@ -586,21 +616,21 @@ public com.google.api.services.bigquery.model.QueryResponse call() { @Override public QueryResponse getQueryResults(JobId jobId, QueryResultsOption... options) { Map optionsMap = optionMap(options); - return getQueryResults(jobId, options(), optionsMap); + return getQueryResults(jobId, getOptions(), optionsMap); } private static QueryResponse getQueryResults(JobId jobId, final BigQueryOptions serviceOptions, final Map optionsMap) { - final JobId completeJobId = jobId.setProjectId(serviceOptions.projectId()); + final JobId completeJobId = jobId.setProjectId(serviceOptions.getProjectId()); try { GetQueryResultsResponse results = runWithRetries(new Callable() { @Override public GetQueryResultsResponse call() { - return serviceOptions.rpc().getQueryResults( + return serviceOptions.getRpc().getQueryResults( completeJobId.getProject(), completeJobId.getJob(), optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); QueryResponse.Builder builder = QueryResponse.newBuilder(); builder.setJobId(JobId.fromPb(results.getJobReference())); builder.setEtag(results.getEtag()); @@ -641,8 +671,8 @@ private static QueryResult.Builder transformQueryResults(JobId jobId, List
    optionMap(Option... options) { diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryOptions.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryOptions.java index 6ff37d527407..4922a1a8d5d9 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryOptions.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/BigQueryOptions.java @@ -71,17 +71,17 @@ private BigQueryOptions(Builder builder) { } @Override - protected BigQueryFactory defaultServiceFactory() { + protected BigQueryFactory getDefaultServiceFactory() { return DefaultBigqueryFactory.INSTANCE; } @Override - protected BigQueryRpcFactory defaultRpcFactory() { + protected BigQueryRpcFactory getDefaultRpcFactory() { return DefaultBigQueryRpcFactory.INSTANCE; } @Override - protected Set scopes() { + protected Set getScopes() { return SCOPES; } @@ -105,11 +105,21 @@ public boolean equals(Object obj) { return baseEquals(other); } + @Deprecated public static BigQueryOptions defaultInstance() { - return builder().build(); + return getDefaultInstance(); } + public static BigQueryOptions getDefaultInstance() { + return newBuilder().build(); + } + + @Deprecated public static Builder builder() { + return newBuilder(); + } + + public static Builder newBuilder() { return new Builder(); } } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Dataset.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Dataset.java index dc81fa5f1a45..dbec7c013eaa 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Dataset.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Dataset.java @@ -175,7 +175,7 @@ public Dataset build() { Dataset(BigQuery bigquery, DatasetInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.bigquery = checkNotNull(bigquery); - this.options = bigquery.options(); + this.options = bigquery.getOptions(); } /** @@ -362,7 +362,7 @@ public final int hashCode() { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); - this.bigquery = options.service(); + this.bigquery = options.getService(); } static Dataset fromPb(BigQuery bigquery, diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Job.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Job.java index 41d21d7229e0..63e6c725be7c 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Job.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Job.java @@ -133,7 +133,7 @@ public Job build() { Job(BigQuery bigquery, JobInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.bigquery = checkNotNull(bigquery); - this.options = bigquery.options(); + this.options = bigquery.getOptions(); } /** @@ -218,8 +218,8 @@ public boolean isDone() { public Job waitFor(WaitForOption... waitOptions) throws InterruptedException, TimeoutException { Timeout timeout = Timeout.getOrDefault(waitOptions); CheckingPeriod checkingPeriod = CheckingPeriod.getOrDefault(waitOptions); - long timeoutMillis = timeout.timeoutMillis(); - Clock clock = options.clock(); + long timeoutMillis = timeout.getTimeoutMillis(); + Clock clock = options.getClock(); long startTime = clock.millis(); while (!isDone()) { if (timeoutMillis != -1 && (clock.millis() - startTime) >= timeoutMillis) { @@ -317,7 +317,7 @@ public final int hashCode() { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); - this.bigquery = options.service(); + this.bigquery = options.getService(); } static Job fromPb(BigQuery bigquery, com.google.api.services.bigquery.model.Job jobPb) { diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResult.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResult.java index 93626537a79c..d01b2afb24d5 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResult.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/QueryResult.java @@ -34,7 +34,11 @@ public class QueryResult extends PageImpl> { interface QueryResultsPageFetcher extends PageImpl.NextPageFetcher> { @Override + @Deprecated QueryResult nextPage(); + + @Override + QueryResult getNextPage(); } static final class Builder { @@ -159,19 +163,25 @@ public long getTotalRows() { } @Override + @Deprecated public QueryResult nextPage() { - return (QueryResult) super.nextPage(); + return getNextPage(); + } + + @Override + public QueryResult getNextPage() { + return (QueryResult) super.getNextPage(); } @Override public String toString() { return MoreObjects.toStringHelper(this) - .add("rows", values()) + .add("rows", getValues()) .add("cacheHit", cacheHit) .add("schema", schema) .add("totalBytesProcessed", totalBytesProcessed) .add("totalRows", totalRows) - .add("cursor", nextPageCursor()) + .add("cursor", getNextPageCursor()) .toString(); } @@ -189,8 +199,8 @@ public final boolean equals(Object obj) { return false; } QueryResult response = (QueryResult) obj; - return Objects.equals(nextPageCursor(), response.nextPageCursor()) - && Objects.equals(values(), response.values()) + return Objects.equals(getNextPageCursor(), response.getNextPageCursor()) + && Objects.equals(getValues(), response.getValues()) && Objects.equals(schema, response.schema) && totalRows == response.totalRows && totalBytesProcessed == response.totalBytesProcessed diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Table.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Table.java index cf6ccdb52101..154f853a363c 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Table.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/Table.java @@ -163,7 +163,7 @@ public Table build() { Table(BigQuery bigquery, TableInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.bigquery = checkNotNull(bigquery); - this.options = bigquery.options(); + this.options = bigquery.getOptions(); } /** @@ -584,7 +584,7 @@ public final int hashCode() { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); - this.bigquery = options.service(); + this.bigquery = options.getService(); } static Table fromPb(BigQuery bigquery, com.google.api.services.bigquery.model.Table tablePb) { diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TableDataWriteChannel.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TableDataWriteChannel.java index 5c3d9c1fb0be..8c96f4a587d4 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TableDataWriteChannel.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/TableDataWriteChannel.java @@ -47,9 +47,9 @@ protected void flushBuffer(final int length, final boolean last) { runWithRetries(callable(new Runnable() { @Override public void run() { - options().rpc().write(uploadId(), buffer(), 0, position(), length, last); + getOptions().getRpc().write(getUploadId(), getBuffer(), 0, getPosition(), length, last); } - }), options().retryParams(), BigQueryImpl.EXCEPTION_HANDLER, options().clock()); + }), getOptions().getRetryParams(), BigQueryImpl.EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); } @@ -57,7 +57,7 @@ public void run() { @Override protected StateImpl.Builder stateBuilder() { - return StateImpl.builder(options(), entity(), uploadId()); + return StateImpl.builder(getOptions(), getEntity(), getUploadId()); } private static String open(final BigQueryOptions options, @@ -66,9 +66,9 @@ private static String open(final BigQueryOptions options, return runWithRetries(new Callable() { @Override public String call() { - return options.rpc().open(writeChannelConfiguration.toPb()); + return options.getRpc().open(writeChannelConfiguration.toPb()); } - }, options.retryParams(), BigQueryImpl.EXCEPTION_HANDLER, options.clock()); + }, options.getRetryParams(), BigQueryImpl.EXCEPTION_HANDLER, options.getClock()); } catch (RetryHelper.RetryHelperException e) { throw BigQueryException.translateAndThrow(e); } diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/package-info.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/package-info.java index 9421cffb285e..0cd3fcfbdc06 100644 --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/package-info.java +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/package-info.java @@ -22,7 +22,7 @@ * * CreateTableAndLoadData.java. *
     {@code
    - * BigQuery bigquery = BigQueryOptions.defaultInstance().service();
    + * BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService();
      * TableId tableId = TableId.of("dataset", "table");
      * Table table = bigquery.getTable(tableId);
      * if (table == null) {
    @@ -34,7 +34,7 @@
      * System.out.println("Loading data into table " + tableId);
      * Job loadJob = table.load(FormatOptions.csv(), "gs://bucket/path");
      * loadJob = loadJob.waitFor();
    - * if (loadJob.status().error() != null) {
    + * if (loadJob.getStatus().getError() != null) {
      *   System.out.println("Job completed with errors");
      * } else {
      *   System.out.println("Job succeeded");
    diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/spi/DefaultBigQueryRpc.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/spi/DefaultBigQueryRpc.java
    index ef5834db786f..01d64b09f7e4 100644
    --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/spi/DefaultBigQueryRpc.java
    +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/spi/DefaultBigQueryRpc.java
    @@ -80,12 +80,12 @@ public class DefaultBigQueryRpc implements BigQueryRpc {
       private final Bigquery bigquery;
     
       public DefaultBigQueryRpc(BigQueryOptions options) {
    -    HttpTransport transport = options.httpTransportFactory().create();
    -    HttpRequestInitializer initializer = options.httpRequestInitializer();
    +    HttpTransport transport = options.getHttpTransportFactory().create();
    +    HttpRequestInitializer initializer = options.getHttpRequestInitializer();
         this.options = options;
         bigquery = new Bigquery.Builder(transport, new JacksonFactory(), initializer)
    -        .setRootUrl(options.host())
    -        .setApplicationName(options.applicationName())
    +        .setRootUrl(options.getHost())
    +        .setApplicationName(options.getApplicationName())
             .build();
       }
     
    @@ -102,7 +102,7 @@ public Dataset getDataset(String projectId, String datasetId, Map opt
               .execute();
         } catch (IOException ex) {
           BigQueryException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return null;
           }
           throw serviceException;
    @@ -168,7 +168,7 @@ public Table create(Table table, Map options) {
       public Job create(Job job, Map options) {
         try {
           String projectId = job.getJobReference() != null
    -          ? job.getJobReference().getProjectId() : this.options.projectId();
    +          ? job.getJobReference().getProjectId() : this.options.getProjectId();
           return bigquery.jobs()
               .insert(projectId, job)
               .setFields(FIELDS.getString(options))
    @@ -187,7 +187,7 @@ public boolean deleteDataset(String projectId, String datasetId, Map
           return true;
         } catch (IOException ex) {
           BigQueryException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return false;
           }
           throw serviceException;
    @@ -232,7 +232,7 @@ public Table getTable(String projectId, String datasetId, String tableId,
               .execute();
         } catch (IOException ex) {
           BigQueryException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return null;
           }
           throw serviceException;
    @@ -274,7 +274,7 @@ public boolean deleteTable(String projectId, String datasetId, String tableId) {
           return true;
         } catch (IOException ex) {
           BigQueryException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return false;
           }
           throw serviceException;
    @@ -318,7 +318,7 @@ public Job getJob(String projectId, String jobId, Map options) {
               .execute();
         } catch (IOException ex) {
           BigQueryException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return null;
           }
           throw serviceException;
    @@ -373,7 +373,7 @@ public boolean cancel(String projectId, String jobId) {
           return true;
         } catch (IOException ex) {
           BigQueryException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return false;
           }
           throw serviceException;
    @@ -393,7 +393,7 @@ public GetQueryResultsResponse getQueryResults(String projectId, String jobId,
               .execute();
         } catch (IOException ex) {
           BigQueryException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return null;
           }
           throw serviceException;
    @@ -403,7 +403,7 @@ public GetQueryResultsResponse getQueryResults(String projectId, String jobId,
       @Override
       public QueryResponse query(QueryRequest request) {
         try {
    -      return bigquery.jobs().query(this.options.projectId(), request).execute();
    +      return bigquery.jobs().query(this.options.getProjectId(), request).execute();
         } catch (IOException ex) {
           throw translate(ex);
         }
    @@ -415,7 +415,7 @@ public String open(JobConfiguration configuration) {
           Job loadJob = new Job().setConfiguration(configuration);
           StringBuilder builder = new StringBuilder()
               .append(BASE_RESUMABLE_URI)
    -          .append(options.projectId())
    +          .append(options.getProjectId())
               .append("/jobs");
           GenericUrl url = new GenericUrl(builder.toString());
           url.set("uploadType", "resumable");
    diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java
    index 05df90b4dda4..e2f6b5f74bf1 100644
    --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java
    +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelper.java
    @@ -31,12 +31,13 @@
     /**
      * Utility to create a remote BigQuery configuration for testing. BigQuery options can be obtained
      * via the {@link #getOptions()} method. Returned options have custom
    - * {@link BigQueryOptions#retryParams()}: {@link RetryParams#retryMaxAttempts()} is {@code 10},
    - * {@link RetryParams#retryMinAttempts()} is {@code 6}, {@link RetryParams#maxRetryDelayMillis()} is
    - * {@code 30000}, {@link RetryParams#totalRetryPeriodMillis()} is {@code 120000} and
    - * {@link RetryParams#initialRetryDelayMillis()} is {@code 250}.
    - * {@link BigQueryOptions#connectTimeout()} and {@link BigQueryOptions#readTimeout()} are both set
    - * to {@code 60000}.
    + * {@link BigQueryOptions#getRetryParams()}: {@link RetryParams#getRetryMaxAttempts()} is
    + * {@code 10}, {@link RetryParams#getRetryMinAttempts()} is {@code 6},
    + * {@link RetryParams#getMaxRetryDelayMillis()} is {@code 30000},
    + * {@link RetryParams#getTotalRetryPeriodMillis()} is {@code 120000} and
    + * {@link RetryParams#getInitialRetryDelayMillis()} is {@code 250}.
    + * {@link BigQueryOptions#getConnectTimeout()} and {@link BigQueryOptions#getReadTimeout()} are both
    + * set to {@code 60000}.
      */
     public class RemoteBigQueryHelper {
     
    @@ -94,12 +95,12 @@ public static String generateDatasetName() {
       public static RemoteBigQueryHelper create(String projectId, InputStream keyStream)
           throws BigQueryHelperException {
         try {
    -      BigQueryOptions bigqueryOptions = BigQueryOptions.builder()
    -          .authCredentials(AuthCredentials.createForJson(keyStream))
    -          .projectId(projectId)
    -          .retryParams(retryParams())
    -          .connectTimeout(60000)
    -          .readTimeout(60000)
    +      BigQueryOptions bigqueryOptions = BigQueryOptions.newBuilder()
    +          .setAuthCredentials(AuthCredentials.createForJson(keyStream))
    +          .setProjectId(projectId)
    +          .setRetryParams(retryParams())
    +          .setConnectTimeout(60000)
    +          .setReadTimeout(60000)
               .build();
           return new RemoteBigQueryHelper(bigqueryOptions);
         } catch (IOException ex) {
    @@ -115,21 +116,21 @@ public static RemoteBigQueryHelper create(String projectId, InputStream keyStrea
        * credentials.
        */
       public static RemoteBigQueryHelper create() {
    -    BigQueryOptions bigqueryOptions = BigQueryOptions.builder()
    -        .retryParams(retryParams())
    -        .connectTimeout(60000)
    -        .readTimeout(60000)
    +    BigQueryOptions bigqueryOptions = BigQueryOptions.newBuilder()
    +        .setRetryParams(retryParams())
    +        .setConnectTimeout(60000)
    +        .setReadTimeout(60000)
             .build();
         return new RemoteBigQueryHelper(bigqueryOptions);
       }
     
       private static RetryParams retryParams() {
    -    return RetryParams.builder()
    -        .retryMaxAttempts(10)
    -        .retryMinAttempts(6)
    -        .maxRetryDelayMillis(30000)
    -        .totalRetryPeriodMillis(120000)
    -        .initialRetryDelayMillis(250)
    +    return RetryParams.newBuilder()
    +        .setRetryMaxAttempts(10)
    +        .setRetryMinAttempts(6)
    +        .setMaxRetryDelayMillis(30000)
    +        .setTotalRetryPeriodMillis(120000)
    +        .setInitialRetryDelayMillis(250)
             .build();
       }
     
    diff --git a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/package-info.java b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/package-info.java
    index 29fc8243cbf0..30c3bd86564f 100644
    --- a/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/package-info.java
    +++ b/google-cloud-bigquery/src/main/java/com/google/cloud/bigquery/testing/package-info.java
    @@ -22,7 +22,7 @@
      * 

    Before the test: *

     {@code
      * RemoteBigQueryHelper bigqueryHelper = RemoteBigQueryHelper.create();
    - * BigQuery bigquery = bigqueryHelper.getOptions().service();
    + * BigQuery bigquery = bigqueryHelper.getOptions().getService();
      * String dataset = RemoteBigQueryHelper.generateDatasetName();
      * bigquery.create(DatasetInfo.newBuilder(dataset).build());
      * } 
    diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryExceptionTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryExceptionTest.java index 059207df2fe9..f4ccc540508d 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryExceptionTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryExceptionTest.java @@ -39,78 +39,78 @@ public class BigQueryExceptionTest { @Test public void testBigqueryException() { BigQueryException exception = new BigQueryException(500, "message"); - assertEquals(500, exception.code()); + assertEquals(500, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); + assertNull(exception.getReason()); assertNull(exception.getError()); assertNull(exception.error()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new BigQueryException(502, "message"); - assertEquals(502, exception.code()); + assertEquals(502, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); + assertNull(exception.getReason()); assertNull(exception.getError()); assertNull(exception.error()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new BigQueryException(503, "message"); - assertEquals(503, exception.code()); + assertEquals(503, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); + assertNull(exception.getReason()); assertNull(exception.getError()); assertNull(exception.error()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new BigQueryException(504, "message"); - assertEquals(504, exception.code()); + assertEquals(504, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); + assertNull(exception.getReason()); assertNull(exception.getError()); assertNull(exception.error()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new BigQueryException(400, "message"); - assertEquals(400, exception.code()); + assertEquals(400, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); + assertNull(exception.getReason()); assertNull(exception.getError()); assertNull(exception.error()); - assertFalse(exception.retryable()); - assertTrue(exception.idempotent()); + assertFalse(exception.isRetryable()); + assertTrue(exception.isIdempotent()); BigQueryError error = new BigQueryError("reason", null, null); exception = new BigQueryException(504, "message", error); - assertEquals(504, exception.code()); + assertEquals(504, exception.getCode()); assertEquals("message", exception.getMessage()); - assertEquals("reason", exception.reason()); + assertEquals("reason", exception.getReason()); assertEquals(error, exception.getError()); assertEquals(error, exception.error()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); IOException cause = new SocketTimeoutException("socketTimeoutMessage"); exception = new BigQueryException(cause); - assertEquals(BigQueryException.UNKNOWN_CODE, exception.code()); - assertNull(exception.reason()); + assertEquals(BigQueryException.UNKNOWN_CODE, exception.getCode()); + assertNull(exception.getReason()); assertEquals("socketTimeoutMessage", exception.getMessage()); assertEquals(cause, exception.getCause()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); exception = new BigQueryException(504, "message", cause); - assertEquals(504, exception.code()); + assertEquals(504, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); + assertNull(exception.getReason()); assertNull(exception.getError()); assertNull(exception.error()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); } @@ -123,10 +123,10 @@ public void testTranslateAndThrow() throws Exception { try { BigQueryException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(503, ex.code()); + assertEquals(503, ex.getCode()); assertEquals("message", ex.getMessage()); - assertTrue(ex.retryable()); - assertTrue(ex.idempotent()); + assertTrue(ex.isRetryable()); + assertTrue(ex.isIdempotent()); } finally { verify(exceptionMock); } @@ -138,10 +138,10 @@ public void testTranslateAndThrow() throws Exception { try { BigQueryException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(BigQueryException.UNKNOWN_CODE, ex.code()); + assertEquals(BigQueryException.UNKNOWN_CODE, ex.getCode()); assertEquals("message", ex.getMessage()); - assertFalse(ex.retryable()); - assertTrue(ex.idempotent()); + assertFalse(ex.isRetryable()); + assertTrue(ex.isIdempotent()); assertSame(cause, ex.getCause()); } finally { verify(exceptionMock); diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryImplTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryImplTest.java index 6648b0d17508..3a56df01c559 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryImplTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/BigQueryImplTest.java @@ -273,10 +273,10 @@ public void setUp() { EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(BigQueryOptions.class))) .andReturn(bigqueryRpcMock); EasyMock.replay(rpcFactoryMock); - options = BigQueryOptions.builder() - .projectId(PROJECT) - .serviceRpcFactory(rpcFactoryMock) - .retryParams(RetryParams.noRetries()) + options = BigQueryOptions.newBuilder() + .setProjectId(PROJECT) + .setServiceRpcFactory(rpcFactoryMock) + .setRetryParams(RetryParams.noRetries()) .build(); } @@ -288,8 +288,8 @@ public void tearDown() { @Test public void testGetOptions() { EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); - assertSame(options, bigquery.options()); + bigquery = options.getService(); + assertSame(options, bigquery.getOptions()); } @Test @@ -298,7 +298,7 @@ public void testCreateDataset() { EasyMock.expect(bigqueryRpcMock.create(datasetInfo.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(datasetInfo.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Dataset dataset = bigquery.create(datasetInfo); assertEquals(new Dataset(bigquery, new DatasetInfo.BuilderImpl(datasetInfo)), dataset); } @@ -310,7 +310,7 @@ public void testCreateDatasetWithSelectedFields() { capture(capturedOptions))) .andReturn(DATASET_INFO_WITH_PROJECT.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Dataset dataset = bigquery.create(DATASET_INFO, DATASET_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(DATASET_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("datasetReference")); @@ -326,7 +326,7 @@ public void testGetDataset() { EasyMock.expect(bigqueryRpcMock.getDataset(PROJECT, DATASET, EMPTY_RPC_OPTIONS)) .andReturn(DATASET_INFO_WITH_PROJECT.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Dataset dataset = bigquery.getDataset(DATASET); assertEquals(new Dataset(bigquery, new DatasetInfo.BuilderImpl(DATASET_INFO_WITH_PROJECT)), dataset); @@ -337,7 +337,7 @@ public void testGetDatasetFromDatasetId() { EasyMock.expect(bigqueryRpcMock.getDataset(PROJECT, DATASET, EMPTY_RPC_OPTIONS)) .andReturn(DATASET_INFO_WITH_PROJECT.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Dataset dataset = bigquery.getDataset(DatasetId.of(DATASET)); assertEquals(new Dataset(bigquery, new DatasetInfo.BuilderImpl(DATASET_INFO_WITH_PROJECT)), dataset); @@ -350,7 +350,7 @@ public void testGetDatasetFromDatasetIdWithProject() { EasyMock.expect(bigqueryRpcMock.getDataset(OTHER_PROJECT, DATASET, EMPTY_RPC_OPTIONS)) .andReturn(datasetInfo.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Dataset dataset = bigquery.getDataset(datasetId); assertEquals(new Dataset(bigquery, new DatasetInfo.BuilderImpl(datasetInfo)), dataset); } @@ -361,7 +361,7 @@ public void testGetDatasetWithSelectedFields() { EasyMock.expect(bigqueryRpcMock.getDataset(eq(PROJECT), eq(DATASET), capture(capturedOptions))) .andReturn(DATASET_INFO_WITH_PROJECT.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Dataset dataset = bigquery.getDataset(DATASET, DATASET_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(DATASET_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("datasetReference")); @@ -374,7 +374,7 @@ public void testGetDatasetWithSelectedFields() { @Test public void testListDatasets() { - bigquery = options.service(); + bigquery = options.getService(); ImmutableList datasetList = ImmutableList.of( new Dataset(bigquery, new DatasetInfo.BuilderImpl(DATASET_INFO_WITH_PROJECT)), new Dataset(bigquery, new DatasetInfo.BuilderImpl(OTHER_DATASET_INFO))); @@ -383,13 +383,14 @@ public void testListDatasets() { EasyMock.expect(bigqueryRpcMock.listDatasets(PROJECT, EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(bigqueryRpcMock); Page page = bigquery.listDatasets(); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(datasetList.toArray(), Iterables.toArray(page.values(), DatasetInfo.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(datasetList.toArray(), + Iterables.toArray(page.getValues(), DatasetInfo.class)); } @Test public void testListDatasetsWithProjects() { - bigquery = options.service(); + bigquery = options.getService(); ImmutableList datasetList = ImmutableList.of(new Dataset(bigquery, new DatasetInfo.BuilderImpl(DATASET_INFO.setProjectId(OTHER_PROJECT)))); Tuple> result = @@ -398,8 +399,9 @@ public void testListDatasetsWithProjects() { .andReturn(result); EasyMock.replay(bigqueryRpcMock); Page page = bigquery.listDatasets(OTHER_PROJECT); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(datasetList.toArray(), Iterables.toArray(page.values(), DatasetInfo.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(datasetList.toArray(), + Iterables.toArray(page.getValues(), DatasetInfo.class)); } @Test @@ -409,16 +411,16 @@ public void testListEmptyDatasets() { Tuple.>of(null, datasets); EasyMock.expect(bigqueryRpcMock.listDatasets(PROJECT, EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Page page = bigquery.listDatasets(); - assertNull(page.nextPageCursor()); + assertNull(page.getNextPageCursor()); assertArrayEquals(ImmutableList.of().toArray(), - Iterables.toArray(page.values(), Dataset.class)); + Iterables.toArray(page.getValues(), Dataset.class)); } @Test public void testListDatasetsWithOptions() { - bigquery = options.service(); + bigquery = options.getService(); ImmutableList datasetList = ImmutableList.of( new Dataset(bigquery, new DatasetInfo.BuilderImpl(DATASET_INFO_WITH_PROJECT)), new Dataset(bigquery, new DatasetInfo.BuilderImpl(OTHER_DATASET_INFO))); @@ -428,8 +430,9 @@ public void testListDatasetsWithOptions() { EasyMock.replay(bigqueryRpcMock); Page page = bigquery.listDatasets(DATASET_LIST_ALL, DATASET_LIST_PAGE_TOKEN, DATASET_LIST_PAGE_SIZE); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(datasetList.toArray(), Iterables.toArray(page.values(), DatasetInfo.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(datasetList.toArray(), + Iterables.toArray(page.getValues(), DatasetInfo.class)); } @Test @@ -437,7 +440,7 @@ public void testDeleteDataset() { EasyMock.expect(bigqueryRpcMock.deleteDataset(PROJECT, DATASET, EMPTY_RPC_OPTIONS)) .andReturn(true); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); assertTrue(bigquery.delete(DATASET)); } @@ -446,7 +449,7 @@ public void testDeleteDatasetFromDatasetId() { EasyMock.expect(bigqueryRpcMock.deleteDataset(PROJECT, DATASET, EMPTY_RPC_OPTIONS)) .andReturn(true); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); assertTrue(bigquery.delete(DatasetId.of(DATASET))); } @@ -456,7 +459,7 @@ public void testDeleteDatasetFromDatasetIdWithProject() { EasyMock.expect(bigqueryRpcMock.deleteDataset(OTHER_PROJECT, DATASET, EMPTY_RPC_OPTIONS)) .andReturn(true); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); assertTrue(bigquery.delete(datasetId)); } @@ -465,7 +468,7 @@ public void testDeleteDatasetWithOptions() { EasyMock.expect(bigqueryRpcMock.deleteDataset(PROJECT, DATASET, DATASET_DELETE_OPTIONS)) .andReturn(true); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); assertTrue(bigquery.delete(DATASET, DATASET_DELETE_CONTENTS)); } @@ -477,7 +480,7 @@ public void testUpdateDataset() { EasyMock.expect(bigqueryRpcMock.patch(updatedDatasetInfo.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(updatedDatasetInfo.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Dataset dataset = bigquery.update(updatedDatasetInfo); assertEquals(new Dataset(bigquery, new DatasetInfo.BuilderImpl(updatedDatasetInfo)), dataset); } @@ -494,7 +497,7 @@ public void testUpdateDatasetWithSelectedFields() { bigqueryRpcMock.patch(eq(updatedDatasetInfoWithProject.toPb()), capture(capturedOptions))) .andReturn(updatedDatasetInfoWithProject.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Dataset dataset = bigquery.update(updatedDatasetInfo, DATASET_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(DATASET_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("datasetReference")); @@ -511,7 +514,7 @@ public void testCreateTable() { EasyMock.expect(bigqueryRpcMock.create(tableInfo.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(tableInfo.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Table table = bigquery.create(tableInfo); assertEquals(new Table(bigquery, new TableInfo.BuilderImpl(tableInfo)), table); } @@ -523,7 +526,7 @@ public void testCreateTableWithSelectedFields() { bigqueryRpcMock.create(eq(TABLE_INFO_WITH_PROJECT.toPb()), capture(capturedOptions))) .andReturn(TABLE_INFO_WITH_PROJECT.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Table table = bigquery.create(TABLE_INFO, TABLE_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(TABLE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("tableReference")); @@ -538,7 +541,7 @@ public void testGetTable() { EasyMock.expect(bigqueryRpcMock.getTable(PROJECT, DATASET, TABLE, EMPTY_RPC_OPTIONS)) .andReturn(TABLE_INFO_WITH_PROJECT.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Table table = bigquery.getTable(DATASET, TABLE); assertEquals(new Table(bigquery, new TableInfo.BuilderImpl(TABLE_INFO_WITH_PROJECT)), table); } @@ -548,7 +551,7 @@ public void testGetTableFromTableId() { EasyMock.expect(bigqueryRpcMock.getTable(PROJECT, DATASET, TABLE, EMPTY_RPC_OPTIONS)) .andReturn(TABLE_INFO_WITH_PROJECT.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Table table = bigquery.getTable(TABLE_ID); assertEquals(new Table(bigquery, new TableInfo.BuilderImpl(TABLE_INFO_WITH_PROJECT)), table); } @@ -560,7 +563,7 @@ public void testGetTableFromTableIdWithProject() { EasyMock.expect(bigqueryRpcMock.getTable(OTHER_PROJECT, DATASET, TABLE, EMPTY_RPC_OPTIONS)) .andReturn(tableInfo.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Table table = bigquery.getTable(tableId); assertEquals(new Table(bigquery, new TableInfo.BuilderImpl(tableInfo)), table); } @@ -572,7 +575,7 @@ public void testGetTableWithSelectedFields() { bigqueryRpcMock.getTable(eq(PROJECT), eq(DATASET), eq(TABLE), capture(capturedOptions))) .andReturn(TABLE_INFO_WITH_PROJECT.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Table table = bigquery.getTable(TABLE_ID, TABLE_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(TABLE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("tableReference")); @@ -584,7 +587,7 @@ public void testGetTableWithSelectedFields() { @Test public void testListTables() { - bigquery = options.service(); + bigquery = options.getService(); ImmutableList
    tableList = ImmutableList.of( new Table(bigquery, new TableInfo.BuilderImpl(TABLE_INFO_WITH_PROJECT)), new Table(bigquery, new TableInfo.BuilderImpl(OTHER_TABLE_INFO))); @@ -594,13 +597,13 @@ public void testListTables() { .andReturn(result); EasyMock.replay(bigqueryRpcMock); Page
    page = bigquery.listTables(DATASET); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(tableList.toArray(), Iterables.toArray(page.values(), Table.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(tableList.toArray(), Iterables.toArray(page.getValues(), Table.class)); } @Test public void testListTablesFromDatasetId() { - bigquery = options.service(); + bigquery = options.getService(); ImmutableList
    tableList = ImmutableList.of( new Table(bigquery, new TableInfo.BuilderImpl(TABLE_INFO_WITH_PROJECT)), new Table(bigquery, new TableInfo.BuilderImpl(OTHER_TABLE_INFO))); @@ -610,13 +613,13 @@ public void testListTablesFromDatasetId() { .andReturn(result); EasyMock.replay(bigqueryRpcMock); Page
    page = bigquery.listTables(DatasetId.of(DATASET)); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(tableList.toArray(), Iterables.toArray(page.values(), Table.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(tableList.toArray(), Iterables.toArray(page.getValues(), Table.class)); } @Test public void testListTablesFromDatasetIdWithProject() { - bigquery = options.service(); + bigquery = options.getService(); ImmutableList
    tableList = ImmutableList.of( new Table(bigquery, new TableInfo.BuilderImpl(TABLE_INFO.setProjectId(OTHER_PROJECT)))); Tuple> result = @@ -625,13 +628,13 @@ public void testListTablesFromDatasetIdWithProject() { .andReturn(result); EasyMock.replay(bigqueryRpcMock); Page
    page = bigquery.listTables(DatasetId.of(OTHER_PROJECT, DATASET)); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(tableList.toArray(), Iterables.toArray(page.values(), Table.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(tableList.toArray(), Iterables.toArray(page.getValues(), Table.class)); } @Test public void testListTablesWithOptions() { - bigquery = options.service(); + bigquery = options.getService(); ImmutableList
    tableList = ImmutableList.of( new Table(bigquery, new TableInfo.BuilderImpl(TABLE_INFO_WITH_PROJECT)), new Table(bigquery, new TableInfo.BuilderImpl(OTHER_TABLE_INFO))); @@ -641,15 +644,15 @@ public void testListTablesWithOptions() { .andReturn(result); EasyMock.replay(bigqueryRpcMock); Page
    page = bigquery.listTables(DATASET, TABLE_LIST_PAGE_SIZE, TABLE_LIST_PAGE_TOKEN); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(tableList.toArray(), Iterables.toArray(page.values(), Table.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(tableList.toArray(), Iterables.toArray(page.getValues(), Table.class)); } @Test public void testDeleteTable() { EasyMock.expect(bigqueryRpcMock.deleteTable(PROJECT, DATASET, TABLE)).andReturn(true); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); assertTrue(bigquery.delete(DATASET, TABLE)); } @@ -657,7 +660,7 @@ public void testDeleteTable() { public void testDeleteTableFromTableId() { EasyMock.expect(bigqueryRpcMock.deleteTable(PROJECT, DATASET, TABLE)).andReturn(true); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); assertTrue(bigquery.delete(TABLE_ID)); } @@ -666,7 +669,7 @@ public void testDeleteTableFromTableIdWithProject() { TableId tableId = TABLE_ID.setProjectId(OTHER_PROJECT); EasyMock.expect(bigqueryRpcMock.deleteTable(OTHER_PROJECT, DATASET, TABLE)).andReturn(true); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); assertTrue(bigquery.delete(tableId)); } @@ -678,7 +681,7 @@ public void testUpdateTable() { EasyMock.expect(bigqueryRpcMock.patch(updatedTableInfo.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(updatedTableInfo.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Table table = bigquery.update(updatedTableInfo); assertEquals(new Table(bigquery, new TableInfo.BuilderImpl(updatedTableInfo)), table); } @@ -693,7 +696,7 @@ public void testUpdateTableWithSelectedFields() { EasyMock.expect(bigqueryRpcMock.patch(eq(updatedTableInfoWithProject.toPb()), capture(capturedOptions))).andReturn(updatedTableInfoWithProject.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Table table = bigquery.update(updatedTableInfo, TABLE_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(TABLE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("tableReference")); @@ -732,7 +735,7 @@ public TableDataInsertAllRequest.Rows apply(RowToInsert rowToInsert) { EasyMock.expect(bigqueryRpcMock.insertAll(PROJECT, DATASET, TABLE, requestPb)) .andReturn(responsePb); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); InsertAllResponse response = bigquery.insertAll(request); assertNotNull(response.getErrorsFor(0L)); assertNull(response.getErrorsFor(1L)); @@ -769,7 +772,7 @@ public TableDataInsertAllRequest.Rows apply(RowToInsert rowToInsert) { EasyMock.expect(bigqueryRpcMock.insertAll(OTHER_PROJECT, DATASET, TABLE, requestPb)) .andReturn(responsePb); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); InsertAllResponse response = bigquery.insertAll(request); assertNotNull(response.getErrorsFor(0L)); assertNull(response.getErrorsFor(1L)); @@ -782,10 +785,10 @@ public void testListTableData() { EasyMock.expect(bigqueryRpcMock.listTableData(PROJECT, DATASET, TABLE, EMPTY_RPC_OPTIONS)) .andReturn(TABLE_DATA_PB); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Page> page = bigquery.listTableData(DATASET, TABLE); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(TABLE_DATA.toArray(), Iterables.toArray(page.values(), List.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(TABLE_DATA.toArray(), Iterables.toArray(page.getValues(), List.class)); } @Test @@ -793,10 +796,10 @@ public void testListTableDataFromTableId() { EasyMock.expect(bigqueryRpcMock.listTableData(PROJECT, DATASET, TABLE, EMPTY_RPC_OPTIONS)) .andReturn(TABLE_DATA_PB); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Page> page = bigquery.listTableData(TableId.of(DATASET, TABLE)); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(TABLE_DATA.toArray(), Iterables.toArray(page.values(), List.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(TABLE_DATA.toArray(), Iterables.toArray(page.getValues(), List.class)); } @Test @@ -806,10 +809,10 @@ public void testListTableDataFromTableIdWithProject() { bigqueryRpcMock.listTableData(OTHER_PROJECT, DATASET, TABLE, EMPTY_RPC_OPTIONS)) .andReturn(TABLE_DATA_PB); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Page> page = bigquery.listTableData(tableId); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(TABLE_DATA.toArray(), Iterables.toArray(page.values(), List.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(TABLE_DATA.toArray(), Iterables.toArray(page.getValues(), List.class)); } @Test @@ -817,11 +820,11 @@ public void testListTableDataWithOptions() { EasyMock.expect(bigqueryRpcMock.listTableData(PROJECT, DATASET, TABLE, TABLE_DATA_LIST_OPTIONS)) .andReturn(TABLE_DATA_PB); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Page> page = bigquery.listTableData(DATASET, TABLE, TABLE_DATA_LIST_PAGE_SIZE, TABLE_DATA_LIST_PAGE_TOKEN, TABLE_DATA_LIST_START_INDEX); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(TABLE_DATA.toArray(), Iterables.toArray(page.values(), List.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(TABLE_DATA.toArray(), Iterables.toArray(page.getValues(), List.class)); } @Test @@ -830,7 +833,7 @@ public void testCreateQueryJob() { JobInfo.of(QUERY_JOB_CONFIGURATION_WITH_PROJECT).toPb(), EMPTY_RPC_OPTIONS)) .andReturn(COMPLETE_QUERY_JOB.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Job job = bigquery.create(QUERY_JOB); assertEquals(new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_QUERY_JOB)), job); } @@ -841,7 +844,7 @@ public void testCreateLoadJob() { JobInfo.of(LOAD_JOB_CONFIGURATION_WITH_PROJECT).toPb(), EMPTY_RPC_OPTIONS)) .andReturn(COMPLETE_LOAD_JOB.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Job job = bigquery.create(LOAD_JOB); assertEquals(new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_LOAD_JOB)), job); } @@ -852,7 +855,7 @@ public void testCreateCopyJob() { JobInfo.of(COPY_JOB_CONFIGURATION_WITH_PROJECT).toPb(), EMPTY_RPC_OPTIONS)) .andReturn(COMPLETE_COPY_JOB.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Job job = bigquery.create(COPY_JOB); assertEquals(new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_COPY_JOB)), job); } @@ -863,7 +866,7 @@ public void testCreateExtractJob() { JobInfo.of(EXTRACT_JOB_CONFIGURATION_WITH_PROJECT).toPb(), EMPTY_RPC_OPTIONS)) .andReturn(COMPLETE_EXTRACT_JOB.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Job job = bigquery.create(EXTRACT_JOB); assertEquals(new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_EXTRACT_JOB)), job); } @@ -875,7 +878,7 @@ public void testCreateJobWithSelectedFields() { eq(JobInfo.of(QUERY_JOB_CONFIGURATION_WITH_PROJECT).toPb()), capture(capturedOptions))) .andReturn(COMPLETE_QUERY_JOB.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Job job = bigquery.create(QUERY_JOB, JOB_OPTION_FIELDS); assertEquals(new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_QUERY_JOB)), job); String selector = (String) capturedOptions.getValue().get(JOB_OPTION_FIELDS.getRpcOption()); @@ -894,7 +897,7 @@ public void testCreateJobWithProjectId() { EasyMock.expect(bigqueryRpcMock.create(eq(jobInfo.toPb()), capture(capturedOptions))) .andReturn(jobInfo.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Job job = bigquery.create(jobInfo, JOB_OPTION_FIELDS); assertEquals(new Job(bigquery, new JobInfo.BuilderImpl(jobInfo)), job); String selector = (String) capturedOptions.getValue().get(JOB_OPTION_FIELDS.getRpcOption()); @@ -909,7 +912,7 @@ public void testGetJob() { EasyMock.expect(bigqueryRpcMock.getJob(PROJECT, JOB, EMPTY_RPC_OPTIONS)) .andReturn(COMPLETE_COPY_JOB.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Job job = bigquery.getJob(JOB); assertEquals(new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_COPY_JOB)), job); } @@ -919,7 +922,7 @@ public void testGetJobFromJobId() { EasyMock.expect(bigqueryRpcMock.getJob(PROJECT, JOB, EMPTY_RPC_OPTIONS)) .andReturn(COMPLETE_COPY_JOB.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Job job = bigquery.getJob(JobId.of(JOB)); assertEquals(new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_COPY_JOB)), job); } @@ -931,14 +934,14 @@ public void testGetJobFromJobIdWithProject() { EasyMock.expect(bigqueryRpcMock.getJob(OTHER_PROJECT, JOB, EMPTY_RPC_OPTIONS)) .andReturn(jobInfo.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); Job job = bigquery.getJob(jobId); assertEquals(new Job(bigquery, new JobInfo.BuilderImpl(jobInfo)), job); } @Test public void testListJobs() { - bigquery = options.service(); + bigquery = options.getService(); ImmutableList jobList = ImmutableList.of( new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_QUERY_JOB)), new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_LOAD_JOB))); @@ -953,13 +956,13 @@ public com.google.api.services.bigquery.model.Job apply(Job job) { EasyMock.expect(bigqueryRpcMock.listJobs(PROJECT, EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(bigqueryRpcMock); Page page = bigquery.listJobs(); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(jobList.toArray(), Iterables.toArray(page.values(), Job.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(jobList.toArray(), Iterables.toArray(page.getValues(), Job.class)); } @Test public void testListJobsWithOptions() { - bigquery = options.service(); + bigquery = options.getService(); ImmutableList jobList = ImmutableList.of( new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_QUERY_JOB)), new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_LOAD_JOB))); @@ -975,14 +978,14 @@ public com.google.api.services.bigquery.model.Job apply(Job job) { EasyMock.replay(bigqueryRpcMock); Page page = bigquery.listJobs(JOB_LIST_ALL_USERS, JOB_LIST_STATE_FILTER, JOB_LIST_PAGE_TOKEN, JOB_LIST_PAGE_SIZE); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(jobList.toArray(), Iterables.toArray(page.values(), Job.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(jobList.toArray(), Iterables.toArray(page.getValues(), Job.class)); } @Test public void testListJobsWithSelectedFields() { Capture> capturedOptions = Capture.newInstance(); - bigquery = options.service(); + bigquery = options.getService(); ImmutableList jobList = ImmutableList.of( new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_QUERY_JOB)), new Job(bigquery, new JobInfo.BuilderImpl(COMPLETE_LOAD_JOB))); @@ -998,8 +1001,8 @@ public com.google.api.services.bigquery.model.Job apply(Job job) { .andReturn(result); EasyMock.replay(bigqueryRpcMock); Page page = bigquery.listJobs(JOB_LIST_OPTION_FIELD); - assertEquals(CURSOR, page.nextPageCursor()); - assertArrayEquals(jobList.toArray(), Iterables.toArray(page.values(), Job.class)); + assertEquals(CURSOR, page.getNextPageCursor()); + assertArrayEquals(jobList.toArray(), Iterables.toArray(page.getValues(), Job.class)); String selector = (String) capturedOptions.getValue().get(JOB_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("nextPageToken,jobs(")); assertTrue(selector.contains("configuration")); @@ -1015,7 +1018,7 @@ public com.google.api.services.bigquery.model.Job apply(Job job) { public void testCancelJob() { EasyMock.expect(bigqueryRpcMock.cancel(PROJECT, JOB)).andReturn(true); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); assertTrue(bigquery.cancel(JOB)); } @@ -1023,7 +1026,7 @@ public void testCancelJob() { public void testCancelJobFromJobId() { EasyMock.expect(bigqueryRpcMock.cancel(PROJECT, JOB)).andReturn(true); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); assertTrue(bigquery.cancel(JobId.of(PROJECT, JOB))); } @@ -1032,7 +1035,7 @@ public void testCancelJobFromJobIdWithProject() { JobId jobId = JobId.of(OTHER_PROJECT, JOB); EasyMock.expect(bigqueryRpcMock.cancel(OTHER_PROJECT, JOB)).andReturn(true); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); assertTrue(bigquery.cancel(jobId)); } @@ -1045,7 +1048,7 @@ public void testQueryRequest() { .setJobComplete(false); EasyMock.expect(bigqueryRpcMock.query(QUERY_REQUEST_WITH_PROJECT.toPb())).andReturn(responsePb); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); QueryResponse response = bigquery.query(QUERY_REQUEST); assertNull(response.getEtag()); assertNull(response.getResult()); @@ -1070,7 +1073,7 @@ public void testQueryRequestCompleted() { .setTotalRows(BigInteger.valueOf(1L)); EasyMock.expect(bigqueryRpcMock.query(QUERY_REQUEST_WITH_PROJECT.toPb())).andReturn(responsePb); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); QueryResponse response = bigquery.query(QUERY_REQUEST); assertNull(response.getEtag()); assertEquals(queryJob, response.getJobId()); @@ -1081,11 +1084,11 @@ public void testQueryRequestCompleted() { assertEquals(null, response.getResult().getSchema()); assertEquals(42L, response.getResult().getTotalBytesProcessed()); assertEquals(1L, response.getResult().getTotalRows()); - for (List row : response.getResult().values()) { + for (List row : response.getResult().getValues()) { assertEquals(false, row.get(0).getBooleanValue()); assertEquals(1L, row.get(1).getLongValue()); } - assertEquals(CURSOR, response.getResult().nextPageCursor()); + assertEquals(CURSOR, response.getResult().getNextPageCursor()); } @Test @@ -1103,7 +1106,7 @@ public void testGetQueryResults() { EasyMock.expect(bigqueryRpcMock.getQueryResults(PROJECT, JOB, EMPTY_RPC_OPTIONS)) .andReturn(responsePb); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); QueryResponse response = bigquery.getQueryResults(queryJob); assertEquals("etag", response.getEtag()); assertEquals(queryJob, response.getJobId()); @@ -1114,11 +1117,11 @@ public void testGetQueryResults() { assertEquals(null, response.getResult().getSchema()); assertEquals(42L, response.getResult().getTotalBytesProcessed()); assertEquals(1L, response.getResult().getTotalRows()); - for (List row : response.getResult().values()) { + for (List row : response.getResult().getValues()) { assertEquals(false, row.get(0).getBooleanValue()); assertEquals(1L, row.get(1).getLongValue()); } - assertEquals(CURSOR, response.getResult().nextPageCursor()); + assertEquals(CURSOR, response.getResult().getNextPageCursor()); } @Test @@ -1136,7 +1139,7 @@ public void testGetQueryResultsWithProject() { EasyMock.expect(bigqueryRpcMock.getQueryResults(OTHER_PROJECT, JOB, EMPTY_RPC_OPTIONS)) .andReturn(responsePb); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); QueryResponse response = bigquery.getQueryResults(queryJob); assertEquals("etag", response.getEtag()); assertEquals(queryJob, response.getJobId()); @@ -1147,11 +1150,11 @@ public void testGetQueryResultsWithProject() { assertEquals(null, response.getResult().getSchema()); assertEquals(42L, response.getResult().getTotalBytesProcessed()); assertEquals(1L, response.getResult().getTotalRows()); - for (List row : response.getResult().values()) { + for (List row : response.getResult().getValues()) { assertEquals(false, row.get(0).getBooleanValue()); assertEquals(1L, row.get(1).getLongValue()); } - assertEquals(CURSOR, response.getResult().nextPageCursor()); + assertEquals(CURSOR, response.getResult().getNextPageCursor()); } @Test @@ -1168,7 +1171,7 @@ public void testGetQueryResultsWithOptions() { EasyMock.expect(bigqueryRpcMock.getQueryResults(PROJECT, JOB, QUERY_RESULTS_OPTIONS)) .andReturn(responsePb); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); QueryResponse response = bigquery.getQueryResults(queryJob, QUERY_RESULTS_OPTION_TIME, QUERY_RESULTS_OPTION_INDEX, QUERY_RESULTS_OPTION_PAGE_SIZE, QUERY_RESULTS_OPTION_PAGE_TOKEN); @@ -1180,11 +1183,11 @@ public void testGetQueryResultsWithOptions() { assertEquals(null, response.getResult().getSchema()); assertEquals(42L, response.getResult().getTotalBytesProcessed()); assertEquals(1L, response.getResult().getTotalRows()); - for (List row : response.getResult().values()) { + for (List row : response.getResult().getValues()) { assertEquals(false, row.get(0).getBooleanValue()); assertEquals(1L, row.get(1).getLongValue()); } - assertEquals(CURSOR, response.getResult().nextPageCursor()); + assertEquals(CURSOR, response.getResult().getNextPageCursor()); } @Test @@ -1194,7 +1197,7 @@ public void testWriter() { bigqueryRpcMock.open(WriteChannelConfiguration.of(TABLE_ID_WITH_PROJECT).toPb())) .andReturn("upload-id"); EasyMock.replay(bigqueryRpcMock); - bigquery = options.service(); + bigquery = options.getService(); WriteChannel channel = bigquery.writer(writeChannelConfiguration); assertNotNull(channel); assertTrue(channel.isOpen()); @@ -1206,7 +1209,8 @@ public void testRetryableException() { .andThrow(new BigQueryException(500, "InternalError")) .andReturn(DATASET_INFO_WITH_PROJECT.toPb()); EasyMock.replay(bigqueryRpcMock); - bigquery = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); + bigquery = + options.toBuilder().setRetryParams(RetryParams.getDefaultInstance()).build().getService(); Dataset dataset = bigquery.getDataset(DATASET); assertEquals(new Dataset(bigquery, new DatasetInfo.BuilderImpl(DATASET_INFO_WITH_PROJECT)), dataset); @@ -1218,7 +1222,8 @@ public void testNonRetryableException() { EasyMock.expect(bigqueryRpcMock.getDataset(PROJECT, DATASET, EMPTY_RPC_OPTIONS)) .andThrow(new BigQueryException(501, exceptionMessage)); EasyMock.replay(bigqueryRpcMock); - bigquery = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); + bigquery = + options.toBuilder().setRetryParams(RetryParams.getDefaultInstance()).build().getService(); thrown.expect(BigQueryException.class); thrown.expectMessage(exceptionMessage); bigquery.getDataset(DatasetId.of(DATASET)); @@ -1230,7 +1235,8 @@ public void testRuntimeException() { EasyMock.expect(bigqueryRpcMock.getDataset(PROJECT, DATASET, EMPTY_RPC_OPTIONS)) .andThrow(new RuntimeException(exceptionMessage)); EasyMock.replay(bigqueryRpcMock); - bigquery = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); + bigquery = + options.toBuilder().setRetryParams(RetryParams.getDefaultInstance()).build().getService(); thrown.expect(BigQueryException.class); thrown.expectMessage(exceptionMessage); bigquery.getDataset(DATASET); diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetInfoTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetInfoTest.java index 4951a8a065a3..14828dec75f3 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetInfoTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetInfoTest.java @@ -86,7 +86,8 @@ public void testToBuilder() { .build(); assertEquals(DatasetId.of("dataset2"), datasetInfo.getDatasetId()); assertEquals("description2", datasetInfo.getDescription()); - datasetInfo = datasetInfo.toBuilder().setDatasetId(DATASET_ID).setDescription("description").build(); + datasetInfo = + datasetInfo.toBuilder().setDatasetId(DATASET_ID).setDescription("description").build(); compareDatasets(DATASET_INFO, datasetInfo); } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetTest.java index 22b78471a2fb..2c585afa264d 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/DatasetTest.java @@ -76,7 +76,7 @@ public class DatasetTest { private Dataset dataset; private void initializeExpectedDataset(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); bigquery = createStrictMock(BigQuery.class); expectedDataset = new Dataset(serviceMockReturnsOptions, new Dataset.BuilderImpl(DATASET_INFO)); @@ -160,7 +160,7 @@ public void testToBuilder() { public void testExists_True() throws Exception { initializeExpectedDataset(1); BigQuery.DatasetOption[] expectedOptions = {BigQuery.DatasetOption.fields()}; - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getDataset(DATASET_INFO.getDatasetId(), expectedOptions)) .andReturn(expectedDataset); replay(bigquery); @@ -172,7 +172,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { initializeExpectedDataset(1); BigQuery.DatasetOption[] expectedOptions = {BigQuery.DatasetOption.fields()}; - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getDataset(DATASET_INFO.getDatasetId(), expectedOptions)).andReturn(null); replay(bigquery); initializeDataset(); @@ -185,7 +185,7 @@ public void testReload() throws Exception { DatasetInfo updatedInfo = DATASET_INFO.toBuilder().setDescription("Description").build(); Dataset expectedDataset = new Dataset(serviceMockReturnsOptions, new DatasetInfo.BuilderImpl(updatedInfo)); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect( bigquery.getDataset(DATASET_INFO.getDatasetId().getDataset())).andReturn(expectedDataset); replay(bigquery); @@ -197,7 +197,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedDataset(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getDataset(DATASET_INFO.getDatasetId().getDataset())).andReturn(null); replay(bigquery); initializeDataset(); @@ -210,7 +210,7 @@ public void testReloadWithOptions() throws Exception { DatasetInfo updatedInfo = DATASET_INFO.toBuilder().setDescription("Description").build(); Dataset expectedDataset = new Dataset(serviceMockReturnsOptions, new DatasetInfo.BuilderImpl(updatedInfo)); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getDataset(DATASET_INFO.getDatasetId().getDataset(), BigQuery.DatasetOption.fields())).andReturn(expectedDataset); replay(bigquery); @@ -224,7 +224,7 @@ public void testUpdate() { initializeExpectedDataset(4); Dataset expectedUpdatedDataset = expectedDataset.toBuilder().setDescription("Description").build(); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.update(eq(expectedDataset))).andReturn(expectedUpdatedDataset); replay(bigquery); initializeDataset(); @@ -237,7 +237,7 @@ public void testUpdateWithOptions() { initializeExpectedDataset(4); Dataset expectedUpdatedDataset = expectedDataset.toBuilder().setDescription("Description").build(); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.update(eq(expectedDataset), eq(BigQuery.DatasetOption.fields()))) .andReturn(expectedUpdatedDataset); replay(bigquery); @@ -249,7 +249,7 @@ public void testUpdateWithOptions() { @Test public void testDeleteTrue() { initializeExpectedDataset(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.delete(DATASET_INFO.getDatasetId())).andReturn(true); replay(bigquery); initializeDataset(); @@ -259,7 +259,7 @@ public void testDeleteTrue() { @Test public void testDeleteFalse() { initializeExpectedDataset(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.delete(DATASET_INFO.getDatasetId())).andReturn(false); replay(bigquery); initializeDataset(); @@ -274,13 +274,14 @@ public void testList() throws Exception { new Table(serviceMockReturnsOptions, new Table.BuilderImpl(TABLE_INFO2)), new Table(serviceMockReturnsOptions, new Table.BuilderImpl(TABLE_INFO3))); PageImpl
    expectedPage = new PageImpl<>(null, "c", tableResults); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.listTables(DATASET_INFO.getDatasetId())).andReturn(expectedPage); replay(bigquery); initializeDataset(); Page
    tablePage = dataset.list(); - assertArrayEquals(tableResults.toArray(), Iterables.toArray(tablePage.values(), Table.class)); - assertEquals(expectedPage.nextPageCursor(), tablePage.nextPageCursor()); + assertArrayEquals(tableResults.toArray(), + Iterables.toArray(tablePage.getValues(), Table.class)); + assertEquals(expectedPage.getNextPageCursor(), tablePage.getNextPageCursor()); } @Test @@ -291,14 +292,15 @@ public void testListWithOptions() throws Exception { new Table(serviceMockReturnsOptions, new Table.BuilderImpl(TABLE_INFO2)), new Table(serviceMockReturnsOptions, new Table.BuilderImpl(TABLE_INFO3))); PageImpl
    expectedPage = new PageImpl<>(null, "c", tableResults); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.listTables(DATASET_INFO.getDatasetId(), BigQuery.TableListOption.pageSize(10L))) .andReturn(expectedPage); replay(bigquery); initializeDataset(); Page
    tablePage = dataset.list(BigQuery.TableListOption.pageSize(10L)); - assertArrayEquals(tableResults.toArray(), Iterables.toArray(tablePage.values(), Table.class)); - assertEquals(expectedPage.nextPageCursor(), tablePage.nextPageCursor()); + assertArrayEquals(tableResults.toArray(), + Iterables.toArray(tablePage.getValues(), Table.class)); + assertEquals(expectedPage.getNextPageCursor(), tablePage.getNextPageCursor()); } @Test @@ -306,7 +308,7 @@ public void testGet() throws Exception { initializeExpectedDataset(2); Table expectedTable = new Table(serviceMockReturnsOptions, new TableInfo.BuilderImpl(TABLE_INFO1)); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getTable(TABLE_INFO1.getTableId())).andReturn(expectedTable); replay(bigquery); initializeDataset(); @@ -318,7 +320,7 @@ public void testGet() throws Exception { @Test public void testGetNull() throws Exception { initializeExpectedDataset(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getTable(TABLE_INFO1.getTableId())).andReturn(null); replay(bigquery); initializeDataset(); @@ -330,7 +332,7 @@ public void testGetWithOptions() throws Exception { initializeExpectedDataset(2); Table expectedTable = new Table(serviceMockReturnsOptions, new TableInfo.BuilderImpl(TABLE_INFO1)); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getTable(TABLE_INFO1.getTableId(), BigQuery.TableOption.fields())) .andReturn(expectedTable); replay(bigquery); @@ -345,7 +347,7 @@ public void testCreateTable() throws Exception { initializeExpectedDataset(2); Table expectedTable = new Table(serviceMockReturnsOptions, new TableInfo.BuilderImpl(TABLE_INFO1)); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.create(TABLE_INFO1)).andReturn(expectedTable); replay(bigquery); initializeDataset(); @@ -358,7 +360,7 @@ public void testCreateTableWithOptions() throws Exception { initializeExpectedDataset(2); Table expectedTable = new Table(serviceMockReturnsOptions, new TableInfo.BuilderImpl(TABLE_INFO1)); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.create(TABLE_INFO1, BigQuery.TableOption.fields())).andReturn(expectedTable); replay(bigquery); initializeDataset(); @@ -392,7 +394,7 @@ public void testToAndFromPb() { private void compareDataset(Dataset expected, Dataset value) { assertEquals(expected, value); compareDatasetInfo(expected, value); - assertEquals(expected.getBigquery().options(), value.getBigquery().options()); + assertEquals(expected.getBigquery().getOptions(), value.getBigquery().getOptions()); } private void compareDatasetInfo(DatasetInfo expected, DatasetInfo value) { diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllRequestTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllRequestTest.java index a25622399aae..f498e84aa788 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllRequestTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/InsertAllRequestTest.java @@ -323,7 +323,8 @@ public void testOf() { request = InsertAllRequest.of(TABLE_INFO, ROWS.get(0), ROWS.get(1)); assertEquals(TABLE_ID, request.getTable()); assertEquals(ROWS, request.getRows()); - request = InsertAllRequest.of(TABLE_ID.getDataset(), TABLE_ID.getTable(), ROWS.get(0), ROWS.get(1)); + request = + InsertAllRequest.of(TABLE_ID.getDataset(), TABLE_ID.getTable(), ROWS.get(0), ROWS.get(1)); assertEquals(TABLE_ID, request.getTable()); assertEquals(ROWS, request.getRows()); } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobTest.java index 2c15b86fad97..42529b1043e7 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/JobTest.java @@ -78,7 +78,7 @@ public class JobTest { public final ExpectedException thrown = ExpectedException.none(); private void initializeExpectedJob(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); bigquery = createStrictMock(BigQuery.class); expectedJob = new Job(serviceMockReturnsOptions, new JobInfo.BuilderImpl(JOB_INFO)); @@ -154,7 +154,7 @@ public void testToBuilder() { public void testExists_True() throws Exception { initializeExpectedJob(1); BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields()}; - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(expectedJob); replay(bigquery); initializeJob(); @@ -165,7 +165,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { initializeExpectedJob(1); BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields()}; - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(null); replay(bigquery); initializeJob(); @@ -178,7 +178,7 @@ public void testIsDone_True() throws Exception { BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields(BigQuery.JobField.STATUS)}; JobStatus status = createStrictMock(JobStatus.class); expect(status.getState()).andReturn(JobStatus.State.DONE); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)) .andReturn(expectedJob.toBuilder().setStatus(status).build()); replay(status, bigquery); @@ -193,7 +193,7 @@ public void testIsDone_False() throws Exception { BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields(BigQuery.JobField.STATUS)}; JobStatus status = createStrictMock(JobStatus.class); expect(status.getState()).andReturn(JobStatus.State.RUNNING); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)) .andReturn(expectedJob.toBuilder().setStatus(status).build()); replay(status, bigquery); @@ -206,7 +206,7 @@ public void testIsDone_False() throws Exception { public void testIsDone_NotExists() throws Exception { initializeExpectedJob(1); BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields(BigQuery.JobField.STATUS)}; - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(null); replay(bigquery); initializeJob(); @@ -219,8 +219,8 @@ public void testWaitFor() throws InterruptedException, TimeoutException { BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields(BigQuery.JobField.STATUS)}; JobStatus status = createStrictMock(JobStatus.class); expect(status.getState()).andReturn(JobStatus.State.DONE); - expect(bigquery.options()).andReturn(mockOptions); - expect(mockOptions.clock()).andReturn(Clock.defaultClock()); + expect(bigquery.getOptions()).andReturn(mockOptions); + expect(mockOptions.getClock()).andReturn(Clock.defaultClock()); Job completedJob = expectedJob.toBuilder().setStatus(status).build(); expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(completedJob); expect(bigquery.getJob(JOB_INFO.getJobId())).andReturn(completedJob); @@ -234,8 +234,8 @@ public void testWaitFor() throws InterruptedException, TimeoutException { public void testWaitFor_Null() throws InterruptedException, TimeoutException { initializeExpectedJob(1); BigQuery.JobOption[] expectedOptions = {BigQuery.JobOption.fields(BigQuery.JobField.STATUS)}; - expect(bigquery.options()).andReturn(mockOptions); - expect(mockOptions.clock()).andReturn(Clock.defaultClock()); + expect(bigquery.getOptions()).andReturn(mockOptions); + expect(mockOptions.getClock()).andReturn(Clock.defaultClock()); expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(null); expect(bigquery.getJob(JOB_INFO.getJobId())).andReturn(null); replay(bigquery, mockOptions); @@ -254,8 +254,8 @@ public void testWaitForWithCheckingPeriod() throws InterruptedException, Timeout JobStatus status = createStrictMock(JobStatus.class); expect(status.getState()).andReturn(JobStatus.State.RUNNING); expect(status.getState()).andReturn(JobStatus.State.DONE); - expect(bigquery.options()).andReturn(mockOptions); - expect(mockOptions.clock()).andReturn(Clock.defaultClock()); + expect(bigquery.getOptions()).andReturn(mockOptions); + expect(mockOptions.getClock()).andReturn(Clock.defaultClock()); Job runningJob = expectedJob.toBuilder().setStatus(status).build(); Job completedJob = expectedJob.toBuilder().setStatus(status).build(); expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(runningJob); @@ -274,9 +274,10 @@ public void testWaitForWithCheckingPeriod_Null() throws InterruptedException, Ti TimeUnit timeUnit = createStrictMock(TimeUnit.class); timeUnit.sleep(42); EasyMock.expectLastCall(); - expect(bigquery.options()).andReturn(mockOptions); - expect(mockOptions.clock()).andReturn(Clock.defaultClock()); - Job runningJob = expectedJob.toBuilder().setStatus(new JobStatus(JobStatus.State.RUNNING)).build(); + expect(bigquery.getOptions()).andReturn(mockOptions); + expect(mockOptions.getClock()).andReturn(Clock.defaultClock()); + Job runningJob = + expectedJob.toBuilder().setStatus(new JobStatus(JobStatus.State.RUNNING)).build(); expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(runningJob); expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(null); expect(bigquery.getJob(JOB_INFO.getJobId())).andReturn(null); @@ -300,8 +301,8 @@ public void testWaitForWithTimeout() throws InterruptedException, TimeoutExcepti JobStatus status = createStrictMock(JobStatus.class); expect(status.getState()).andReturn(JobStatus.State.RUNNING); expect(status.getState()).andReturn(JobStatus.State.RUNNING); - expect(bigquery.options()).andReturn(mockOptions); - expect(mockOptions.clock()).andReturn(clock); + expect(bigquery.getOptions()).andReturn(mockOptions); + expect(mockOptions.getClock()).andReturn(clock); Job runningJob = expectedJob.toBuilder().setStatus(status).build(); expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(runningJob); expect(bigquery.getJob(JOB_INFO.getJobId(), expectedOptions)).andReturn(runningJob); @@ -318,7 +319,7 @@ public void testReload() throws Exception { initializeExpectedJob(4); JobInfo updatedInfo = JOB_INFO.toBuilder().setEtag("etag").build(); Job expectedJob = new Job(serviceMockReturnsOptions, new JobInfo.BuilderImpl(updatedInfo)); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getJob(JOB_INFO.getJobId())).andReturn(expectedJob); replay(bigquery); initializeJob(); @@ -329,7 +330,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedJob(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getJob(JOB_INFO.getJobId())).andReturn(null); replay(bigquery); initializeJob(); @@ -341,7 +342,7 @@ public void testReloadWithOptions() throws Exception { initializeExpectedJob(4); JobInfo updatedInfo = JOB_INFO.toBuilder().setEtag("etag").build(); Job expectedJob = new Job(serviceMockReturnsOptions, new JobInfo.BuilderImpl(updatedInfo)); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getJob(JOB_INFO.getJobId(), BigQuery.JobOption.fields())) .andReturn(expectedJob); replay(bigquery); @@ -353,7 +354,7 @@ public void testReloadWithOptions() throws Exception { @Test public void testCancel() throws Exception { initializeExpectedJob(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.cancel(JOB_INFO.getJobId())).andReturn(true); replay(bigquery); initializeJob(); @@ -377,7 +378,7 @@ public void testToAndFromPb() { private void compareJob(Job expected, Job value) { assertEquals(expected, value); compareJobInfo(expected, value); - assertEquals(expected.getBigquery().options(), value.getBigquery().options()); + assertEquals(expected.getBigquery().getOptions(), value.getBigquery().getOptions()); } private void compareJobInfo(JobInfo expected, JobInfo value) { diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResponseTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResponseTest.java index b6c3bc61ff7e..d0595e2d44e1 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResponseTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResponseTest.java @@ -41,7 +41,13 @@ public class QueryResponseTest { private static final QueryResult.QueryResultsPageFetcher FETCHER = new QueryResult.QueryResultsPageFetcher() { @Override + @Deprecated public QueryResult nextPage() { + return getNextPage(); + } + + @Override + public QueryResult getNextPage() { return null; } }; diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResultTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResultTest.java index 875560ee3032..9ba62d0fe923 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResultTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/QueryResultTest.java @@ -37,7 +37,13 @@ public class QueryResultTest { private static final QueryResult.QueryResultsPageFetcher FETCHER = new QueryResult.QueryResultsPageFetcher() { @Override + @Deprecated public QueryResult nextPage() { + return getNextPage(); + } + + @Override + public QueryResult getNextPage() { return null; } }; @@ -62,14 +68,14 @@ public void testBuilder() { assertEquals(TOTAL_ROWS, QUERY_RESULT.getTotalRows()); assertEquals(TOTAL_BYTES_PROCESSED, QUERY_RESULT.getTotalBytesProcessed()); assertEquals(CACHE_HIT, QUERY_RESULT.cacheHit()); - assertEquals(CURSOR, QUERY_RESULT.nextPageCursor()); - assertEquals(null, QUERY_RESULT.nextPage()); + assertEquals(CURSOR, QUERY_RESULT.getNextPageCursor()); + assertEquals(null, QUERY_RESULT.getNextPage()); assertEquals(null, QUERY_RESULT_INCOMPLETE.getSchema()); assertEquals(0L, QUERY_RESULT_INCOMPLETE.getTotalRows()); assertEquals(TOTAL_BYTES_PROCESSED, QUERY_RESULT_INCOMPLETE.getTotalBytesProcessed()); assertEquals(false, QUERY_RESULT_INCOMPLETE.cacheHit()); - assertEquals(null, QUERY_RESULT_INCOMPLETE.nextPageCursor()); - assertEquals(null, QUERY_RESULT_INCOMPLETE.nextPage()); + assertEquals(null, QUERY_RESULT_INCOMPLETE.getNextPageCursor()); + assertEquals(null, QUERY_RESULT_INCOMPLETE.getNextPage()); } @Test @@ -96,9 +102,9 @@ public void testEquals() { private void compareQueryResult(QueryResult expected, QueryResult value) { assertEquals(expected, value); - assertEquals(expected.nextPage(), value.nextPage()); - assertEquals(expected.nextPageCursor(), value.nextPageCursor()); - assertEquals(expected.values(), value.values()); + assertEquals(expected.getNextPage(), value.getNextPage()); + assertEquals(expected.getNextPageCursor(), value.getNextPageCursor()); + assertEquals(expected.getValues(), value.getValues()); assertEquals(expected.getSchema(), value.getSchema()); assertEquals(expected.getTotalRows(), value.getTotalRows()); assertEquals(expected.getTotalBytesProcessed(), value.getTotalBytesProcessed()); diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java index 016686d6f8c3..6f91a1427f4e 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/SerializationTest.java @@ -215,7 +215,7 @@ public class SerializationTest extends BaseSerializationTest { .setResult(QUERY_RESULT) .build(); private static final BigQuery BIGQUERY = - BigQueryOptions.builder().projectId("p1").build().service(); + BigQueryOptions.newBuilder().setProjectId("p1").build().getService(); private static final Dataset DATASET = new Dataset(BIGQUERY, new DatasetInfo.BuilderImpl(DATASET_INFO)); private static final Table TABLE = new Table(BIGQUERY, new TableInfo.BuilderImpl(TABLE_INFO)); @@ -227,13 +227,13 @@ public class SerializationTest extends BaseSerializationTest { @Override protected Serializable[] serializableObjects() { - BigQueryOptions options = BigQueryOptions.builder() - .projectId("p1") - .authCredentials(AuthCredentials.createForAppEngine()) + BigQueryOptions options = BigQueryOptions.newBuilder() + .setProjectId("p1") + .setAuthCredentials(AuthCredentials.createForAppEngine()) .build(); BigQueryOptions otherOptions = options.toBuilder() - .projectId("p2") - .authCredentials(null) + .setProjectId("p2") + .setAuthCredentials(null) .build(); return new Serializable[]{DOMAIN_ACCESS, GROUP_ACCESS, USER_ACCESS, VIEW_ACCESS, DATASET_ID, DATASET_INFO, TABLE_ID, CSV_OPTIONS, STREAMING_BUFFER, TABLE_DEFINITION, @@ -252,7 +252,7 @@ protected Serializable[] serializableObjects() { @Override protected Restorable[] restorableObjects() { - BigQueryOptions options = BigQueryOptions.builder().projectId("p2").build(); + BigQueryOptions options = BigQueryOptions.newBuilder().setProjectId("p2").build(); // avoid closing when you don't want partial writes upon failure @SuppressWarnings("resource") TableDataWriteChannel writer = diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/StandardTableDefinitionTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/StandardTableDefinitionTest.java index 48e4d2e2ed0e..2f915a71864a 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/StandardTableDefinitionTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/StandardTableDefinitionTest.java @@ -70,7 +70,8 @@ public class StandardTableDefinitionTest { @Test public void testToBuilder() { compareStandardTableDefinition(TABLE_DEFINITION, TABLE_DEFINITION.toBuilder().build()); - StandardTableDefinition tableDefinition = TABLE_DEFINITION.toBuilder().setLocation("EU").build(); + StandardTableDefinition tableDefinition = + TABLE_DEFINITION.toBuilder().setLocation("EU").build(); assertEquals("EU", tableDefinition.getLocation()); tableDefinition = tableDefinition.toBuilder() .setLocation(LOCATION) diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableDataWriteChannelTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableDataWriteChannelTest.java index 95c1c90a3b2e..f5bf37a5bb94 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableDataWriteChannelTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableDataWriteChannelTest.java @@ -54,12 +54,12 @@ public class TableDataWriteChannelTest { private static final String UPLOAD_ID = "uploadid"; private static final TableId TABLE_ID = TableId.of("dataset", "table"); private static final WriteChannelConfiguration LOAD_CONFIGURATION = - WriteChannelConfiguration.builder(TABLE_ID) - .createDisposition(JobInfo.CreateDisposition.CREATE_IF_NEEDED) - .writeDisposition(JobInfo.WriteDisposition.WRITE_APPEND) - .formatOptions(FormatOptions.json()) - .ignoreUnknownValues(true) - .maxBadRecords(10) + WriteChannelConfiguration.newBuilder(TABLE_ID) + .setCreateDisposition(JobInfo.CreateDisposition.CREATE_IF_NEEDED) + .setWriteDisposition(JobInfo.WriteDisposition.WRITE_APPEND) + .setFormatOptions(FormatOptions.json()) + .setIgnoreUnknownValues(true) + .setMaxBadRecords(10) .build(); private static final int MIN_CHUNK_SIZE = 256 * 1024; private static final int DEFAULT_CHUNK_SIZE = 8 * MIN_CHUNK_SIZE; @@ -80,9 +80,9 @@ public void setUp() { bigqueryRpcMock = createMock(BigQueryRpc.class); expect(rpcFactoryMock.create(anyObject(BigQueryOptions.class))).andReturn(bigqueryRpcMock); replay(rpcFactoryMock); - options = BigQueryOptions.builder() - .projectId("projectid") - .serviceRpcFactory(rpcFactoryMock) + options = BigQueryOptions.newBuilder() + .setProjectId("projectid") + .setServiceRpcFactory(rpcFactoryMock) .build(); } @@ -133,7 +133,7 @@ public void testWriteWithFlush() throws IOException { eq(CUSTOM_CHUNK_SIZE), eq(false)); replay(bigqueryRpcMock); writer = new TableDataWriteChannel(options, LOAD_CONFIGURATION); - writer.chunkSize(CUSTOM_CHUNK_SIZE); + writer.setChunkSize(CUSTOM_CHUNK_SIZE); ByteBuffer buffer = randomBuffer(CUSTOM_CHUNK_SIZE); assertEquals(CUSTOM_CHUNK_SIZE, writer.write(buffer)); assertArrayEquals(buffer.array(), capturedBuffer.getValue()); @@ -239,10 +239,10 @@ public void testSaveAndRestoreClosed() throws IOException { RestorableState writerState = writer.capture(); RestorableState expectedWriterState = TableDataWriteChannel.StateImpl.builder(options, LOAD_CONFIGURATION, UPLOAD_ID) - .buffer(null) - .chunkSize(DEFAULT_CHUNK_SIZE) - .isOpen(false) - .position(0) + .setBuffer(null) + .setChunkSize(DEFAULT_CHUNK_SIZE) + .setIsOpen(false) + .setPosition(0) .build(); WriteChannel restoredWriter = writerState.restore(); assertArrayEquals(new byte[0], capturedBuffer.getValue()); diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableTest.java index 1a48d161a5c4..dae32a89c830 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/TableTest.java @@ -90,7 +90,7 @@ public class TableTest { private Table table; private void initializeExpectedTable(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); bigquery = createStrictMock(BigQuery.class); expectedTable = new Table(serviceMockReturnsOptions, new TableInfo.BuilderImpl(TABLE_INFO)); @@ -170,7 +170,7 @@ public void testToBuilder() { public void testExists_True() throws Exception { initializeExpectedTable(1); BigQuery.TableOption[] expectedOptions = {BigQuery.TableOption.fields()}; - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getTable(TABLE_INFO.getTableId(), expectedOptions)).andReturn(expectedTable); replay(bigquery); initializeTable(); @@ -181,7 +181,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { initializeExpectedTable(1); BigQuery.TableOption[] expectedOptions = {BigQuery.TableOption.fields()}; - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getTable(TABLE_INFO.getTableId(), expectedOptions)).andReturn(null); replay(bigquery); initializeTable(); @@ -194,7 +194,7 @@ public void testReload() throws Exception { TableInfo updatedInfo = TABLE_INFO.toBuilder().setDescription("Description").build(); Table expectedTable = new Table(serviceMockReturnsOptions, new TableInfo.BuilderImpl(updatedInfo)); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getTable(TABLE_INFO.getTableId())).andReturn(expectedTable); replay(bigquery); initializeTable(); @@ -205,7 +205,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedTable(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getTable(TABLE_INFO.getTableId())).andReturn(null); replay(bigquery); initializeTable(); @@ -218,7 +218,7 @@ public void testReloadWithOptions() throws Exception { TableInfo updatedInfo = TABLE_INFO.toBuilder().setDescription("Description").build(); Table expectedTable = new Table(serviceMockReturnsOptions, new TableInfo.BuilderImpl(updatedInfo)); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.getTable(TABLE_INFO.getTableId(), BigQuery.TableOption.fields())) .andReturn(expectedTable); replay(bigquery); @@ -231,7 +231,7 @@ public void testReloadWithOptions() throws Exception { public void testUpdate() { initializeExpectedTable(4); Table expectedUpdatedTable = expectedTable.toBuilder().setDescription("Description").build(); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.update(eq(expectedTable))).andReturn(expectedUpdatedTable); replay(bigquery); initializeTable(); @@ -243,7 +243,7 @@ public void testUpdate() { public void testUpdateWithOptions() { initializeExpectedTable(4); Table expectedUpdatedTable = expectedTable.toBuilder().setDescription("Description").build(); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.update(eq(expectedTable), eq(BigQuery.TableOption.fields()))) .andReturn(expectedUpdatedTable); replay(bigquery); @@ -255,7 +255,7 @@ public void testUpdateWithOptions() { @Test public void testDeleteTrue() { initializeExpectedTable(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.delete(TABLE_INFO.getTableId())).andReturn(true); replay(bigquery); initializeTable(); @@ -265,7 +265,7 @@ public void testDeleteTrue() { @Test public void testDeleteFalse() { initializeExpectedTable(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.delete(TABLE_INFO.getTableId())).andReturn(false); replay(bigquery); initializeTable(); @@ -275,7 +275,7 @@ public void testDeleteFalse() { @Test public void testInsert() throws Exception { initializeExpectedTable(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.insertAll(INSERT_ALL_REQUEST)).andReturn(EMPTY_INSERT_ALL_RESPONSE); replay(bigquery); initializeTable(); @@ -286,7 +286,7 @@ public void testInsert() throws Exception { @Test public void testInsertComplete() throws Exception { initializeExpectedTable(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); expect(bigquery.insertAll(INSERT_ALL_REQUEST_COMPLETE)).andReturn(EMPTY_INSERT_ALL_RESPONSE); replay(bigquery); initializeTable(); @@ -297,36 +297,36 @@ public void testInsertComplete() throws Exception { @Test public void testList() throws Exception { initializeExpectedTable(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); PageImpl> tableDataPage = new PageImpl<>(null, "c", ROWS); expect(bigquery.listTableData(TABLE_ID1)).andReturn(tableDataPage); replay(bigquery); initializeTable(); Page> dataPage = table.list(); - Iterator> tableDataIterator = tableDataPage.values().iterator(); - Iterator> dataIterator = dataPage.values().iterator(); + Iterator> tableDataIterator = dataPage.getValues().iterator(); + Iterator> dataIterator = dataPage.getValues().iterator(); assertTrue(Iterators.elementsEqual(tableDataIterator, dataIterator)); } @Test public void testListWithOptions() throws Exception { initializeExpectedTable(1); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); PageImpl> tableDataPage = new PageImpl<>(null, "c", ROWS); expect(bigquery.listTableData(TABLE_ID1, BigQuery.TableDataListOption.pageSize(10L))) .andReturn(tableDataPage); replay(bigquery); initializeTable(); Page> dataPage = table.list(BigQuery.TableDataListOption.pageSize(10L)); - Iterator> tableDataIterator = tableDataPage.values().iterator(); - Iterator> dataIterator = dataPage.values().iterator(); + Iterator> tableDataIterator = dataPage.getValues().iterator(); + Iterator> dataIterator = dataPage.getValues().iterator(); assertTrue(Iterators.elementsEqual(tableDataIterator, dataIterator)); } @Test public void testCopyFromString() throws Exception { initializeExpectedTable(2); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); Job expectedJob = new Job(serviceMockReturnsOptions, new JobInfo.BuilderImpl(COPY_JOB_INFO)); expect(bigquery.create(COPY_JOB_INFO)) .andReturn(expectedJob); @@ -339,7 +339,7 @@ public void testCopyFromString() throws Exception { @Test public void testCopyFromId() throws Exception { initializeExpectedTable(2); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); Job expectedJob = new Job(serviceMockReturnsOptions, new JobInfo.BuilderImpl(COPY_JOB_INFO)); expect(bigquery.create(COPY_JOB_INFO)).andReturn(expectedJob); replay(bigquery); @@ -351,7 +351,7 @@ public void testCopyFromId() throws Exception { @Test public void testLoadDataUri() throws Exception { initializeExpectedTable(2); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); Job expectedJob = new Job(serviceMockReturnsOptions, new JobInfo.BuilderImpl(LOAD_JOB_INFO)); expect(bigquery.create(LOAD_JOB_INFO)).andReturn(expectedJob); replay(bigquery); @@ -363,7 +363,7 @@ public void testLoadDataUri() throws Exception { @Test public void testLoadDataUris() throws Exception { initializeExpectedTable(2); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); Job expectedJob = new Job(serviceMockReturnsOptions, new JobInfo.BuilderImpl(LOAD_JOB_INFO)); expect(bigquery.create(LOAD_JOB_INFO)).andReturn(expectedJob); replay(bigquery); @@ -375,7 +375,7 @@ public void testLoadDataUris() throws Exception { @Test public void testExtractDataUri() throws Exception { initializeExpectedTable(2); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); Job expectedJob = new Job(serviceMockReturnsOptions, new JobInfo.BuilderImpl(EXTRACT_JOB_INFO)); expect(bigquery.create(EXTRACT_JOB_INFO)).andReturn(expectedJob); replay(bigquery); @@ -387,7 +387,7 @@ public void testExtractDataUri() throws Exception { @Test public void testExtractDataUris() throws Exception { initializeExpectedTable(2); - expect(bigquery.options()).andReturn(mockOptions); + expect(bigquery.getOptions()).andReturn(mockOptions); Job expectedJob = new Job(serviceMockReturnsOptions, new JobInfo.BuilderImpl(EXTRACT_JOB_INFO)); expect(bigquery.create(EXTRACT_JOB_INFO)).andReturn(expectedJob); replay(bigquery); @@ -413,7 +413,7 @@ public void testToAndFromPb() { private void compareTable(Table expected, Table value) { assertEquals(expected, value); compareTableInfo(expected, value); - assertEquals(expected.getBigquery().options(), value.getBigquery().options()); + assertEquals(expected.getBigquery().getOptions(), value.getBigquery().getOptions()); } private void compareTableInfo(TableInfo expected, TableInfo value) { diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/UserDefinedFunctionTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/UserDefinedFunctionTest.java index 2621a5e13798..214d6725ef90 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/UserDefinedFunctionTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/UserDefinedFunctionTest.java @@ -58,7 +58,7 @@ public void testToAndFromPb() { private void compareUserDefinedFunction(UserDefinedFunction expected, UserDefinedFunction value) { assertEquals(expected, value); - assertEquals(expected.type(), value.type()); - assertEquals(expected.content(), value.content()); + assertEquals(expected.getType(), value.getType()); + assertEquals(expected.getContent(), value.getContent()); } } diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java index 61b3ae83753a..9722b44a0ddd 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/it/ITBigQueryTest.java @@ -193,8 +193,8 @@ public class ITBigQueryTest { public static void beforeClass() throws InterruptedException, TimeoutException { RemoteBigQueryHelper bigqueryHelper = RemoteBigQueryHelper.create(); RemoteStorageHelper storageHelper = RemoteStorageHelper.create(); - bigquery = bigqueryHelper.getOptions().service(); - storage = storageHelper.getOptions().service(); + bigquery = bigqueryHelper.getOptions().getService(); + storage = storageHelper.getOptions().getService(); storage.create(BucketInfo.of(BUCKET)); storage.create(BlobInfo.newBuilder(BUCKET, LOAD_FILE).setContentType("text/plain").build(), CSV_CONTENT.getBytes(StandardCharsets.UTF_8)); @@ -243,7 +243,7 @@ public void testListDatasets() { @Test public void testGetDataset() { Dataset dataset = bigquery.getDataset(DATASET); - assertEquals(bigquery.options().projectId(), dataset.getDatasetId().getProject()); + assertEquals(bigquery.getOptions().getProjectId(), dataset.getDatasetId().getProject()); assertEquals(DATASET, dataset.getDatasetId().getDataset()); assertEquals(DESCRIPTION, dataset.getDescription()); assertNotNull(dataset.getAcl()); @@ -257,7 +257,7 @@ public void testGetDataset() { public void testGetDatasetWithSelectedFields() { Dataset dataset = bigquery.getDataset(DATASET, DatasetOption.fields(DatasetField.CREATION_TIME)); - assertEquals(bigquery.options().projectId(), dataset.getDatasetId().getProject()); + assertEquals(bigquery.getOptions().getProjectId(), dataset.getDatasetId().getProject()); assertEquals(DATASET, dataset.getDatasetId().getDataset()); assertNotNull(dataset.getCreationTime()); assertNull(dataset.getDescription()); @@ -277,7 +277,7 @@ public void testUpdateDataset() { .setDescription("Some Description") .build()); assertNotNull(dataset); - assertEquals(bigquery.options().projectId(), dataset.getDatasetId().getProject()); + assertEquals(bigquery.getOptions().getProjectId(), dataset.getDatasetId().getProject()); assertEquals(OTHER_DATASET, dataset.getDatasetId().getDataset()); assertEquals("Some Description", dataset.getDescription()); Dataset updatedDataset = @@ -292,7 +292,7 @@ public void testUpdateDatasetWithSelectedFields() { .setDescription("Some Description") .build()); assertNotNull(dataset); - assertEquals(bigquery.options().projectId(), dataset.getDatasetId().getProject()); + assertEquals(bigquery.getOptions().getProjectId(), dataset.getDatasetId().getProject()); assertEquals(OTHER_DATASET, dataset.getDatasetId().getDataset()); assertEquals("Some Description", dataset.getDescription()); Dataset updatedDataset = @@ -398,7 +398,7 @@ public void testCreateExternalTable() throws InterruptedException { } long integerValue = 0; int rowCount = 0; - for (List row : response.getResult().values()) { + for (List row : response.getResult().getValues()) { FieldValue timestampCell = row.get(0); FieldValue stringCell = row.get(1); FieldValue integerCell = row.get(2); @@ -460,7 +460,7 @@ public void testCreateViewTable() throws InterruptedException { Thread.sleep(1000); } int rowCount = 0; - for (List row : response.getResult().values()) { + for (List row : response.getResult().getValues()) { FieldValue timestampCell = row.get(0); FieldValue stringCell = row.get(1); FieldValue booleanCell = row.get(2); @@ -485,7 +485,7 @@ public void testListTables() { assertNotNull(createdTable); Page
    tables = bigquery.listTables(DATASET); boolean found = false; - Iterator
    tableIterator = tables.values().iterator(); + Iterator
    tableIterator = tables.getValues().iterator(); while (tableIterator.hasNext() && !found) { if (tableIterator.next().getTableId().equals(createdTable.getTableId())) { found = true; @@ -688,7 +688,7 @@ public void testInsertAllWithErrors() { public void testListAllTableData() { Page> rows = bigquery.listTableData(TABLE_ID); int rowCount = 0; - for (List row : rows.values()) { + for (List row : rows.getValues()) { FieldValue timestampCell = row.get(0); FieldValue stringCell = row.get(1); FieldValue integerCell = row.get(2); @@ -735,7 +735,7 @@ public void testQuery() throws InterruptedException { } assertEquals(QUERY_RESULT_SCHEMA, response.getResult().getSchema()); int rowCount = 0; - for (List row : response.getResult().values()) { + for (List row : response.getResult().getValues()) { FieldValue timestampCell = row.get(0); FieldValue stringCell = row.get(1); FieldValue booleanCell = row.get(2); @@ -756,7 +756,7 @@ public void testQuery() throws InterruptedException { @Test public void testListJobs() { Page jobs = bigquery.listJobs(); - for (Job job : jobs.values()) { + for (Job job : jobs.getValues()) { assertNotNull(job.getJobId()); assertNotNull(job.getStatistics()); assertNotNull(job.getStatus()); @@ -768,7 +768,7 @@ public void testListJobs() { @Test public void testListJobsWithSelectedFields() { Page jobs = bigquery.listJobs(JobListOption.fields(JobField.USER_EMAIL)); - for (Job job : jobs.values()) { + for (Job job : jobs.getValues()) { assertNotNull(job.getJobId()); assertNotNull(job.getStatus()); assertNotNull(job.getUserEmail()); @@ -903,7 +903,7 @@ public void testQueryJob() throws InterruptedException, TimeoutException { assertFalse(response.hasErrors()); assertEquals(QUERY_RESULT_SCHEMA, response.getResult().getSchema()); int rowCount = 0; - for (List row : response.getResult().values()) { + for (List row : response.getResult().getValues()) { FieldValue timestampCell = row.get(0); FieldValue stringCell = row.get(1); FieldValue booleanCell = row.get(2); @@ -986,7 +986,7 @@ public void testInsertFromFile() throws InterruptedException { } Page> rows = bigquery.listTableData(tableId); int rowCount = 0; - for (List row : rows.values()) { + for (List row : rows.getValues()) { FieldValue timestampCell = row.get(0); FieldValue stringCell = row.get(1); FieldValue integerCell = row.get(2); diff --git a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelperTest.java b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelperTest.java index 1912c3d9283e..2595406b747c 100644 --- a/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelperTest.java +++ b/google-cloud-bigquery/src/test/java/com/google/cloud/bigquery/testing/RemoteBigQueryHelperTest.java @@ -81,14 +81,13 @@ public void testForceDelete() throws InterruptedException, ExecutionException { public void testCreateFromStream() { RemoteBigQueryHelper helper = RemoteBigQueryHelper.create(PROJECT_ID, JSON_KEY_STREAM); BigQueryOptions options = helper.getOptions(); - assertEquals(options, helper.getOptions()); - assertEquals(PROJECT_ID, options.projectId()); - assertEquals(60000, options.connectTimeout()); - assertEquals(60000, options.readTimeout()); - assertEquals(10, options.retryParams().retryMaxAttempts()); - assertEquals(6, options.retryParams().retryMinAttempts()); - assertEquals(30000, options.retryParams().maxRetryDelayMillis()); - assertEquals(120000, options.retryParams().totalRetryPeriodMillis()); - assertEquals(250, options.retryParams().initialRetryDelayMillis()); + assertEquals(PROJECT_ID, options.getProjectId()); + assertEquals(60000, options.getConnectTimeout()); + assertEquals(60000, options.getReadTimeout()); + assertEquals(10, options.getRetryParams().getRetryMaxAttempts()); + assertEquals(6, options.getRetryParams().getRetryMinAttempts()); + assertEquals(30000, options.getRetryParams().getMaxRetryDelayMillis()); + assertEquals(120000, options.getRetryParams().getTotalRetryPeriodMillis()); + assertEquals(250, options.getRetryParams().getInitialRetryDelayMillis()); } } diff --git a/google-cloud-compute/README.md b/google-cloud-compute/README.md index 395f22936b0c..72bff7504ba1 100644 --- a/google-cloud-compute/README.md +++ b/google-cloud-compute/README.md @@ -88,7 +88,7 @@ code to create your service object: import com.google.cloud.compute.Compute; import com.google.cloud.compute.ComputeOptions; -Compute compute = ComputeOptions.defaultInstance().service(); +Compute compute = ComputeOptions.getDefaultInstance().getService(); ``` For other authentication options, see the [Authentication](https://github.com/GoogleCloudPlatform/google-cloud-java#authentication) @@ -116,7 +116,7 @@ RegionAddressId addressId = RegionAddressId.of("us-central1", "test-address"); Operation operation = compute.create(AddressInfo.of(addressId)); // Wait for operation to complete operation = operation.waitFor(); -if (operation.errors() == null) { +if (operation.getErrors() == null) { System.out.println("Address " + addressId + " was successfully created"); } else { // inspect operation.getErrors() @@ -153,7 +153,7 @@ operation = operation.waitFor(); if (operation.getErrors() == null) { System.out.println("Disk " + diskId + " was successfully created"); } else { - // inspect operation.errors() + // inspect operation.getErrors() throw new RuntimeException("Disk creation failed"); } ``` @@ -199,7 +199,7 @@ operation = operation.waitFor(); if (operation.getErrors() == null) { System.out.println("Instance " + instanceId + " was successfully created"); } else { - // inspect operation.errors() + // inspect operation.getErrors() throw new RuntimeException("Instance creation failed"); } ``` diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Address.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Address.java index 1c40e44dcd26..30042267312d 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Address.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Address.java @@ -133,7 +133,7 @@ public Address build() { Address(Compute compute, AddressInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.compute = checkNotNull(compute); - this.options = compute.options(); + this.options = compute.getOptions(); } /** @@ -208,7 +208,7 @@ public final int hashCode() { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); - this.compute = options.service(); + this.compute = options.getService(); } static Address fromPb(Compute compute, com.google.api.services.compute.model.Address addressPb) { diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Compute.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Compute.java index 47d594ba6ec5..97ba2e539208 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Compute.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Compute.java @@ -65,7 +65,13 @@ enum DiskTypeField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -100,7 +106,13 @@ enum MachineTypeField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -131,7 +143,13 @@ enum RegionField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -161,7 +179,13 @@ enum ZoneField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -186,7 +210,13 @@ enum LicenseField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -235,7 +265,13 @@ enum OperationField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -268,7 +304,13 @@ enum AddressField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -309,7 +351,13 @@ enum DiskField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -343,7 +391,13 @@ enum SnapshotField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -379,7 +433,13 @@ enum ImageField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -410,7 +470,13 @@ enum SubnetworkField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -442,7 +508,13 @@ enum NetworkField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -481,7 +553,13 @@ enum InstanceField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -547,7 +625,7 @@ class DiskTypeFilter extends ListFilter { private static final long serialVersionUID = 4847837203592234453L; private DiskTypeFilter(DiskTypeField field, ComparisonOperator operator, Object value) { - super(field.selector(), operator, value); + super(field.getSelector(), operator, value); } /** @@ -595,7 +673,7 @@ class MachineTypeFilter extends ListFilter { private static final long serialVersionUID = 7346062041571853235L; private MachineTypeFilter(MachineTypeField field, ComparisonOperator operator, Object value) { - super(field.selector(), operator, value); + super(field.getSelector(), operator, value); } /** @@ -643,7 +721,7 @@ class RegionFilter extends ListFilter { private static final long serialVersionUID = 4464892812442567172L; private RegionFilter(RegionField field, ComparisonOperator operator, Object value) { - super(field.selector(), operator, value); + super(field.getSelector(), operator, value); } /** @@ -677,7 +755,7 @@ class ZoneFilter extends ListFilter { private static final long serialVersionUID = -3927428278548808737L; private ZoneFilter(ZoneField field, ComparisonOperator operator, Object value) { - super(field.selector(), operator, value); + super(field.getSelector(), operator, value); } /** @@ -711,7 +789,7 @@ class OperationFilter extends ListFilter { private static final long serialVersionUID = -3202249202748346427L; private OperationFilter(OperationField field, ComparisonOperator operator, Object value) { - super(field.selector(), operator, value); + super(field.getSelector(), operator, value); } /** @@ -759,7 +837,7 @@ class AddressFilter extends ListFilter { private static final long serialVersionUID = -227481644259653765L; private AddressFilter(AddressField field, ComparisonOperator operator, Object value) { - super(field.selector(), operator, value); + super(field.getSelector(), operator, value); } /** @@ -793,7 +871,7 @@ class SnapshotFilter extends ListFilter { private static final long serialVersionUID = 8757711630092406747L; private SnapshotFilter(SnapshotField field, ComparisonOperator operator, Object value) { - super(field.selector(), operator, value); + super(field.getSelector(), operator, value); } /** @@ -841,7 +919,7 @@ class ImageFilter extends ListFilter { private static final long serialVersionUID = -3601427417234098397L; private ImageFilter(ImageField field, ComparisonOperator operator, Object value) { - super(field.selector(), operator, value); + super(field.getSelector(), operator, value); } /** @@ -889,7 +967,7 @@ class DiskFilter extends ListFilter { private static final long serialVersionUID = 5856790665396877913L; private DiskFilter(DiskField field, ComparisonOperator operator, Object value) { - super(field.selector(), operator, value); + super(field.getSelector(), operator, value); } /** @@ -937,7 +1015,7 @@ class SubnetworkFilter extends ListFilter { private static final long serialVersionUID = 979448583739105481L; private SubnetworkFilter(SubnetworkField field, ComparisonOperator operator, Object value) { - super(field.selector(), operator, value); + super(field.getSelector(), operator, value); } /** @@ -971,7 +1049,7 @@ class NetworkFilter extends ListFilter { private static final long serialVersionUID = 7921406498804130930L; private NetworkFilter(NetworkField field, ComparisonOperator operator, Object value) { - super(field.selector(), operator, value); + super(field.getSelector(), operator, value); } /** @@ -1019,7 +1097,7 @@ class InstanceFilter extends ListFilter { private static final long serialVersionUID = 679008888882025686L; private InstanceFilter(InstanceField field, ComparisonOperator operator, Object value) { - super(field.selector(), operator, value); + super(field.getSelector(), operator, value); } /** diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeException.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeException.java index 1a69457040d6..2f46cdb85163 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeException.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeException.java @@ -45,7 +45,7 @@ public ComputeException(IOException exception) { } @Override - protected Set retryableErrors() { + protected Set getRetryableErrors() { return RETRYABLE_ERRORS; } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeImpl.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeImpl.java index 637b47cc6ff6..5b66cefb182a 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeImpl.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeImpl.java @@ -51,7 +51,13 @@ private static class GlobalOperationPageFetcher implements NextPageFetcher nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listGlobalOperations(serviceOptions, requestOptions); } } @@ -72,7 +78,13 @@ private static class DiskTypePageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listDiskTypes(zone, serviceOptions, requestOptions); } } @@ -91,7 +103,13 @@ private static class AggregatedDiskTypePageFetcher implements NextPageFetcher nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listDiskTypes(serviceOptions, requestOptions); } } @@ -112,7 +130,13 @@ private static class MachineTypePageFetcher implements NextPageFetcher nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listMachineTypes(zone, serviceOptions, requestOptions); } } @@ -131,7 +155,13 @@ private static class AggregatedMachineTypePageFetcher implements NextPageFetcher } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listMachineTypes(serviceOptions, requestOptions); } } @@ -150,7 +180,13 @@ private static class RegionPageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listRegions(serviceOptions, requestOptions); } } @@ -169,7 +205,13 @@ private static class ZonePageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listZones(serviceOptions, requestOptions); } } @@ -190,7 +232,13 @@ private static class RegionOperationPageFetcher implements NextPageFetcher nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listRegionOperations(region, serviceOptions, requestOptions); } } @@ -211,7 +259,13 @@ private static class ZoneOperationPageFetcher implements NextPageFetcher nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listZoneOperations(zone, serviceOptions, requestOptions); } } @@ -230,7 +284,13 @@ private static class GlobalAddressPageFetcher implements NextPageFetcher
    nextPage() { + return getNextPage(); + } + + @Override + public Page
    getNextPage() { return listGlobalAddresses(serviceOptions, requestOptions); } } @@ -251,7 +311,13 @@ private static class RegionAddressPageFetcher implements NextPageFetcher
    nextPage() { + return getNextPage(); + } + + @Override + public Page
    getNextPage() { return listRegionAddresses(region, serviceOptions, requestOptions); } } @@ -270,7 +336,13 @@ private static class AggregatedAddressPageFetcher implements NextPageFetcher nextPage() { + return getNextPage(); + } + + @Override + public Page
    getNextPage() { return listAddresses(serviceOptions, requestOptions); } } @@ -289,7 +361,13 @@ private static class SnapshotPageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listSnapshots(serviceOptions, requestOptions); } } @@ -310,7 +388,13 @@ private static class ImagePageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listImages(project, serviceOptions, requestOptions); } } @@ -331,7 +415,13 @@ private static class DiskPageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listDisks(zone, serviceOptions, requestOptions); } } @@ -350,7 +440,13 @@ private static class AggregatedDiskPageFetcher implements NextPageFetcher } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listDisks(serviceOptions, requestOptions); } } @@ -371,7 +467,13 @@ private static class SubnetworkPageFetcher implements NextPageFetcher nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listSubnetworks(region, serviceOptions, requestOptions); } } @@ -390,7 +492,13 @@ private static class AggregatedSubnetworkPageFetcher implements NextPageFetcher< } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listSubnetworks(serviceOptions, requestOptions); } } @@ -409,7 +517,13 @@ private static class NetworkPageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listNetworks(serviceOptions, requestOptions); } } @@ -430,7 +544,13 @@ private static class InstancePageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listInstances(zone, serviceOptions, requestOptions); } } @@ -449,7 +569,13 @@ private static class AggregatedInstancePageFetcher implements NextPageFetcher nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listInstances(serviceOptions, requestOptions); } } @@ -458,7 +584,7 @@ public Page nextPage() { ComputeImpl(ComputeOptions options) { super(options); - computeRpc = options.rpc(); + computeRpc = options.getRpc(); } @Override @@ -471,7 +597,7 @@ public DiskType getDiskType(final DiskTypeId diskTypeId, DiskTypeOption... optio public com.google.api.services.compute.model.DiskType call() { return computeRpc.getDiskType(diskTypeId.getZone(), diskTypeId.getType(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : DiskType.fromPb(answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -485,7 +611,7 @@ public DiskType getDiskType(String zone, String diskType, DiskTypeOption... opti @Override public Page listDiskTypes(String zone, DiskTypeListOption... options) { - return listDiskTypes(zone, options(), optionMap(options)); + return listDiskTypes(zone, getOptions(), optionMap(options)); } private static Page listDiskTypes(final String zone, @@ -497,9 +623,9 @@ private static Page listDiskTypes(final String zone, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listDiskTypes(zone, optionsMap); + return serviceOptions.getRpc().listDiskTypes(zone, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable diskTypes = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -519,7 +645,7 @@ public DiskType apply(com.google.api.services.compute.model.DiskType diskType) { @Override public Page listDiskTypes(DiskTypeAggregatedListOption... options) { - return listDiskTypes(options(), optionMap(options)); + return listDiskTypes(getOptions(), optionMap(options)); } private static Page listDiskTypes(final ComputeOptions serviceOptions, @@ -531,9 +657,9 @@ private static Page listDiskTypes(final ComputeOptions serviceOptions, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listDiskTypes(optionsMap); + return serviceOptions.getRpc().listDiskTypes(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable diskTypes = Iterables.transform(result.y(), new Function() { @@ -560,7 +686,7 @@ public com.google.api.services.compute.model.MachineType call() { return computeRpc.getMachineType(machineType.getZone(), machineType.getType(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : MachineType.fromPb(answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -574,7 +700,7 @@ public MachineType getMachineType(String zone, String machineType, MachineTypeOp @Override public Page listMachineTypes(String zone, MachineTypeListOption... options) { - return listMachineTypes(zone, options(), optionMap(options)); + return listMachineTypes(zone, getOptions(), optionMap(options)); } private static Page listMachineTypes(final String zone, @@ -586,9 +712,9 @@ private static Page listMachineTypes(final String zone, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listMachineTypes(zone, optionsMap); + return serviceOptions.getRpc().listMachineTypes(zone, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable machineTypes = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -609,7 +735,7 @@ public MachineType apply( @Override public Page listMachineTypes(MachineTypeAggregatedListOption... options) { - return listMachineTypes(options(), optionMap(options)); + return listMachineTypes(getOptions(), optionMap(options)); } private static Page listMachineTypes(final ComputeOptions serviceOptions, @@ -621,9 +747,9 @@ private static Page listMachineTypes(final ComputeOptions serviceOp @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listMachineTypes(optionsMap); + return serviceOptions.getRpc().listMachineTypes(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable machineTypes = Iterables.transform(result.y(), new Function() { @@ -651,7 +777,7 @@ public Region getRegion(final String region, RegionOption... options) { public com.google.api.services.compute.model.Region call() { return computeRpc.getRegion(region, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Region.fromPb(answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -660,7 +786,7 @@ public com.google.api.services.compute.model.Region call() { @Override public Page listRegions(RegionListOption... options) { - return listRegions(options(), optionMap(options)); + return listRegions(getOptions(), optionMap(options)); } private static Page listRegions(final ComputeOptions serviceOptions, @@ -672,9 +798,9 @@ private static Page listRegions(final ComputeOptions serviceOptions, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listRegions(optionsMap); + return serviceOptions.getRpc().listRegions(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable regions = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -702,7 +828,7 @@ public Zone getZone(final String zone, ZoneOption... options) { public com.google.api.services.compute.model.Zone call() { return computeRpc.getZone(zone, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Zone.fromPb(answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -711,7 +837,7 @@ public com.google.api.services.compute.model.Zone call() { @Override public Page listZones(ZoneListOption... options) { - return listZones(options(), optionMap(options)); + return listZones(getOptions(), optionMap(options)); } private static Page listZones(final ComputeOptions serviceOptions, @@ -723,9 +849,9 @@ private static Page listZones(final ComputeOptions serviceOptions, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listZones(optionsMap); + return serviceOptions.getRpc().listZones(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable zones = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -749,7 +875,7 @@ public License getLicense(String license, LicenseOption... options) { @Override public License getLicense(LicenseId license, LicenseOption... options) { - final LicenseId completeId = license.setProjectId(options().projectId()); + final LicenseId completeId = license.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { com.google.api.services.compute.model.License answer = @@ -759,7 +885,7 @@ public com.google.api.services.compute.model.License call() { return computeRpc.getLicense(completeId.getProject(), completeId.getLicense(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : License.fromPb(answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -789,7 +915,7 @@ public com.google.api.services.compute.model.Operation call() { throw new IllegalArgumentException("Unexpected operation identity type"); } } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -801,14 +927,14 @@ public com.google.api.services.compute.model.Operation call() { return new Function() { @Override public Operation apply(com.google.api.services.compute.model.Operation operation) { - return Operation.fromPb(serviceOptions.service(), operation); + return Operation.fromPb(serviceOptions.getService(), operation); } }; } @Override public Page listGlobalOperations(OperationListOption... options) { - return listGlobalOperations(options(), optionMap(options)); + return listGlobalOperations(getOptions(), optionMap(options)); } private static Page listGlobalOperations(final ComputeOptions serviceOptions, @@ -820,9 +946,9 @@ private static Page listGlobalOperations(final ComputeOptions service @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listGlobalOperations(optionsMap); + return serviceOptions.getRpc().listGlobalOperations(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable operations = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -836,7 +962,7 @@ Iterable> call() { @Override public Page listRegionOperations(String region, OperationListOption... options) { - return listRegionOperations(region, options(), optionMap(options)); + return listRegionOperations(region, getOptions(), optionMap(options)); } private static Page listRegionOperations(final String region, @@ -848,9 +974,9 @@ private static Page listRegionOperations(final String region, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listRegionOperations(region, optionsMap); + return serviceOptions.getRpc().listRegionOperations(region, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable operations = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -864,7 +990,7 @@ Iterable> call() { @Override public Page listZoneOperations(String zone, OperationListOption... options) { - return listZoneOperations(zone, options(), optionMap(options)); + return listZoneOperations(zone, getOptions(), optionMap(options)); } private static Page listZoneOperations(final String zone, @@ -876,9 +1002,9 @@ private static Page listZoneOperations(final String zone, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listZoneOperations(zone, optionsMap); + return serviceOptions.getRpc().listZoneOperations(zone, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable operations = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -911,7 +1037,7 @@ public Boolean call() { throw new IllegalArgumentException("Unexpected operation identity type"); } } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); } @@ -936,7 +1062,7 @@ public com.google.api.services.compute.model.Address call() { throw new IllegalArgumentException("Unexpected address identity type"); } } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Address.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -946,7 +1072,7 @@ public com.google.api.services.compute.model.Address call() { @Override public Operation create(final AddressInfo address, OperationOption... options) { final com.google.api.services.compute.model.Address addressPb = - address.setProjectId(options().projectId()).toPb(); + address.setProjectId(getOptions().getProjectId()).toPb(); final Map optionsMap = optionMap(options); try { return Operation.fromPb(this, @@ -964,7 +1090,7 @@ public com.google.api.services.compute.model.Operation call() { throw new IllegalArgumentException("Unexpected address identity type"); } } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); } @@ -975,14 +1101,14 @@ private static Function return new Function() { @Override public Address apply(com.google.api.services.compute.model.Address address) { - return Address.fromPb(serviceOptions.service(), address); + return Address.fromPb(serviceOptions.getService(), address); } }; } @Override public Page
    listGlobalAddresses(AddressListOption... options) { - return listGlobalAddresses(options(), optionMap(options)); + return listGlobalAddresses(getOptions(), optionMap(options)); } private static Page
    listGlobalAddresses(final ComputeOptions serviceOptions, @@ -994,9 +1120,9 @@ private static Page
    listGlobalAddresses(final ComputeOptions serviceOpt @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listGlobalAddresses(optionsMap); + return serviceOptions.getRpc().listGlobalAddresses(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable
    operations = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -1010,7 +1136,7 @@ Iterable> call() { @Override public Page
    listRegionAddresses(String region, AddressListOption... options) { - return listRegionAddresses(region, options(), optionMap(options)); + return listRegionAddresses(region, getOptions(), optionMap(options)); } private static Page
    listRegionAddresses(final String region, @@ -1022,9 +1148,9 @@ private static Page
    listRegionAddresses(final String region, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listRegionAddresses(region, optionsMap); + return serviceOptions.getRpc().listRegionAddresses(region, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable
    operations = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -1038,7 +1164,7 @@ Iterable> call() { @Override public Page
    listAddresses(AddressAggregatedListOption... options) { - return listAddresses(options(), optionMap(options)); + return listAddresses(getOptions(), optionMap(options)); } private static Page
    listAddresses(final ComputeOptions serviceOptions, @@ -1050,9 +1176,9 @@ private static Page
    listAddresses(final ComputeOptions serviceOptions, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listAddresses(optionsMap); + return serviceOptions.getRpc().listAddresses(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable
    operations = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -1060,7 +1186,7 @@ Iterable> call() { new Function() { @Override public Address apply(com.google.api.services.compute.model.Address address) { - return Address.fromPb(serviceOptions.service(), address); + return Address.fromPb(serviceOptions.getService(), address); } }); return new PageImpl<>(new AggregatedAddressPageFetcher(serviceOptions, cursor, optionsMap), @@ -1089,7 +1215,7 @@ public com.google.api.services.compute.model.Operation call() { throw new IllegalArgumentException("Unexpected address identity type"); } } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1098,7 +1224,7 @@ public com.google.api.services.compute.model.Operation call() { @Override public Operation create(SnapshotInfo snapshot, OperationOption... options) { - final SnapshotInfo completeSnapshot = snapshot.setProjectId(options().projectId()); + final SnapshotInfo completeSnapshot = snapshot.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { com.google.api.services.compute.model.Operation answer = @@ -1110,7 +1236,7 @@ public com.google.api.services.compute.model.Operation call() { completeSnapshot.getSnapshotId().getSnapshot(), completeSnapshot.getDescription(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1127,7 +1253,7 @@ public Snapshot getSnapshot(final String snapshot, SnapshotOption... options) { public com.google.api.services.compute.model.Snapshot call() { return computeRpc.getSnapshot(snapshot, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Snapshot.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1136,7 +1262,7 @@ public com.google.api.services.compute.model.Snapshot call() { @Override public Page listSnapshots(SnapshotListOption... options) { - return listSnapshots(options(), optionMap(options)); + return listSnapshots(getOptions(), optionMap(options)); } private static Page listSnapshots(final ComputeOptions serviceOptions, @@ -1148,9 +1274,9 @@ private static Page listSnapshots(final ComputeOptions serviceOptions, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listSnapshots(optionsMap); + return serviceOptions.getRpc().listSnapshots(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable snapshots = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -1158,7 +1284,7 @@ Iterable> call() { new Function() { @Override public Snapshot apply(com.google.api.services.compute.model.Snapshot snapshot) { - return Snapshot.fromPb(serviceOptions.service(), snapshot); + return Snapshot.fromPb(serviceOptions.getService(), snapshot); } }); return new PageImpl<>(new SnapshotPageFetcher(serviceOptions, cursor, optionsMap), cursor, @@ -1183,7 +1309,7 @@ public Operation deleteSnapshot(final String snapshot, OperationOption... option public com.google.api.services.compute.model.Operation call() { return computeRpc.deleteSnapshot(snapshot, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1192,7 +1318,7 @@ public com.google.api.services.compute.model.Operation call() { @Override public Operation create(ImageInfo image, OperationOption... options) { - final ImageInfo completeImage = image.setProjectId(options().projectId()); + final ImageInfo completeImage = image.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { com.google.api.services.compute.model.Operation answer = @@ -1201,7 +1327,7 @@ public Operation create(ImageInfo image, OperationOption... options) { public com.google.api.services.compute.model.Operation call() { return computeRpc.createImage(completeImage.toPb(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1210,7 +1336,7 @@ public com.google.api.services.compute.model.Operation call() { @Override public Image getImage(ImageId imageId, ImageOption... options) { - final ImageId completeImageId = imageId.setProjectId(options().projectId()); + final ImageId completeImageId = imageId.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { com.google.api.services.compute.model.Image answer = @@ -1220,7 +1346,7 @@ public com.google.api.services.compute.model.Image call() { return computeRpc.getImage(completeImageId.getProject(), completeImageId.getImage(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Image.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1229,12 +1355,12 @@ public com.google.api.services.compute.model.Image call() { @Override public Page listImages(String project, ImageListOption... options) { - return listImages(project, options(), optionMap(options)); + return listImages(project, getOptions(), optionMap(options)); } @Override public Page listImages(ImageListOption... options) { - return listImages(options().projectId(), options(), optionMap(options)); + return listImages(getOptions().getProjectId(), getOptions(), optionMap(options)); } private static Page listImages(final String project, final ComputeOptions serviceOptions, @@ -1246,9 +1372,9 @@ private static Page listImages(final String project, final ComputeOptions @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listImages(project, optionsMap); + return serviceOptions.getRpc().listImages(project, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable images = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -1256,7 +1382,7 @@ Iterable> call() { new Function() { @Override public Image apply(com.google.api.services.compute.model.Image image) { - return Image.fromPb(serviceOptions.service(), image); + return Image.fromPb(serviceOptions.getService(), image); } }); return new PageImpl<>(new ImagePageFetcher(project, serviceOptions, cursor, optionsMap), @@ -1268,7 +1394,7 @@ public Image apply(com.google.api.services.compute.model.Image image) { @Override public Operation deleteImage(ImageId image, OperationOption... options) { - final ImageId completeId = image.setProjectId(options().projectId()); + final ImageId completeId = image.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { com.google.api.services.compute.model.Operation answer = @@ -1278,7 +1404,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.deleteImage(completeId.getProject(), completeId.getImage(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1288,7 +1414,7 @@ public com.google.api.services.compute.model.Operation call() { @Override public Operation deprecate(ImageId image, final DeprecationStatus deprecationStatus, OperationOption... options) { - final ImageId completeId = image.setProjectId(options().projectId()); + final ImageId completeId = image.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { com.google.api.services.compute.model.Operation answer = @@ -1298,7 +1424,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.deprecateImage(completeId.getProject(), completeId.getImage(), deprecationStatus.toPb(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1315,7 +1441,7 @@ public Disk getDisk(final DiskId diskId, DiskOption... options) { public com.google.api.services.compute.model.Disk call() { return computeRpc.getDisk(diskId.getZone(), diskId.getDisk(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Disk.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1325,7 +1451,7 @@ public com.google.api.services.compute.model.Disk call() { @Override public Operation create(final DiskInfo disk, OperationOption... options) { final com.google.api.services.compute.model.Disk diskPb = - disk.setProjectId(options().projectId()).toPb(); + disk.setProjectId(getOptions().getProjectId()).toPb(); final Map optionsMap = optionMap(options); try { return Operation.fromPb(this, @@ -1334,7 +1460,7 @@ public Operation create(final DiskInfo disk, OperationOption... options) { public com.google.api.services.compute.model.Operation call() { return computeRpc.createDisk(disk.getDiskId().getZone(), diskPb, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); } @@ -1345,14 +1471,14 @@ private static Function diskFr return new Function() { @Override public Disk apply(com.google.api.services.compute.model.Disk disk) { - return Disk.fromPb(serviceOptions.service(), disk); + return Disk.fromPb(serviceOptions.getService(), disk); } }; } @Override public Page listDisks(String zone, DiskListOption... options) { - return listDisks(zone, options(), optionMap(options)); + return listDisks(zone, getOptions(), optionMap(options)); } private static Page listDisks(final String zone, final ComputeOptions serviceOptions, @@ -1364,9 +1490,9 @@ private static Page listDisks(final String zone, final ComputeOptions serv @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listDisks(zone, optionsMap); + return serviceOptions.getRpc().listDisks(zone, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable disks = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -1380,7 +1506,7 @@ Iterable> call() { @Override public Page listDisks(DiskAggregatedListOption... options) { - return listDisks(options(), optionMap(options)); + return listDisks(getOptions(), optionMap(options)); } private static Page listDisks(final ComputeOptions serviceOptions, @@ -1392,9 +1518,9 @@ private static Page listDisks(final ComputeOptions serviceOptions, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listDisks(optionsMap); + return serviceOptions.getRpc().listDisks(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable disks = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -1416,7 +1542,7 @@ public Operation deleteDisk(final DiskId disk, OperationOption... options) { public com.google.api.services.compute.model.Operation call() { return computeRpc.deleteDisk(disk.getZone(), disk.getDisk(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1433,7 +1559,7 @@ public Operation resize(final DiskId disk, final long sizeGb, OperationOption... public com.google.api.services.compute.model.Operation call() { return computeRpc.resizeDisk(disk.getZone(), disk.getDisk(), sizeGb, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1441,7 +1567,7 @@ public com.google.api.services.compute.model.Operation call() { } public Operation create(SubnetworkInfo subnetwork, OperationOption... options) { - final SubnetworkInfo completeSubnetwork = subnetwork.setProjectId(options().projectId()); + final SubnetworkInfo completeSubnetwork = subnetwork.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { com.google.api.services.compute.model.Operation answer = @@ -1451,7 +1577,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.createSubnetwork(completeSubnetwork.getSubnetworkId().getRegion(), completeSubnetwork.toPb(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1469,7 +1595,7 @@ public com.google.api.services.compute.model.Subnetwork call() { return computeRpc.getSubnetwork(subnetworkId.getRegion(), subnetworkId.getSubnetwork(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Subnetwork.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1481,14 +1607,14 @@ public com.google.api.services.compute.model.Subnetwork call() { return new Function() { @Override public Subnetwork apply(com.google.api.services.compute.model.Subnetwork subnetwork) { - return Subnetwork.fromPb(serviceOptions.service(), subnetwork); + return Subnetwork.fromPb(serviceOptions.getService(), subnetwork); } }; } @Override public Page listSubnetworks(String region, SubnetworkListOption... options) { - return listSubnetworks(region, options(), optionMap(options)); + return listSubnetworks(region, getOptions(), optionMap(options)); } private static Page listSubnetworks(final String region, @@ -1500,9 +1626,9 @@ private static Page listSubnetworks(final String region, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listSubnetworks(region, optionsMap); + return serviceOptions.getRpc().listSubnetworks(region, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable subnetworks = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -1516,7 +1642,7 @@ Iterable> call() { @Override public Page listSubnetworks(SubnetworkAggregatedListOption... options) { - return listSubnetworks(options(), optionMap(options)); + return listSubnetworks(getOptions(), optionMap(options)); } private static Page listSubnetworks(final ComputeOptions serviceOptions, @@ -1528,9 +1654,9 @@ private static Page listSubnetworks(final ComputeOptions serviceOpti @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listSubnetworks(optionsMap); + return serviceOptions.getRpc().listSubnetworks(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable subnetworks = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -1553,7 +1679,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.deleteSubnetwork(subnetwork.getRegion(), subnetwork.getSubnetwork(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1562,7 +1688,7 @@ public com.google.api.services.compute.model.Operation call() { @Override public Operation create(NetworkInfo network, OperationOption... options) { - final NetworkInfo completeNetwork = network.setProjectId(options().projectId()); + final NetworkInfo completeNetwork = network.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { com.google.api.services.compute.model.Operation answer = @@ -1571,7 +1697,7 @@ public Operation create(NetworkInfo network, OperationOption... options) { public com.google.api.services.compute.model.Operation call() { return computeRpc.createNetwork(completeNetwork.toPb(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1588,7 +1714,7 @@ public Network getNetwork(final String network, NetworkOption... options) { public com.google.api.services.compute.model.Network call() { return computeRpc.getNetwork(network, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Network.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1597,7 +1723,7 @@ public com.google.api.services.compute.model.Network call() { @Override public Page listNetworks(NetworkListOption... options) { - return listNetworks(options(), optionMap(options)); + return listNetworks(getOptions(), optionMap(options)); } private static Page listNetworks(final ComputeOptions serviceOptions, @@ -1609,9 +1735,9 @@ private static Page listNetworks(final ComputeOptions serviceOptions, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listNetworks(optionsMap); + return serviceOptions.getRpc().listNetworks(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable networks = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -1619,7 +1745,7 @@ Iterable> call() { new Function() { @Override public Network apply(com.google.api.services.compute.model.Network network) { - return Network.fromPb(serviceOptions.service(), network); + return Network.fromPb(serviceOptions.getService(), network); } }); return new PageImpl<>(new NetworkPageFetcher(serviceOptions, cursor, optionsMap), @@ -1639,7 +1765,7 @@ public Operation deleteNetwork(final NetworkId network, OperationOption... optio public com.google.api.services.compute.model.Operation call() { return computeRpc.deleteNetwork(network.getNetwork(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1653,7 +1779,7 @@ public Operation deleteNetwork(String network, OperationOption... options) { @Override public Operation create(InstanceInfo instance, OperationOption... options) { - final InstanceInfo completeInstance = instance.setProjectId(options().projectId()); + final InstanceInfo completeInstance = instance.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { com.google.api.services.compute.model.Operation answer = @@ -1663,7 +1789,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.createInstance(completeInstance.getInstanceId().getZone(), completeInstance.toPb(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1680,7 +1806,7 @@ public Instance getInstance(final InstanceId instance, InstanceOption... options public com.google.api.services.compute.model.Instance call() { return computeRpc.getInstance(instance.getZone(), instance.getInstance(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Instance.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1692,14 +1818,14 @@ public com.google.api.services.compute.model.Instance call() { return new Function() { @Override public Instance apply(com.google.api.services.compute.model.Instance instance) { - return Instance.fromPb(serviceOptions.service(), instance); + return Instance.fromPb(serviceOptions.getService(), instance); } }; } @Override public Page listInstances(String zone, InstanceListOption... options) { - return listInstances(zone, options(), optionMap(options)); + return listInstances(zone, getOptions(), optionMap(options)); } private static Page listInstances(final String zone, @@ -1711,9 +1837,9 @@ private static Page listInstances(final String zone, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listInstances(zone, optionsMap); + return serviceOptions.getRpc().listInstances(zone, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable instances = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -1727,7 +1853,7 @@ Iterable> call() { @Override public Page listInstances(InstanceAggregatedListOption... options) { - return listInstances(options(), optionMap(options)); + return listInstances(getOptions(), optionMap(options)); } private static Page listInstances(final ComputeOptions serviceOptions, @@ -1739,9 +1865,9 @@ private static Page listInstances(final ComputeOptions serviceOptions, @Override public ComputeRpc.Tuple> call() { - return serviceOptions.rpc().listInstances(optionsMap); + return serviceOptions.getRpc().listInstances(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable instances = Iterables.transform( result.y() == null ? ImmutableList.of() @@ -1764,7 +1890,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.deleteInstance(instance.getZone(), instance.getInstance(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1783,7 +1909,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.addAccessConfig(instance.getZone(), instance.getInstance(), networkInterface, accessConfig.toPb(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1792,7 +1918,7 @@ public com.google.api.services.compute.model.Operation call() { private Operation attachDisk(final InstanceId instance, AttachedDisk diskToAttach, OperationOption... options) { - final AttachedDisk completeDisk = diskToAttach.setProjectId(options().projectId()); + final AttachedDisk completeDisk = diskToAttach.setProjectId(getOptions().getProjectId()); final Map optionsMap = optionMap(options); try { com.google.api.services.compute.model.Operation answer = @@ -1802,7 +1928,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.attachDisk(instance.getZone(), instance.getInstance(), completeDisk.toPb(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1843,7 +1969,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.deleteAccessConfig(instance.getZone(), instance.getInstance(), networkInterface, accessConfig, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1862,7 +1988,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.detachDisk(instance.getZone(), instance.getInstance(), deviceName, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1878,7 +2004,7 @@ public String call() { return computeRpc.getSerialPortOutput(instance.getZone(), instance.getInstance(), port, optionMap()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); } @@ -1893,7 +2019,7 @@ public String call() { return computeRpc.getSerialPortOutput(instance.getZone(), instance.getInstance(), null, optionMap()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); } @@ -1909,7 +2035,7 @@ public Operation reset(final InstanceId instance, OperationOption... options) { public com.google.api.services.compute.model.Operation call() { return computeRpc.reset(instance.getZone(), instance.getInstance(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1928,7 +2054,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.setDiskAutoDelete(instance.getZone(), instance.getInstance(), deviceName, autoDelete, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1938,7 +2064,8 @@ public com.google.api.services.compute.model.Operation call() { @Override public Operation setMachineType(final InstanceId instance, final MachineTypeId machineType, OperationOption... options) { - final String machineTypeUrl = machineType.setProjectId(options().projectId()).getSelfLink(); + final String machineTypeUrl = + machineType.setProjectId(getOptions().getProjectId()).getSelfLink(); final Map optionsMap = optionMap(options); try { com.google.api.services.compute.model.Operation answer = @@ -1948,7 +2075,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.setMachineType(instance.getZone(), instance.getInstance(), machineTypeUrl, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1967,7 +2094,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.setMetadata(instance.getZone(), instance.getInstance(), metadata.toPb(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -1986,7 +2113,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.setScheduling(instance.getZone(), instance.getInstance(), schedulingOptions.toPb(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -2004,7 +2131,7 @@ public com.google.api.services.compute.model.Operation call() { return computeRpc.setTags(instance.getZone(), instance.getInstance(), tags.toPb(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -2021,7 +2148,7 @@ public Operation start(final InstanceId instance, OperationOption... options) { public com.google.api.services.compute.model.Operation call() { return computeRpc.start(instance.getZone(), instance.getInstance(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); @@ -2038,7 +2165,7 @@ public Operation stop(final InstanceId instance, OperationOption... options) { public com.google.api.services.compute.model.Operation call() { return computeRpc.stop(instance.getZone(), instance.getInstance(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Operation.fromPb(this, answer); } catch (RetryHelper.RetryHelperException e) { throw ComputeException.translateAndThrow(e); diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeOptions.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeOptions.java index a5428c81ea59..b95c64243515 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeOptions.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/ComputeOptions.java @@ -71,17 +71,17 @@ private ComputeOptions(Builder builder) { } @Override - protected ComputeFactory defaultServiceFactory() { + protected ComputeFactory getDefaultServiceFactory() { return DefaultComputeFactory.INSTANCE; } @Override - protected ComputeRpcFactory defaultRpcFactory() { + protected ComputeRpcFactory getDefaultRpcFactory() { return DefaultComputeRpcFactory.INSTANCE; } @Override - protected Set scopes() { + protected Set getScopes() { return SCOPES; } @@ -104,11 +104,21 @@ public boolean equals(Object obj) { return baseEquals(other); } + @Deprecated public static ComputeOptions defaultInstance() { - return builder().build(); + return getDefaultInstance(); } + public static ComputeOptions getDefaultInstance() { + return newBuilder().build(); + } + + @Deprecated public static Builder builder() { + return newBuilder(); + } + + public static Builder newBuilder() { return new Builder(); } } diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Disk.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Disk.java index 41a7f95b91b5..47e03ae7aaf3 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Disk.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Disk.java @@ -146,7 +146,7 @@ public Disk build() { Disk(Compute compute, DiskInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.compute = checkNotNull(compute); - this.options = compute.options(); + this.options = compute.getOptions(); } /** @@ -279,7 +279,7 @@ public final int hashCode() { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); - this.compute = options.service(); + this.compute = options.getService(); } static Disk fromPb(Compute compute, com.google.api.services.compute.model.Disk diskPb) { diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Image.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Image.java index 0b5fbb8487e3..ed9579d9d8bb 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Image.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Image.java @@ -145,7 +145,7 @@ public Image build() { Image(Compute compute, ImageInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.compute = checkNotNull(compute); - this.options = compute.options(); + this.options = compute.getOptions(); } /** @@ -231,7 +231,7 @@ public final int hashCode() { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); - this.compute = options.service(); + this.compute = options.getService(); } static Image fromPb(Compute compute, com.google.api.services.compute.model.Image imagePb) { diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Instance.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Instance.java index c28761cbeaa9..b6d86441902f 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Instance.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Instance.java @@ -252,7 +252,7 @@ public Instance build() { Instance(Compute compute, Instance.BuilderImpl infoBuilder) { super(infoBuilder); this.compute = checkNotNull(compute); - this.options = compute.options(); + this.options = compute.getOptions(); } /** @@ -535,7 +535,7 @@ public final int hashCode() { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); - this.compute = options.service(); + this.compute = options.getService(); } static Instance fromPb(Compute compute, diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Network.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Network.java index 3f57619db859..35f8702fa237 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Network.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Network.java @@ -119,7 +119,7 @@ public Network build() { Network(Compute compute, NetworkInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.compute = checkNotNull(compute); - this.options = compute.options(); + this.options = compute.getOptions(); } /** @@ -210,7 +210,7 @@ public final int hashCode() { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); - this.compute = options.service(); + this.compute = options.getService(); } static Network fromPb(Compute compute, diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Operation.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Operation.java index c1034bc2de77..a92360197d13 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Operation.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Operation.java @@ -519,7 +519,7 @@ Operation build() { private Operation(Builder builder) { this.compute = checkNotNull(builder.compute); - this.options = compute.options(); + this.options = compute.getOptions(); this.generatedId = builder.generatedId; this.operationId = checkNotNull(builder.operationId); this.clientOperationId = builder.clientOperationId; @@ -919,8 +919,8 @@ public Operation waitFor(WaitForOption... waitOptions) throws InterruptedException, TimeoutException { WaitForOption.Timeout timeout = WaitForOption.Timeout.getOrDefault(waitOptions); CheckingPeriod checkingPeriod = CheckingPeriod.getOrDefault(waitOptions); - long timeoutMillis = timeout.timeoutMillis(); - Clock clock = options.clock(); + long timeoutMillis = timeout.getTimeoutMillis(); + Clock clock = options.getClock(); long startTime = clock.millis(); while (!isDone()) { if (timeoutMillis != -1 && (clock.millis() - startTime) >= timeoutMillis) { @@ -1049,7 +1049,7 @@ com.google.api.services.compute.model.Operation toPb() { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); - this.compute = options.service(); + this.compute = options.getService(); } static Operation fromPb(Compute compute, diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Snapshot.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Snapshot.java index 3947addb969a..1a8a23fb933f 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Snapshot.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Snapshot.java @@ -157,7 +157,7 @@ public Snapshot build() { Snapshot(Compute compute, SnapshotInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.compute = checkNotNull(compute); - this.options = compute.options(); + this.options = compute.getOptions(); } /** @@ -232,7 +232,7 @@ public final int hashCode() { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); - this.compute = options.service(); + this.compute = options.getService(); } static Snapshot fromPb(Compute compute, diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/Subnetwork.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/Subnetwork.java index c190d0201415..fde8630f2cc2 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/Subnetwork.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/Subnetwork.java @@ -133,7 +133,7 @@ public Subnetwork build() { Subnetwork(Compute compute, SubnetworkInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.compute = checkNotNull(compute); - this.options = compute.options(); + this.options = compute.getOptions(); } /** @@ -208,7 +208,7 @@ public final int hashCode() { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); - this.compute = options.service(); + this.compute = options.getService(); } static Subnetwork fromPb(Compute compute, diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/package-info.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/package-info.java index 51c9babdaeb6..3e41cf2bcfcc 100644 --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/package-info.java +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/package-info.java @@ -22,7 +22,7 @@ * * CreateSnapshot.java. *
     {@code
    - * Compute compute = ComputeOptions.defaultInstance().service();
    + * Compute compute = ComputeOptions.getDefaultInstance().getService();
      * DiskId diskId = DiskId.of("us-central1-a", "disk-name");
      * Disk disk = compute.getDisk(diskId, Compute.DiskOption.fields());
      * if (disk != null) {
    @@ -39,7 +39,7 @@
      * 
      * CreateInstance.java.
      * 
     {@code
    - * Compute compute = ComputeOptions.defaultInstance().service();
    + * Compute compute = ComputeOptions.getDefaultInstance().getService();
      * ImageId imageId = ImageId.of("debian-cloud", "debian-8-jessie-v20160329");
      * NetworkId networkId = NetworkId.of("default");
      * AttachedDisk attachedDisk = AttachedDisk.of(AttachedDisk.CreateDiskConfiguration.of(imageId));
    diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/spi/DefaultComputeRpc.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/spi/DefaultComputeRpc.java
    index 542a2aa2fcb7..b0bb3b598399 100644
    --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/spi/DefaultComputeRpc.java
    +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/spi/DefaultComputeRpc.java
    @@ -81,12 +81,12 @@ public class DefaultComputeRpc implements ComputeRpc {
       private final Compute compute;
     
       public DefaultComputeRpc(ComputeOptions options) {
    -    HttpTransport transport = options.httpTransportFactory().create();
    -    HttpRequestInitializer initializer = options.httpRequestInitializer();
    +    HttpTransport transport = options.getHttpTransportFactory().create();
    +    HttpRequestInitializer initializer = options.getHttpRequestInitializer();
         this.options = options;
         compute = new Compute.Builder(transport, new JacksonFactory(), initializer)
    -        .setRootUrl(options.host())
    -        .setApplicationName(options.applicationName())
    +        .setRootUrl(options.getHost())
    +        .setApplicationName(options.getApplicationName())
             .build();
       }
     
    @@ -98,7 +98,7 @@ private static ComputeException translate(IOException exception) {
       public DiskType getDiskType(String zone, String diskType, Map options) {
         try {
           return compute.diskTypes()
    -          .get(this.options.projectId(), zone, diskType)
    +          .get(this.options.getProjectId(), zone, diskType)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -110,7 +110,7 @@ public DiskType getDiskType(String zone, String diskType, Map options
       public Tuple> listDiskTypes(String zone, Map options) {
         try {
           DiskTypeList diskTypesList = compute.diskTypes()
    -          .list(this.options.projectId(), zone)
    +          .list(this.options.getProjectId(), zone)
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -127,7 +127,7 @@ public Tuple> listDiskTypes(String zone, Map> listDiskTypes(Map options) {
         try {
           DiskTypeAggregatedList aggregatedList = compute.diskTypes()
    -          .aggregatedList(this.options.projectId())
    +          .aggregatedList(this.options.getProjectId())
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -154,7 +154,7 @@ public Tuple> listDiskTypes(Map options) {
       public MachineType getMachineType(String zone, String machineType, Map options) {
         try {
           return compute.machineTypes()
    -          .get(this.options.projectId(), zone, machineType)
    +          .get(this.options.getProjectId(), zone, machineType)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -167,7 +167,7 @@ public Tuple> listMachineTypes(String zone,
           Map options) {
         try {
           MachineTypeList machineTypesList = compute.machineTypes()
    -          .list(this.options.projectId(), zone)
    +          .list(this.options.getProjectId(), zone)
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -184,7 +184,7 @@ public Tuple> listMachineTypes(String zone,
       public Tuple> listMachineTypes(Map options) {
         try {
           MachineTypeAggregatedList aggregatedList = compute.machineTypes()
    -          .aggregatedList(this.options.projectId())
    +          .aggregatedList(this.options.getProjectId())
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -211,7 +211,7 @@ public Tuple> listMachineTypes(Map opti
       public Region getRegion(String region, Map options) {
         try {
           return compute.regions()
    -          .get(this.options.projectId(), region)
    +          .get(this.options.getProjectId(), region)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -223,7 +223,7 @@ public Region getRegion(String region, Map options) {
       public Tuple> listRegions(Map options) {
         try {
           RegionList regionsList = compute.regions()
    -          .list(this.options.projectId())
    +          .list(this.options.getProjectId())
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -240,7 +240,7 @@ public Tuple> listRegions(Map options) {
       public Zone getZone(String zone, Map options) {
         try {
           return compute.zones()
    -          .get(this.options.projectId(), zone)
    +          .get(this.options.getProjectId(), zone)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -252,7 +252,7 @@ public Zone getZone(String zone, Map options) {
       public Tuple> listZones(Map options) {
         try {
           ZoneList zonesList = compute.zones()
    -          .list(this.options.projectId())
    +          .list(this.options.getProjectId())
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -281,7 +281,7 @@ public License getLicense(String project, String license, Map options
       public Operation getGlobalOperation(String operation, Map options) {
         try {
           return compute.globalOperations()
    -          .get(this.options.projectId(), operation)
    +          .get(this.options.getProjectId(), operation)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -293,7 +293,7 @@ public Operation getGlobalOperation(String operation, Map options) {
       public Tuple> listGlobalOperations(Map options) {
         try {
           OperationList operationsList = compute.globalOperations()
    -          .list(this.options.projectId())
    +          .list(this.options.getProjectId())
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -309,7 +309,7 @@ public Tuple> listGlobalOperations(Map op
       @Override
       public boolean deleteGlobalOperation(String operation) {
         try {
    -      compute.globalOperations().delete(this.options.projectId(), operation).execute();
    +      compute.globalOperations().delete(this.options.getProjectId(), operation).execute();
           return true;
         } catch (IOException ex) {
           return falseForNotFound(ex);
    @@ -320,7 +320,7 @@ public boolean deleteGlobalOperation(String operation) {
       public Operation getRegionOperation(String region, String operation, Map options) {
         try {
           return compute.regionOperations()
    -          .get(this.options.projectId(), region, operation)
    +          .get(this.options.getProjectId(), region, operation)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -333,7 +333,7 @@ public Tuple> listRegionOperations(String region,
           Map options) {
         try {
           OperationList operationsList = compute.regionOperations()
    -          .list(this.options.projectId(), region)
    +          .list(this.options.getProjectId(), region)
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -349,7 +349,7 @@ public Tuple> listRegionOperations(String region,
       @Override
       public boolean deleteRegionOperation(String region, String operation) {
         try {
    -      compute.regionOperations().delete(this.options.projectId(), region, operation).execute();
    +      compute.regionOperations().delete(this.options.getProjectId(), region, operation).execute();
           return true;
         } catch (IOException ex) {
           return falseForNotFound(ex);
    @@ -360,7 +360,7 @@ public boolean deleteRegionOperation(String region, String operation) {
       public Operation getZoneOperation(String zone, String operation, Map options) {
         try {
           return compute.zoneOperations()
    -          .get(this.options.projectId(), zone, operation)
    +          .get(this.options.getProjectId(), zone, operation)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -373,7 +373,7 @@ public Tuple> listZoneOperations(String zone,
           Map options) {
         try {
           OperationList operationsList = compute.zoneOperations()
    -          .list(this.options.projectId(), zone)
    +          .list(this.options.getProjectId(), zone)
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -389,7 +389,7 @@ public Tuple> listZoneOperations(String zone,
       @Override
       public boolean deleteZoneOperation(String zone, String operation) {
         try {
    -      compute.zoneOperations().delete(this.options.projectId(), zone, operation).execute();
    +      compute.zoneOperations().delete(this.options.getProjectId(), zone, operation).execute();
           return true;
         } catch (IOException ex) {
           return falseForNotFound(ex);
    @@ -400,7 +400,7 @@ public boolean deleteZoneOperation(String zone, String operation) {
       public Address getGlobalAddress(String address, Map options) {
         try {
           return compute.globalAddresses()
    -          .get(this.options.projectId(), address)
    +          .get(this.options.getProjectId(), address)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -412,7 +412,7 @@ public Address getGlobalAddress(String address, Map options) {
       public Operation createGlobalAddress(Address address, Map options) {
         try {
           return compute.globalAddresses()
    -          .insert(this.options.projectId(), address)
    +          .insert(this.options.getProjectId(), address)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -424,7 +424,7 @@ public Operation createGlobalAddress(Address address, Map options) {
       public Tuple> listGlobalAddresses(Map options) {
         try {
           AddressList addressList = compute.globalAddresses()
    -          .list(this.options.projectId())
    +          .list(this.options.getProjectId())
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -441,7 +441,7 @@ public Tuple> listGlobalAddresses(Map optio
       public Operation deleteGlobalAddress(String address, Map options) {
         try {
           return compute.globalAddresses()
    -          .delete(this.options.projectId(), address)
    +          .delete(this.options.getProjectId(), address)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -453,7 +453,7 @@ public Operation deleteGlobalAddress(String address, Map options) {
       public Address getRegionAddress(String region, String address, Map options) {
         try {
           return compute.addresses()
    -          .get(this.options.projectId(), region, address)
    +          .get(this.options.getProjectId(), region, address)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -465,7 +465,7 @@ public Address getRegionAddress(String region, String address, Map op
       public Operation createRegionAddress(String region, Address address, Map options) {
         try {
           return compute.addresses()
    -          .insert(this.options.projectId(), region, address)
    +          .insert(this.options.getProjectId(), region, address)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -478,7 +478,7 @@ public Tuple> listRegionAddresses(String region,
           Map options) {
         try {
           AddressList addressList = compute.addresses()
    -          .list(this.options.projectId(), region)
    +          .list(this.options.getProjectId(), region)
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -495,7 +495,7 @@ public Tuple> listRegionAddresses(String region,
       public Tuple> listAddresses(Map options) {
         try {
           AddressAggregatedList aggregatedList = compute.addresses()
    -          .aggregatedList(this.options.projectId())
    +          .aggregatedList(this.options.getProjectId())
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -522,7 +522,7 @@ public Tuple> listAddresses(Map options) {
       public Operation deleteRegionAddress(String region, String address, Map options) {
         try {
           return compute.addresses()
    -          .delete(this.options.projectId(), region, address)
    +          .delete(this.options.getProjectId(), region, address)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -536,7 +536,7 @@ public Operation createSnapshot(String zone, String disk, String snapshot, Strin
         Snapshot snapshotObject = new Snapshot().setName(snapshot).setDescription(description);
         try {
           return compute.disks()
    -          .createSnapshot(this.options.projectId(), zone, disk, snapshotObject)
    +          .createSnapshot(this.options.getProjectId(), zone, disk, snapshotObject)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -548,7 +548,7 @@ public Operation createSnapshot(String zone, String disk, String snapshot, Strin
       public Snapshot getSnapshot(String snapshot, Map options) {
         try {
           return compute.snapshots()
    -          .get(this.options.projectId(), snapshot)
    +          .get(this.options.getProjectId(), snapshot)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -560,7 +560,7 @@ public Snapshot getSnapshot(String snapshot, Map options) {
       public Tuple> listSnapshots(Map options) {
         try {
           SnapshotList snapshotList = compute.snapshots()
    -          .list(this.options.projectId())
    +          .list(this.options.getProjectId())
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -577,7 +577,7 @@ public Tuple> listSnapshots(Map options) {
       public Operation deleteSnapshot(String snapshot, Map options) {
         try {
           return compute.snapshots()
    -          .delete(this.options.projectId(), snapshot)
    +          .delete(this.options.getProjectId(), snapshot)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -589,7 +589,7 @@ public Operation deleteSnapshot(String snapshot, Map options) {
       public Operation createImage(Image image, Map options) {
         try {
           return compute.images()
    -          .insert(this.options.projectId(), image)
    +          .insert(this.options.getProjectId(), image)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -655,7 +655,7 @@ public Operation deprecateImage(String project, String image, DeprecationStatus
       public Disk getDisk(String zone, String disk, Map options) {
         try {
           return compute.disks()
    -          .get(this.options.projectId(), zone, disk)
    +          .get(this.options.getProjectId(), zone, disk)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -667,7 +667,7 @@ public Disk getDisk(String zone, String disk, Map options) {
       public Operation createDisk(String zone, Disk disk, Map options) {
         try {
           return compute.disks()
    -          .insert(this.options.projectId(), zone, disk)
    +          .insert(this.options.getProjectId(), zone, disk)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -679,7 +679,7 @@ public Operation createDisk(String zone, Disk disk, Map options) {
       public Tuple> listDisks(String zone, Map options) {
         try {
           DiskList diskList = compute.disks()
    -          .list(this.options.projectId(), zone)
    +          .list(this.options.getProjectId(), zone)
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -696,7 +696,7 @@ public Tuple> listDisks(String zone, Map optio
       public Tuple> listDisks(Map options) {
         try {
           DiskAggregatedList aggregatedList = compute.disks()
    -          .aggregatedList(this.options.projectId())
    +          .aggregatedList(this.options.getProjectId())
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -723,7 +723,7 @@ public Tuple> listDisks(Map options) {
       public Operation deleteDisk(String zone, String disk, Map options) {
         try {
           return compute.disks()
    -          .delete(this.options.projectId(), zone, disk)
    +          .delete(this.options.getProjectId(), zone, disk)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -735,7 +735,7 @@ public Operation deleteDisk(String zone, String disk, Map options) {
       public Operation resizeDisk(String zone, String disk, long sizeGb, Map options) {
         try {
           DisksResizeRequest resizeRequest = new DisksResizeRequest().setSizeGb(sizeGb);
    -      return compute.disks().resize(this.options.projectId(), zone, disk, resizeRequest)
    +      return compute.disks().resize(this.options.getProjectId(), zone, disk, resizeRequest)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -746,7 +746,7 @@ public Operation resizeDisk(String zone, String disk, long sizeGb, Map options) {
         try {
           return compute.subnetworks()
    -          .insert(this.options.projectId(), region, subnetwork)
    +          .insert(this.options.getProjectId(), region, subnetwork)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -758,7 +758,7 @@ public Operation createSubnetwork(String region, Subnetwork subnetwork, Map options) {
         try {
           return compute.subnetworks()
    -          .get(this.options.projectId(), region, subnetwork)
    +          .get(this.options.getProjectId(), region, subnetwork)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -771,7 +771,7 @@ public Tuple> listSubnetworks(String region,
           Map options) {
         try {
           SubnetworkList subnetworkList = compute.subnetworks()
    -          .list(this.options.projectId(), region)
    +          .list(this.options.getProjectId(), region)
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -788,7 +788,7 @@ public Tuple> listSubnetworks(String region,
       public Tuple> listSubnetworks(Map options) {
         try {
           SubnetworkAggregatedList aggregatedList = compute.subnetworks()
    -          .aggregatedList(this.options.projectId())
    +          .aggregatedList(this.options.getProjectId())
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -815,7 +815,7 @@ public Tuple> listSubnetworks(Map option
       public Operation deleteSubnetwork(String region, String subnetwork, Map options) {
         try {
           return compute.subnetworks()
    -          .delete(this.options.projectId(), region, subnetwork)
    +          .delete(this.options.getProjectId(), region, subnetwork)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -827,7 +827,7 @@ public Operation deleteSubnetwork(String region, String subnetwork, Map options) {
         try {
           return compute.networks()
    -          .insert(this.options.projectId(), network)
    +          .insert(this.options.getProjectId(), network)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -839,7 +839,7 @@ public Operation createNetwork(Network network, Map options) {
       public Network getNetwork(String network, Map options) {
         try {
           return compute.networks()
    -          .get(this.options.projectId(), network)
    +          .get(this.options.getProjectId(), network)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -851,7 +851,7 @@ public Network getNetwork(String network, Map options) {
       public Tuple> listNetworks(Map options) {
         try {
           NetworkList networkList = compute.networks()
    -          .list(this.options.projectId())
    +          .list(this.options.getProjectId())
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -868,7 +868,7 @@ public Tuple> listNetworks(Map options) {
       public Operation deleteNetwork(String network, Map options) {
         try {
           return compute.networks()
    -          .delete(this.options.projectId(), network)
    +          .delete(this.options.getProjectId(), network)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -880,7 +880,7 @@ public Operation deleteNetwork(String network, Map options) {
       public Operation createInstance(String zone, Instance instance, Map options) {
         try {
           return compute.instances()
    -          .insert(this.options.projectId(), zone, instance)
    +          .insert(this.options.getProjectId(), zone, instance)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -892,7 +892,7 @@ public Operation createInstance(String zone, Instance instance, Map o
       public Instance getInstance(String zone, String instance, Map options) {
         try {
           return compute.instances()
    -          .get(this.options.projectId(), zone, instance)
    +          .get(this.options.getProjectId(), zone, instance)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -904,7 +904,7 @@ public Instance getInstance(String zone, String instance, Map options
       public Tuple> listInstances(String zone, Map options) {
         try {
           InstanceList instanceList = compute.instances()
    -          .list(this.options.projectId(), zone)
    +          .list(this.options.getProjectId(), zone)
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -921,7 +921,7 @@ public Tuple> listInstances(String zone, Map> listInstances(Map options) {
         try {
           InstanceAggregatedList aggregatedList = compute.instances()
    -          .aggregatedList(this.options.projectId())
    +          .aggregatedList(this.options.getProjectId())
               .setFilter(Option.FILTER.getString(options))
               .setMaxResults(Option.MAX_RESULTS.getLong(options))
               .setPageToken(Option.PAGE_TOKEN.getString(options))
    @@ -948,7 +948,7 @@ public Tuple> listInstances(Map options) {
       public Operation deleteInstance(String zone, String instance, Map options) {
         try {
           return compute.instances()
    -          .delete(this.options.projectId(), zone, instance)
    +          .delete(this.options.getProjectId(), zone, instance)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -961,7 +961,8 @@ public Operation addAccessConfig(String zone, String instance, String networkInt
           AccessConfig accessConfig, Map options) {
         try {
           return compute.instances()
    -          .addAccessConfig(this.options.projectId(), zone, instance, networkInterface, accessConfig)
    +          .addAccessConfig(
    +              this.options.getProjectId(), zone, instance, networkInterface, accessConfig)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -974,7 +975,7 @@ public Operation attachDisk(String zone, String instance, AttachedDisk attachedD
           Map options) {
         try {
           return compute.instances()
    -          .attachDisk(this.options.projectId(), zone, instance, attachedDisk)
    +          .attachDisk(this.options.getProjectId(), zone, instance, attachedDisk)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -987,7 +988,7 @@ public Operation deleteAccessConfig(String zone, String instance, String network
           String accessConfig, Map options) {
         try {
           return compute.instances()
    -          .deleteAccessConfig(this.options.projectId(), zone, instance, accessConfig,
    +          .deleteAccessConfig(this.options.getProjectId(), zone, instance, accessConfig,
                   networkInterface)
               .setFields(Option.FIELDS.getString(options))
               .execute();
    @@ -1001,7 +1002,7 @@ public Operation detachDisk(String zone, String instance, String deviceName,
           Map options) {
         try {
           return compute.instances()
    -          .detachDisk(this.options.projectId(), zone, instance, deviceName)
    +          .detachDisk(this.options.getProjectId(), zone, instance, deviceName)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -1014,7 +1015,7 @@ public String getSerialPortOutput(String zone, String instance, Integer port,
           Map options) {
         try {
           SerialPortOutput portOutput = compute.instances()
    -          .getSerialPortOutput(this.options.projectId(), zone, instance)
    +          .getSerialPortOutput(this.options.getProjectId(), zone, instance)
               .setPort(port)
               .setFields(Option.FIELDS.getString(options))
               .execute();
    @@ -1028,7 +1029,7 @@ public String getSerialPortOutput(String zone, String instance, Integer port,
       public Operation reset(String zone, String instance, Map options) {
         try {
           return compute.instances()
    -          .reset(this.options.projectId(), zone, instance)
    +          .reset(this.options.getProjectId(), zone, instance)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -1041,7 +1042,7 @@ public Operation setDiskAutoDelete(String zone, String instance, String deviceNa
           boolean autoDelete, Map options) {
         try {
           return compute.instances()
    -          .setDiskAutoDelete(this.options.projectId(), zone, instance, autoDelete, deviceName)
    +          .setDiskAutoDelete(this.options.getProjectId(), zone, instance, autoDelete, deviceName)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -1056,7 +1057,7 @@ public Operation setMachineType(String zone, String instance, String machineType
           InstancesSetMachineTypeRequest request =
               new InstancesSetMachineTypeRequest().setMachineType(machineTypeUrl);
           return compute.instances()
    -          .setMachineType(this.options.projectId(), zone, instance, request)
    +          .setMachineType(this.options.getProjectId(), zone, instance, request)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -1069,7 +1070,7 @@ public Operation setMetadata(String zone, String instance, Metadata metadata,
           Map options) {
         try {
           return compute.instances()
    -          .setMetadata(this.options.projectId(), zone, instance, metadata)
    +          .setMetadata(this.options.getProjectId(), zone, instance, metadata)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -1082,7 +1083,7 @@ public Operation setScheduling(String zone, String instance, Scheduling scheduli
           Map options) {
         try {
           return compute.instances()
    -          .setScheduling(this.options.projectId(), zone, instance, scheduling)
    +          .setScheduling(this.options.getProjectId(), zone, instance, scheduling)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -1094,7 +1095,7 @@ public Operation setScheduling(String zone, String instance, Scheduling scheduli
       public Operation setTags(String zone, String instance, Tags tags, Map options) {
         try {
           return compute.instances()
    -          .setTags(this.options.projectId(), zone, instance, tags)
    +          .setTags(this.options.getProjectId(), zone, instance, tags)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -1106,7 +1107,7 @@ public Operation setTags(String zone, String instance, Tags tags, Map
       public Operation start(String zone, String instance, Map options) {
         try {
           return compute.instances()
    -          .start(this.options.projectId(), zone, instance)
    +          .start(this.options.getProjectId(), zone, instance)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -1118,7 +1119,7 @@ public Operation start(String zone, String instance, Map options) {
       public Operation stop(String zone, String instance, Map options) {
         try {
           return compute.instances()
    -          .stop(this.options.projectId(), zone, instance)
    +          .stop(this.options.getProjectId(), zone, instance)
               .setFields(Option.FIELDS.getString(options))
               .execute();
         } catch (IOException ex) {
    @@ -1134,7 +1135,7 @@ public Operation stop(String zone, String instance, Map options) {
        */
       private static  T nullForNotFound(IOException exception) {
         ComputeException serviceException = translate(exception);
    -    if (serviceException.code() == HTTP_NOT_FOUND) {
    +    if (serviceException.getCode() == HTTP_NOT_FOUND) {
           return null;
         }
         throw serviceException;
    @@ -1148,7 +1149,7 @@ private static  T nullForNotFound(IOException exception) {
        */
       private static boolean falseForNotFound(IOException exception) {
         ComputeException serviceException = translate(exception);
    -    if (serviceException.code() == HTTP_NOT_FOUND) {
    +    if (serviceException.getCode() == HTTP_NOT_FOUND) {
           return false;
         }
         throw serviceException;
    diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/RemoteComputeHelper.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/RemoteComputeHelper.java
    index 92937c824ba0..ac39acd94ad4 100644
    --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/RemoteComputeHelper.java
    +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/RemoteComputeHelper.java
    @@ -29,12 +29,13 @@
     /**
      * Utility to create a remote Compute configuration for testing. Compute options can be obtained
      * via the {@link #options()} method. Returned options have custom
    - * {@link ComputeOptions#retryParams()}: {@link RetryParams#retryMaxAttempts()} is {@code 10},
    - * {@link RetryParams#retryMinAttempts()} is {@code 6}, {@link RetryParams#maxRetryDelayMillis()} is
    - * {@code 30000}, {@link RetryParams#totalRetryPeriodMillis()} is {@code 120000} and
    - * {@link RetryParams#initialRetryDelayMillis()} is {@code 250}.
    - * {@link ComputeOptions#connectTimeout()} and {@link ComputeOptions#readTimeout()} are both set to
    - * {@code 60000}.
    + * {@link ComputeOptions#getRetryParams()}: {@link RetryParams#getRetryMaxAttempts()} is {@code 10},
    + * {@link RetryParams#getRetryMinAttempts()} is {@code 6},
    + * {@link RetryParams#getMaxRetryDelayMillis()} is {@code 30000},
    + * {@link RetryParams#getTotalRetryPeriodMillis()} is {@code 120000} and
    + * {@link RetryParams#getInitialRetryDelayMillis()} is {@code 250}.
    + * {@link ComputeOptions#getConnectTimeout()} and {@link ComputeOptions#getReadTimeout()} are both
    + * set to {@code 60000}.
      */
     public class RemoteComputeHelper {
     
    @@ -81,12 +82,12 @@ public static String baseResourceName() {
        */
       public static RemoteComputeHelper create(String projectId, InputStream keyStream) {
         try {
    -      ComputeOptions computeOptions = ComputeOptions.builder()
    -          .authCredentials(AuthCredentials.createForJson(keyStream))
    -          .projectId(projectId)
    -          .retryParams(retryParams())
    -          .connectTimeout(60000)
    -          .readTimeout(60000)
    +      ComputeOptions computeOptions = ComputeOptions.newBuilder()
    +          .setAuthCredentials(AuthCredentials.createForJson(keyStream))
    +          .setProjectId(projectId)
    +          .setRetryParams(retryParams())
    +          .setConnectTimeout(60000)
    +          .setReadTimeout(60000)
               .build();
           return new RemoteComputeHelper(computeOptions);
         } catch (IOException ex) {
    @@ -102,21 +103,21 @@ public static RemoteComputeHelper create(String projectId, InputStream keyStream
        * credentials.
        */
       public static RemoteComputeHelper create() {
    -    ComputeOptions computeOptions = ComputeOptions.builder()
    -        .retryParams(retryParams())
    -        .connectTimeout(60000)
    -        .readTimeout(60000)
    +    ComputeOptions computeOptions = ComputeOptions.newBuilder()
    +        .setRetryParams(retryParams())
    +        .setConnectTimeout(60000)
    +        .setReadTimeout(60000)
             .build();
         return new RemoteComputeHelper(computeOptions);
       }
     
       private static RetryParams retryParams() {
    -    return RetryParams.builder()
    -        .retryMaxAttempts(10)
    -        .retryMinAttempts(6)
    -        .maxRetryDelayMillis(30000)
    -        .totalRetryPeriodMillis(120000)
    -        .initialRetryDelayMillis(250)
    +    return RetryParams.newBuilder()
    +        .setRetryMaxAttempts(10)
    +        .setRetryMinAttempts(6)
    +        .setMaxRetryDelayMillis(30000)
    +        .setTotalRetryPeriodMillis(120000)
    +        .setInitialRetryDelayMillis(250)
             .build();
       }
     
    diff --git a/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/package-info.java b/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/package-info.java
    index 897999dfcce5..504df470906b 100644
    --- a/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/package-info.java
    +++ b/google-cloud-compute/src/main/java/com/google/cloud/compute/testing/package-info.java
    @@ -22,7 +22,7 @@
      * 

    Before the test: *

     {@code
      * RemoteComputeHelper computeHelper = RemoteComputeHelper.create();
    - * Compute compute = computeHelper.getOptions().service();
    + * Compute compute = computeHelper.getOptions().getService();
      * } 
    * * @see diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressTest.java index aca5721c6306..a5e23b99a21f 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/AddressTest.java @@ -66,7 +66,7 @@ public class AddressTest { private Address address; private void initializeExpectedAddress(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); instanceAddress = new Address.Builder(serviceMockReturnsOptions, REGION_ADDRESS_ID) .setAddress(ADDRESS) @@ -257,7 +257,7 @@ public void testToAndFromPb() { @Test public void testDeleteOperation() { initializeExpectedAddress(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(GlobalOperationId.of("project", "op")) .build(); @@ -270,7 +270,7 @@ public void testDeleteOperation() { @Test public void testDeleteNull() { initializeExpectedAddress(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.deleteAddress(REGION_ADDRESS_ID)).andReturn(null); replay(compute); initializeAddress(); @@ -281,7 +281,7 @@ public void testDeleteNull() { public void testExists_True() throws Exception { initializeExpectedAddress(3); Compute.AddressOption[] expectedOptions = {Compute.AddressOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getAddress(REGION_ADDRESS_ID, expectedOptions)).andReturn(regionForwardingAddress); replay(compute); initializeAddress(); @@ -293,7 +293,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { initializeExpectedAddress(3); Compute.AddressOption[] expectedOptions = {Compute.AddressOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getAddress(REGION_ADDRESS_ID, expectedOptions)).andReturn(null); replay(compute); initializeAddress(); @@ -304,7 +304,7 @@ public void testExists_False() throws Exception { @Test public void testReload() throws Exception { initializeExpectedAddress(5); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getAddress(REGION_ADDRESS_ID)).andReturn(regionForwardingAddress); replay(compute); initializeAddress(); @@ -316,7 +316,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedAddress(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getAddress(REGION_ADDRESS_ID)).andReturn(null); replay(compute); initializeAddress(); @@ -327,7 +327,7 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedAddress(5); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getAddress(REGION_ADDRESS_ID, Compute.AddressOption.fields())) .andReturn(regionForwardingAddress); replay(compute); @@ -339,7 +339,7 @@ public void testReloadWithOptions() throws Exception { private void compareAddress(Address expected, Address value) { assertEquals(expected, value); - assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getCompute().getOptions(), value.getCompute().getOptions()); assertEquals(expected.getAddress(), value.getAddress()); assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); assertEquals(expected.getDescription(), value.getDescription()); diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/ComputeExceptionTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/ComputeExceptionTest.java index 2705a739814b..0d5b271a475d 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/ComputeExceptionTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/ComputeExceptionTest.java @@ -39,33 +39,33 @@ public class ComputeExceptionTest { @Test public void testResourceManagerException() { ComputeException exception = new ComputeException(500, "message"); - assertEquals(500, exception.code()); + assertEquals(500, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new ComputeException(403, "message"); - assertEquals(403, exception.code()); + assertEquals(403, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertFalse(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertFalse(exception.isRetryable()); + assertTrue(exception.isIdempotent()); IOException cause = new SocketTimeoutException(); exception = new ComputeException(cause); - assertNull(exception.reason()); + assertNull(exception.getReason()); assertNull(exception.getMessage()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); exception = new ComputeException(403, "message", cause); - assertEquals(403, exception.code()); + assertEquals(403, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertFalse(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertFalse(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); } @@ -78,10 +78,10 @@ public void testTranslateAndThrow() throws Exception { try { ComputeException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(500, ex.code()); + assertEquals(500, ex.getCode()); assertEquals("message", ex.getMessage()); - assertTrue(ex.retryable()); - assertTrue(ex.idempotent()); + assertTrue(ex.isRetryable()); + assertTrue(ex.isIdempotent()); } finally { verify(exceptionMock); } @@ -93,10 +93,10 @@ public void testTranslateAndThrow() throws Exception { try { ComputeException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(ComputeException.UNKNOWN_CODE, ex.code()); + assertEquals(ComputeException.UNKNOWN_CODE, ex.getCode()); assertEquals("message", ex.getMessage()); - assertFalse(ex.retryable()); - assertTrue(ex.idempotent()); + assertFalse(ex.isRetryable()); + assertTrue(ex.isIdempotent()); assertSame(cause, ex.getCause()); } finally { verify(exceptionMock); diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/ComputeImplTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/ComputeImplTest.java index b8c4205586ff..27ac4551700d 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/ComputeImplTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/ComputeImplTest.java @@ -479,12 +479,12 @@ public void setUp() { EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(ComputeOptions.class))) .andReturn(computeRpcMock).times(2); EasyMock.replay(rpcFactoryMock); - options = ComputeOptions.builder() - .projectId(PROJECT) - .serviceRpcFactory(rpcFactoryMock) - .retryParams(RetryParams.noRetries()) + options = ComputeOptions.newBuilder() + .setProjectId(PROJECT) + .setServiceRpcFactory(rpcFactoryMock) + .setRetryParams(RetryParams.noRetries()) .build(); - Compute otherService = options.toBuilder().build().service(); + Compute otherService = options.toBuilder().build().getService(); globalOperation = new Operation.Builder(otherService) .getGeneratedId(GENERATED_ID) .setOperationId(GLOBAL_OPERATION_ID) @@ -555,8 +555,8 @@ public void tearDown() { @Test public void testGetOptions() { EasyMock.replay(computeRpcMock); - compute = options.service(); - assertSame(options, compute.options()); + compute = options.getService(); + assertSame(options, compute.getOptions()); } @Test @@ -565,7 +565,7 @@ public void testGetDiskType() { DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andReturn(DISK_TYPE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); DiskType diskType = compute.getDiskType(DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType()); assertEquals(DISK_TYPE, diskType); } @@ -576,7 +576,7 @@ public void testGetDiskType_Null() { DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getDiskType(DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType())); } @@ -586,7 +586,7 @@ public void testGetDiskTypeFromDiskTypeId() { DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andReturn(DISK_TYPE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); DiskType diskType = compute.getDiskType(DISK_TYPE_ID); assertEquals(DISK_TYPE, diskType); } @@ -599,7 +599,7 @@ public void testGetDiskTypeWithSelectedFields() { eq(DISK_TYPE_ID.getZone()), eq(DISK_TYPE_ID.getType()), capture(capturedOptions))) .andReturn(DISK_TYPE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); DiskType diskType = compute.getDiskType(DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), DISK_TYPE_OPTION_FIELDS); String selector = @@ -614,7 +614,7 @@ public void testGetDiskTypeWithSelectedFields() { @Test public void testListDiskTypes() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList diskTypeList = ImmutableList.of(DISK_TYPE, DISK_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(diskTypeList, DiskType.TO_PB_FUNCTION)); @@ -622,15 +622,15 @@ public void testListDiskTypes() { .andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listDiskTypes(DISK_TYPE_ID.getZone()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.values(), DiskType.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.getValues(), DiskType.class)); } @Test public void testListDiskTypesNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList diskTypeList = ImmutableList.of(DISK_TYPE, DISK_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(diskTypeList, DiskType.TO_PB_FUNCTION)); @@ -645,11 +645,12 @@ public void testListDiskTypesNextPage() { .andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listDiskTypes(DISK_TYPE_ID.getZone()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.values(), DiskType.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextDiskTypeList.toArray(), Iterables.toArray(page.values(), DiskType.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.getValues(), DiskType.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextDiskTypeList.toArray(), + Iterables.toArray(page.getValues(), DiskType.class)); } @Test @@ -660,16 +661,16 @@ public void testListEmptyDiskTypes() { EasyMock.expect(computeRpcMock.listDiskTypes(DISK_TYPE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Page page = compute.listDiskTypes(DISK_TYPE_ID.getZone()); - assertNull(page.nextPageCursor()); - assertArrayEquals(diskTypes.toArray(), Iterables.toArray(page.values(), DiskType.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(diskTypes.toArray(), Iterables.toArray(page.getValues(), DiskType.class)); } @Test public void testListDiskTypesWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList diskTypeList = ImmutableList.of(DISK_TYPE, DISK_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(diskTypeList, DiskType.TO_PB_FUNCTION)); @@ -678,29 +679,29 @@ public void testListDiskTypesWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listDiskTypes(DISK_TYPE_ID.getZone(), DISK_TYPE_LIST_PAGE_SIZE, DISK_TYPE_LIST_PAGE_TOKEN, DISK_TYPE_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.values(), DiskType.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.getValues(), DiskType.class)); } @Test public void testAggregatedListDiskTypes() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList diskTypeList = ImmutableList.of(DISK_TYPE, DISK_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(diskTypeList, DiskType.TO_PB_FUNCTION)); EasyMock.expect(computeRpcMock.listDiskTypes(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listDiskTypes(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.values(), DiskType.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.getValues(), DiskType.class)); } @Test public void testAggregatedListDiskTypesNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList diskTypeList = ImmutableList.of(DISK_TYPE, DISK_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(diskTypeList, DiskType.TO_PB_FUNCTION)); @@ -713,11 +714,12 @@ public void testAggregatedListDiskTypesNextPage() { EasyMock.expect(computeRpcMock.listDiskTypes(nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listDiskTypes(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.values(), DiskType.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextDiskTypeList.toArray(), Iterables.toArray(page.values(), DiskType.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.getValues(), DiskType.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextDiskTypeList.toArray(), + Iterables.toArray(page.getValues(), DiskType.class)); } @Test @@ -727,16 +729,16 @@ public void testAggregatedListEmptyDiskTypes() { ComputeRpc.Tuple.>of(null, diskTypes); EasyMock.expect(computeRpcMock.listDiskTypes(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Page page = compute.listDiskTypes(); - assertNull(page.nextPageCursor()); - assertArrayEquals(diskTypes.toArray(), Iterables.toArray(page.values(), DiskType.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(diskTypes.toArray(), Iterables.toArray(page.getValues(), DiskType.class)); } @Test public void testAggregatedListDiskTypesWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList diskTypeList = ImmutableList.of(DISK_TYPE, DISK_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(diskTypeList, DiskType.TO_PB_FUNCTION)); @@ -744,8 +746,8 @@ public void testAggregatedListDiskTypesWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listDiskTypes(DISK_TYPE_AGGREGATED_LIST_PAGE_SIZE, DISK_TYPE_AGGREGATED_LIST_PAGE_TOKEN, DISK_TYPE_AGGREGATED_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.values(), DiskType.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(diskTypeList.toArray(), Iterables.toArray(page.getValues(), DiskType.class)); } @Test @@ -755,7 +757,7 @@ public void testGetMachineType() { MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andReturn(MACHINE_TYPE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); MachineType machineType = compute.getMachineType(MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_ID.getType()); assertEquals(MACHINE_TYPE, machineType); @@ -768,7 +770,7 @@ public void testGetMachineType_Null() { MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getMachineType(MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_ID.getType())); } @@ -778,7 +780,7 @@ public void testGetMachineTypeFromMachineTypeId() { MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andReturn(MACHINE_TYPE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); MachineType machineType = compute.getMachineType(MACHINE_TYPE_ID); assertEquals(MACHINE_TYPE, machineType); } @@ -791,7 +793,7 @@ public void testGetMachineTypeWithSelectedFields() { capture(capturedOptions))) .andReturn(MACHINE_TYPE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); MachineType machineType = compute.getMachineType(MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_ID.getType(), MACHINE_TYPE_OPTION_FIELDS); String selector = @@ -806,7 +808,7 @@ public void testGetMachineTypeWithSelectedFields() { @Test public void testListMachineTypes() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList machineTypeList = ImmutableList.of(MACHINE_TYPE, MACHINE_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, @@ -815,8 +817,8 @@ public void testListMachineTypes() { .andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listMachineTypes(MACHINE_TYPE_ID.getZone()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(machineTypeList.toArray(), Iterables.toArray(page.values(), + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(machineTypeList.toArray(), Iterables.toArray(page.getValues(), MachineType.class)); } @@ -824,7 +826,7 @@ public void testListMachineTypes() { public void testListMachineTypesNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList machineTypeList = ImmutableList.of(MACHINE_TYPE, MACHINE_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, @@ -841,13 +843,13 @@ public void testListMachineTypesNextPage() { .andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listMachineTypes(MACHINE_TYPE_ID.getZone()); - assertEquals(cursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); assertArrayEquals(machineTypeList.toArray(), - Iterables.toArray(page.values(), MachineType.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); + Iterables.toArray(page.getValues(), MachineType.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); assertArrayEquals(nextMachineTypeList.toArray(), - Iterables.toArray(page.values(), MachineType.class)); + Iterables.toArray(page.getValues(), MachineType.class)); } @Test @@ -860,16 +862,17 @@ public void testListEmptyMachineTypes() { EasyMock.expect(computeRpcMock.listMachineTypes(MACHINE_TYPE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Page page = compute.listMachineTypes(MACHINE_TYPE_ID.getZone()); - assertNull(page.nextPageCursor()); - assertArrayEquals(machineTypes.toArray(), Iterables.toArray(page.values(), MachineType.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(machineTypes.toArray(), + Iterables.toArray(page.getValues(), MachineType.class)); } @Test public void testListMachineTypesWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList machineTypeList = ImmutableList.of(MACHINE_TYPE, MACHINE_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, @@ -880,15 +883,15 @@ public void testListMachineTypesWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listMachineTypes(MACHINE_TYPE_ID.getZone(), MACHINE_TYPE_LIST_PAGE_SIZE, MACHINE_TYPE_LIST_PAGE_TOKEN, MACHINE_TYPE_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); assertArrayEquals(machineTypeList.toArray(), - Iterables.toArray(page.values(), MachineType.class)); + Iterables.toArray(page.getValues(), MachineType.class)); } @Test public void testAggregatedListMachineTypes() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList machineTypeList = ImmutableList.of(MACHINE_TYPE, MACHINE_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, @@ -896,8 +899,8 @@ public void testAggregatedListMachineTypes() { EasyMock.expect(computeRpcMock.listMachineTypes(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listMachineTypes(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(machineTypeList.toArray(), Iterables.toArray(page.values(), + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(machineTypeList.toArray(), Iterables.toArray(page.getValues(), MachineType.class)); } @@ -905,7 +908,7 @@ public void testAggregatedListMachineTypes() { public void testAggregatedListMachineTypesNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList machineTypeList = ImmutableList.of(MACHINE_TYPE, MACHINE_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, @@ -920,13 +923,13 @@ public void testAggregatedListMachineTypesNextPage() { EasyMock.expect(computeRpcMock.listMachineTypes(nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listMachineTypes(); - assertEquals(cursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); assertArrayEquals(machineTypeList.toArray(), - Iterables.toArray(page.values(), MachineType.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); + Iterables.toArray(page.getValues(), MachineType.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); assertArrayEquals(nextMachineTypeList.toArray(), - Iterables.toArray(page.values(), MachineType.class)); + Iterables.toArray(page.getValues(), MachineType.class)); } @Test @@ -938,16 +941,17 @@ public void testAggregatedListEmptyMachineTypes() { machineTypes); EasyMock.expect(computeRpcMock.listMachineTypes(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Page page = compute.listMachineTypes(); - assertNull(page.nextPageCursor()); - assertArrayEquals(machineTypes.toArray(), Iterables.toArray(page.values(), MachineType.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(machineTypes.toArray(), + Iterables.toArray(page.getValues(), MachineType.class)); } @Test public void testAggregatedListMachineTypesWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList machineTypeList = ImmutableList.of(MACHINE_TYPE, MACHINE_TYPE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, @@ -957,9 +961,9 @@ public void testAggregatedListMachineTypesWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listMachineTypes(MACHINE_TYPE_AGGREGATED_LIST_PAGE_SIZE, MACHINE_TYPE_AGGREGATED_LIST_PAGE_TOKEN, MACHINE_TYPE_AGGREGATED_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); assertArrayEquals(machineTypeList.toArray(), - Iterables.toArray(page.values(), MachineType.class)); + Iterables.toArray(page.getValues(), MachineType.class)); } @Test @@ -967,7 +971,7 @@ public void testGetRegion() { EasyMock.expect(computeRpcMock.getRegion(REGION_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(REGION.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Region region = compute.getRegion(REGION_ID.getRegion()); assertEquals(REGION, region); } @@ -977,7 +981,7 @@ public void testGetRegion_Null() { EasyMock.expect(computeRpcMock.getRegion(REGION_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getRegion(REGION_ID.getRegion())); } @@ -987,7 +991,7 @@ public void testGetRegionWithSelectedFields() { EasyMock.expect(computeRpcMock.getRegion(eq(REGION_ID.getRegion()), capture(capturedOptions))) .andReturn(REGION.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Region region = compute.getRegion(REGION_ID.getRegion(), REGION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(REGION_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); @@ -1000,22 +1004,22 @@ public void testGetRegionWithSelectedFields() { @Test public void testListRegions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList regionList = ImmutableList.of(REGION, REGION); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(regionList, Region.TO_PB_FUNCTION)); EasyMock.expect(computeRpcMock.listRegions(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listRegions(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(regionList.toArray(), Iterables.toArray(page.values(), Region.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(regionList.toArray(), Iterables.toArray(page.getValues(), Region.class)); } @Test public void testListRegionsNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList regionList = ImmutableList.of(REGION, REGION); ImmutableList nextRegionList = ImmutableList.of(REGION); ComputeRpc.Tuple> result = @@ -1027,11 +1031,11 @@ public void testListRegionsNextPage() { EasyMock.expect(computeRpcMock.listRegions(nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listRegions(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(regionList.toArray(), Iterables.toArray(page.values(), Region.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextRegionList.toArray(), Iterables.toArray(page.values(), Region.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(regionList.toArray(), Iterables.toArray(page.getValues(), Region.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextRegionList.toArray(), Iterables.toArray(page.getValues(), Region.class)); } @Test @@ -1042,16 +1046,16 @@ public void testListEmptyRegions() { regions); EasyMock.expect(computeRpcMock.listRegions(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Page page = compute.listRegions(); - assertNull(page.nextPageCursor()); - assertArrayEquals(regions.toArray(), Iterables.toArray(page.values(), Region.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(regions.toArray(), Iterables.toArray(page.getValues(), Region.class)); } @Test public void testListRegionsWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList regionList = ImmutableList.of(REGION, REGION); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(regionList, Region.TO_PB_FUNCTION)); @@ -1059,8 +1063,8 @@ public void testListRegionsWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listRegions(REGION_LIST_PAGE_SIZE, REGION_LIST_PAGE_TOKEN, REGION_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(regionList.toArray(), Iterables.toArray(page.values(), Region.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(regionList.toArray(), Iterables.toArray(page.getValues(), Region.class)); } @Test @@ -1068,7 +1072,7 @@ public void testGetZone() { EasyMock.expect(computeRpcMock.getZone(ZONE_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(ZONE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Zone zone = compute.getZone(ZONE_ID.getZone()); assertEquals(ZONE, zone); } @@ -1077,7 +1081,7 @@ public void testGetZone() { public void testGetZone_Null() { EasyMock.expect(computeRpcMock.getZone(ZONE_ID.getZone(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getZone(ZONE_ID.getZone())); } @@ -1087,7 +1091,7 @@ public void testGetZoneWithSelectedFields() { EasyMock.expect(computeRpcMock.getZone(eq(ZONE_ID.getZone()), capture(capturedOptions))) .andReturn(ZONE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Zone zone = compute.getZone(ZONE_ID.getZone(), ZONE_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(ZONE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); @@ -1100,22 +1104,22 @@ public void testGetZoneWithSelectedFields() { @Test public void testListZones() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList zoneList = ImmutableList.of(ZONE, ZONE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(zoneList, Zone.TO_PB_FUNCTION)); EasyMock.expect(computeRpcMock.listZones(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listZones(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(zoneList.toArray(), Iterables.toArray(page.values(), Zone.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(zoneList.toArray(), Iterables.toArray(page.getValues(), Zone.class)); } @Test public void testListZonesNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList zoneList = ImmutableList.of(ZONE, ZONE); ImmutableList nextZoneList = ImmutableList.of(ZONE); ComputeRpc.Tuple> result = @@ -1127,11 +1131,11 @@ public void testListZonesNextPage() { EasyMock.expect(computeRpcMock.listZones(nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listZones(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(zoneList.toArray(), Iterables.toArray(page.values(), Zone.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextZoneList.toArray(), Iterables.toArray(page.values(), Zone.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(zoneList.toArray(), Iterables.toArray(page.getValues(), Zone.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextZoneList.toArray(), Iterables.toArray(page.getValues(), Zone.class)); } @Test @@ -1141,16 +1145,16 @@ public void testListEmptyZones() { ComputeRpc.Tuple.>of(null, zones); EasyMock.expect(computeRpcMock.listZones(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Page page = compute.listZones(); - assertNull(page.nextPageCursor()); - assertArrayEquals(zones.toArray(), Iterables.toArray(page.values(), Zone.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(zones.toArray(), Iterables.toArray(page.getValues(), Zone.class)); } @Test public void testListZonesWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList zoneList = ImmutableList.of(ZONE, ZONE); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(zoneList, Zone.TO_PB_FUNCTION)); @@ -1158,8 +1162,8 @@ public void testListZonesWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listZones(ZONE_LIST_PAGE_SIZE, ZONE_LIST_PAGE_TOKEN, ZONE_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(zoneList.toArray(), Iterables.toArray(page.values(), Zone.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(zoneList.toArray(), Iterables.toArray(page.getValues(), Zone.class)); } @Test @@ -1167,7 +1171,7 @@ public void testGetLicenseFromString() { EasyMock.expect(computeRpcMock.getLicense(PROJECT, LICENSE_ID.getLicense(), EMPTY_RPC_OPTIONS)) .andReturn(LICENSE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); License license = compute.getLicense(LICENSE_ID.getLicense()); assertEquals(LICENSE, license); } @@ -1177,7 +1181,7 @@ public void testGetLicenseFromString_Null() { EasyMock.expect(computeRpcMock.getLicense(PROJECT, LICENSE_ID.getLicense(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getLicense(LICENSE_ID.getLicense())); } @@ -1188,7 +1192,7 @@ public void testGetLicenseFromStringWithOptions() { eq(PROJECT), eq(LICENSE_ID.getLicense()), capture(capturedOptions))) .andReturn(LICENSE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); License license = compute.getLicense(LICENSE_ID.getLicense(), LICENSE_OPTION_FIELDS); assertEquals(LICENSE, license); String selector = (String) capturedOptions.getValue().get(LICENSE_OPTION_FIELDS.getRpcOption()); @@ -1206,7 +1210,7 @@ public void testGetLicenseFromIdWithOptions() { eq(licenseId.getProject()), eq(licenseId.getLicense()), capture(capturedOptions))) .andReturn(LICENSE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); License license = compute.getLicense(licenseId, LICENSE_OPTION_FIELDS); assertEquals(LICENSE, license); String selector = (String) capturedOptions.getValue().get(LICENSE_OPTION_FIELDS.getRpcOption()); @@ -1222,7 +1226,7 @@ public void testGetLicenseFromId() { EasyMock.expect(computeRpcMock.getLicense(licenseId.getProject(), licenseId.getLicense(), EMPTY_RPC_OPTIONS)).andReturn(LICENSE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); License license = compute.getLicense(licenseId); assertEquals(LICENSE, license); } @@ -1234,7 +1238,7 @@ public void testGetLicenseFromId_Null() { licenseId.getProject(), licenseId.getLicense(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getLicense(licenseId)); } @@ -1244,7 +1248,7 @@ public void testGetGlobalOperation() { computeRpcMock.getGlobalOperation(GLOBAL_OPERATION_ID.getOperation(), EMPTY_RPC_OPTIONS)) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(globalOperation, compute.getOperation(GLOBAL_OPERATION_ID)); } @@ -1254,7 +1258,7 @@ public void testGetGlobalOperation_Null() { computeRpcMock.getGlobalOperation(GLOBAL_OPERATION_ID.getOperation(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getOperation(GLOBAL_OPERATION_ID)); } @@ -1265,7 +1269,7 @@ public void testGetGlobalOperationWithSelectedFields() { eq(GLOBAL_OPERATION_ID.getOperation()), capture(capturedOptions))) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.getOperation(GLOBAL_OPERATION_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -1279,22 +1283,23 @@ public void testGetGlobalOperationWithSelectedFields() { @Test public void testListGlobalOperations() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList operationList = ImmutableList.of(globalOperation, globalOperation); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); EasyMock.expect(computeRpcMock.listGlobalOperations(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listGlobalOperations(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(operationList.toArray(), + Iterables.toArray(page.getValues(), Operation.class)); } @Test public void testListGlobalOperationsNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList operationList = ImmutableList.of(globalOperation, globalOperation); ImmutableList nextOperationList = ImmutableList.of(globalOperation); ComputeRpc.Tuple> result = @@ -1307,12 +1312,13 @@ public void testListGlobalOperationsNextPage() { EasyMock.expect(computeRpcMock.listGlobalOperations(nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listGlobalOperations(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(operationList.toArray(), + Iterables.toArray(page.getValues(), Operation.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); assertArrayEquals(nextOperationList.toArray(), - Iterables.toArray(page.values(), Operation.class)); + Iterables.toArray(page.getValues(), Operation.class)); } @Test @@ -1323,16 +1329,16 @@ public void testListEmptyGlobalOperations() { operations); EasyMock.expect(computeRpcMock.listGlobalOperations(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Page page = compute.listGlobalOperations(); - assertNull(page.nextPageCursor()); - assertArrayEquals(operations.toArray(), Iterables.toArray(page.values(), Operation.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(operations.toArray(), Iterables.toArray(page.getValues(), Operation.class)); } @Test public void testListGlobalOperationsWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList operationList = ImmutableList.of(globalOperation, globalOperation); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); @@ -1340,8 +1346,9 @@ public void testListGlobalOperationsWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listGlobalOperations(OPERATION_LIST_PAGE_SIZE, OPERATION_LIST_PAGE_TOKEN, OPERATION_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(operationList.toArray(), + Iterables.toArray(page.getValues(), Operation.class)); } @Test @@ -1349,7 +1356,7 @@ public void testDeleteGlobalOperation_True() { EasyMock.expect(computeRpcMock.deleteGlobalOperation(GLOBAL_OPERATION_ID.getOperation())) .andReturn(true); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertTrue(compute.deleteOperation(GLOBAL_OPERATION_ID)); } @@ -1358,7 +1365,7 @@ public void testDeleteGlobalOperation_False() { EasyMock.expect(computeRpcMock.deleteGlobalOperation(GLOBAL_OPERATION_ID.getOperation())) .andReturn(false); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertFalse(compute.deleteOperation(GLOBAL_OPERATION_ID)); } @@ -1368,7 +1375,7 @@ public void testGetRegionOperation() { REGION_OPERATION_ID.getOperation(), EMPTY_RPC_OPTIONS)) .andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.getOperation(REGION_OPERATION_ID); assertEquals(regionOperation, operation); } @@ -1379,7 +1386,7 @@ public void testGetRegionOperation_Null() { REGION_OPERATION_ID.getOperation(), EMPTY_RPC_OPTIONS)) .andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.getOperation(REGION_OPERATION_ID); assertEquals(regionOperation, operation); } @@ -1391,7 +1398,7 @@ public void testGetRegionOperationWithSelectedFields() { eq(REGION_OPERATION_ID.getOperation()), capture(capturedOptions))) .andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.getOperation(REGION_OPERATION_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -1405,7 +1412,7 @@ public void testGetRegionOperationWithSelectedFields() { @Test public void testListRegionOperations() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList operationList = ImmutableList.of(regionOperation, regionOperation); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); @@ -1414,15 +1421,16 @@ public void testListRegionOperations() { .andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listRegionOperations(REGION_OPERATION_ID.getRegion()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(operationList.toArray(), + Iterables.toArray(page.getValues(), Operation.class)); } @Test public void testListRegionOperationsNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList operationList = ImmutableList.of(regionOperation, regionOperation); ImmutableList nextOperationList = ImmutableList.of(regionOperation); ComputeRpc.Tuple> result = @@ -1437,12 +1445,13 @@ public void testListRegionOperationsNextPage() { nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listRegionOperations(REGION_OPERATION_ID.getRegion()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(operationList.toArray(), + Iterables.toArray(page.getValues(), Operation.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); assertArrayEquals(nextOperationList.toArray(), - Iterables.toArray(page.values(), Operation.class)); + Iterables.toArray(page.getValues(), Operation.class)); } @Test @@ -1455,16 +1464,16 @@ public void testListEmptyRegionOperations() { computeRpcMock.listRegionOperations(REGION_OPERATION_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Page page = compute.listRegionOperations(REGION_OPERATION_ID.getRegion()); - assertNull(page.nextPageCursor()); - assertArrayEquals(operations.toArray(), Iterables.toArray(page.values(), Operation.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(operations.toArray(), Iterables.toArray(page.getValues(), Operation.class)); } @Test public void testListRegionOperationsWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList operationList = ImmutableList.of(regionOperation, regionOperation); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); @@ -1474,8 +1483,9 @@ public void testListRegionOperationsWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listRegionOperations(REGION_OPERATION_ID.getRegion(), OPERATION_LIST_PAGE_SIZE, OPERATION_LIST_PAGE_TOKEN, OPERATION_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(operationList.toArray(), + Iterables.toArray(page.getValues(), Operation.class)); } @Test @@ -1483,7 +1493,7 @@ public void testDeleteRegionOperation_True() { EasyMock.expect(computeRpcMock.deleteRegionOperation(REGION_OPERATION_ID.getRegion(), REGION_OPERATION_ID.getOperation())).andReturn(true); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertTrue(compute.deleteOperation(REGION_OPERATION_ID)); } @@ -1492,7 +1502,7 @@ public void testDeleteRegionOperation_False() { EasyMock.expect(computeRpcMock.deleteRegionOperation(REGION_OPERATION_ID.getRegion(), REGION_OPERATION_ID.getOperation())).andReturn(false); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertFalse(compute.deleteOperation(REGION_OPERATION_ID)); } @@ -1501,7 +1511,7 @@ public void testGetZoneOperation() { EasyMock.expect(computeRpcMock.getZoneOperation(ZONE_OPERATION_ID.getZone(), ZONE_OPERATION_ID.getOperation(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.getOperation(ZONE_OPERATION_ID); assertEquals(zoneOperation, operation); } @@ -1511,7 +1521,7 @@ public void testGetZoneOperation_Null() { EasyMock.expect(computeRpcMock.getZoneOperation(ZONE_OPERATION_ID.getZone(), ZONE_OPERATION_ID.getOperation(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getOperation(ZONE_OPERATION_ID)); } @@ -1522,7 +1532,7 @@ public void testGetZoneOperationWithSelectedFields() { eq(ZONE_OPERATION_ID.getOperation()), capture(capturedOptions))) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.getOperation(ZONE_OPERATION_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -1536,7 +1546,7 @@ public void testGetZoneOperationWithSelectedFields() { @Test public void testListZoneOperations() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList operationList = ImmutableList.of(zoneOperation, zoneOperation); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); @@ -1545,15 +1555,16 @@ public void testListZoneOperations() { .andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listZoneOperations(ZONE_OPERATION_ID.getZone()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(operationList.toArray(), + Iterables.toArray(page.getValues(), Operation.class)); } @Test public void testListZoneOperationsNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList operationList = ImmutableList.of(zoneOperation, zoneOperation); ImmutableList nextOperationList = ImmutableList.of(zoneOperation); ComputeRpc.Tuple> result = @@ -1569,12 +1580,13 @@ public void testListZoneOperationsNextPage() { .andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listZoneOperations(ZONE_OPERATION_ID.getZone()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(operationList.toArray(), + Iterables.toArray(page.getValues(), Operation.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); assertArrayEquals(nextOperationList.toArray(), - Iterables.toArray(page.values(), Operation.class)); + Iterables.toArray(page.getValues(), Operation.class)); } @Test @@ -1587,16 +1599,16 @@ public void testListEmptyZoneOperations() { computeRpcMock.listZoneOperations(ZONE_OPERATION_ID.getZone(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Page page = compute.listZoneOperations(ZONE_OPERATION_ID.getZone()); - assertNull(page.nextPageCursor()); - assertArrayEquals(operations.toArray(), Iterables.toArray(page.values(), Operation.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(operations.toArray(), Iterables.toArray(page.getValues(), Operation.class)); } @Test public void testListZoneOperationsWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList operationList = ImmutableList.of(zoneOperation, zoneOperation); ComputeRpc.Tuple> result = ComputeRpc.Tuple.of(cursor, Iterables.transform(operationList, OPERATION_TO_PB_FUNCTION)); @@ -1606,8 +1618,9 @@ public void testListZoneOperationsWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listZoneOperations(ZONE_OPERATION_ID.getZone(), OPERATION_LIST_PAGE_SIZE, OPERATION_LIST_PAGE_TOKEN, OPERATION_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(operationList.toArray(), Iterables.toArray(page.values(), Operation.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(operationList.toArray(), + Iterables.toArray(page.getValues(), Operation.class)); } @Test @@ -1615,7 +1628,7 @@ public void testDeleteZoneOperation_True() { EasyMock.expect(computeRpcMock.deleteZoneOperation(ZONE_OPERATION_ID.getZone(), ZONE_OPERATION_ID.getOperation())).andReturn(true); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertTrue(compute.deleteOperation(ZONE_OPERATION_ID)); } @@ -1624,7 +1637,7 @@ public void testDeleteZoneOperation_False() { EasyMock.expect(computeRpcMock.deleteZoneOperation(ZONE_OPERATION_ID.getZone(), ZONE_OPERATION_ID.getOperation())).andReturn(false); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertFalse(compute.deleteOperation(ZONE_OPERATION_ID)); } @@ -1634,7 +1647,7 @@ public void testGetGlobalAddress() { GLOBAL_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)) .andReturn(GLOBAL_ADDRESS.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Address address = compute.getAddress(GLOBAL_ADDRESS_ID); assertEquals(new Address(compute, new AddressInfo.BuilderImpl(GLOBAL_ADDRESS)), address); } @@ -1645,7 +1658,7 @@ public void testGetGlobalAddress_Null() { GLOBAL_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getAddress(GLOBAL_ADDRESS_ID)); } @@ -1656,7 +1669,7 @@ public void testGetGlobalAddressWithSelectedFields() { eq(GLOBAL_ADDRESS_ID.getAddress()), capture(capturedOptions))) .andReturn(GLOBAL_ADDRESS.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Address address = compute.getAddress(GLOBAL_ADDRESS_ID, ADDRESS_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(ADDRESS_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); @@ -1671,7 +1684,7 @@ public void testGetRegionAddress() { EasyMock.expect(computeRpcMock.getRegionAddress(REGION_ADDRESS_ID.getRegion(), REGION_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)).andReturn(REGION_ADDRESS.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Address address = compute.getAddress(REGION_ADDRESS_ID); assertEquals(new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS)), address); } @@ -1681,7 +1694,7 @@ public void testGetRegionAddress_Null() { EasyMock.expect(computeRpcMock.getRegionAddress(REGION_ADDRESS_ID.getRegion(), REGION_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)).andReturn(REGION_ADDRESS.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Address address = compute.getAddress(REGION_ADDRESS_ID); assertEquals(new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS)), address); } @@ -1693,7 +1706,7 @@ public void testGetRegionAddressWithSelectedFields() { eq(REGION_ADDRESS_ID.getAddress()), capture(capturedOptions))) .andReturn(REGION_ADDRESS.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Address address = compute.getAddress(REGION_ADDRESS_ID, ADDRESS_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(ADDRESS_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); @@ -1709,7 +1722,7 @@ public void testDeleteGlobalAddress_Operation() { GLOBAL_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(globalOperation, compute.deleteAddress(GLOBAL_ADDRESS_ID)); } @@ -1719,7 +1732,7 @@ public void testDeleteGlobalAddressWithSelectedFields_Operation() { EasyMock.expect(computeRpcMock.deleteGlobalAddress(eq(GLOBAL_ADDRESS_ID.getAddress()), capture(capturedOptions))).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.deleteAddress(GLOBAL_ADDRESS_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -1736,7 +1749,7 @@ public void testDeleteGlobalAddress_Null() { GLOBAL_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.deleteAddress(GLOBAL_ADDRESS_ID)); } @@ -1745,7 +1758,7 @@ public void testDeleteRegionAddress_Operation() { EasyMock.expect(computeRpcMock.deleteRegionAddress(REGION_ADDRESS_ID.getRegion(), REGION_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)).andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(regionOperation, compute.deleteAddress(REGION_ADDRESS_ID)); } @@ -1756,7 +1769,7 @@ public void testDeleteRegionAddressWithSelectedFields_Operation() { eq(REGION_ADDRESS_ID.getAddress()), capture(capturedOptions))) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.deleteAddress(REGION_ADDRESS_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -1772,14 +1785,14 @@ public void testDeleteRegionAddress_Null() { EasyMock.expect(computeRpcMock.deleteRegionAddress(REGION_ADDRESS_ID.getRegion(), REGION_ADDRESS_ID.getAddress(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.deleteAddress(REGION_ADDRESS_ID)); } @Test public void testListGlobalAddresses() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList
    addressList = ImmutableList.of( new Address(compute, new AddressInfo.BuilderImpl(GLOBAL_ADDRESS)), new Address(compute, new AddressInfo.BuilderImpl(GLOBAL_ADDRESS))); @@ -1788,15 +1801,15 @@ public void testListGlobalAddresses() { EasyMock.expect(computeRpcMock.listGlobalAddresses(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page
    page = compute.listGlobalAddresses(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(addressList.toArray(), Iterables.toArray(page.values(), Address.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(addressList.toArray(), Iterables.toArray(page.getValues(), Address.class)); } @Test public void testListGlobalAddressesNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList
    addressList = ImmutableList.of( new Address(compute, new AddressInfo.BuilderImpl(GLOBAL_ADDRESS)), new Address(compute, new AddressInfo.BuilderImpl(GLOBAL_ADDRESS))); @@ -1812,11 +1825,12 @@ public void testListGlobalAddressesNextPage() { EasyMock.expect(computeRpcMock.listGlobalAddresses(nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page
    page = compute.listGlobalAddresses(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(addressList.toArray(), Iterables.toArray(page.values(), Address.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextAddressList.toArray(), Iterables.toArray(page.values(), Address.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(addressList.toArray(), Iterables.toArray(page.getValues(), Address.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextAddressList.toArray(), + Iterables.toArray(page.getValues(), Address.class)); } @Test @@ -1826,16 +1840,16 @@ public void testListEmptyGlobalAddresses() { ComputeRpc.Tuple.>of(null, addresses); EasyMock.expect(computeRpcMock.listGlobalAddresses(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Page
    page = compute.listGlobalAddresses(); - assertNull(page.nextPageCursor()); - assertArrayEquals(addresses.toArray(), Iterables.toArray(page.values(), Address.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(addresses.toArray(), Iterables.toArray(page.getValues(), Address.class)); } @Test public void testListGlobalAddressesWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList
    addressList = ImmutableList.of( new Address(compute, new AddressInfo.BuilderImpl(GLOBAL_ADDRESS)), new Address(compute, new AddressInfo.BuilderImpl(GLOBAL_ADDRESS))); @@ -1845,14 +1859,14 @@ public void testListGlobalAddressesWithOptions() { EasyMock.replay(computeRpcMock); Page
    page = compute.listGlobalAddresses(ADDRESS_LIST_PAGE_SIZE, ADDRESS_LIST_PAGE_TOKEN, ADDRESS_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(addressList.toArray(), Iterables.toArray(page.values(), Address.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(addressList.toArray(), Iterables.toArray(page.getValues(), Address.class)); } @Test public void testListRegionAddresses() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList
    addressList = ImmutableList.of( new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS)), new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS))); @@ -1863,15 +1877,15 @@ public void testListRegionAddresses() { .andReturn(result); EasyMock.replay(computeRpcMock); Page
    page = compute.listRegionAddresses(REGION_ADDRESS_ID.getRegion()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(addressList.toArray(), Iterables.toArray(page.values(), Address.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(addressList.toArray(), Iterables.toArray(page.getValues(), Address.class)); } @Test public void testListRegionAddressesNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList
    addressList = ImmutableList.of( new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS)), new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS))); @@ -1891,11 +1905,12 @@ public void testListRegionAddressesNextPage() { .andReturn(nextResult); EasyMock.replay(computeRpcMock); Page
    page = compute.listRegionAddresses(REGION_ADDRESS_ID.getRegion()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(addressList.toArray(), Iterables.toArray(page.values(), Address.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextAddressList.toArray(), Iterables.toArray(page.values(), Address.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(addressList.toArray(), Iterables.toArray(page.getValues(), Address.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextAddressList.toArray(), + Iterables.toArray(page.getValues(), Address.class)); } @Test @@ -1907,16 +1922,16 @@ public void testListEmptyRegionAddresses() { computeRpcMock.listRegionAddresses(REGION_ADDRESS_ID.getRegion(), EMPTY_RPC_OPTIONS)) .andReturn(result); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Page
    page = compute.listRegionAddresses(REGION_ADDRESS_ID.getRegion()); - assertNull(page.nextPageCursor()); - assertArrayEquals(addresses.toArray(), Iterables.toArray(page.values(), Address.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(addresses.toArray(), Iterables.toArray(page.getValues(), Address.class)); } @Test public void testListRegionAddressesWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList
    addressList = ImmutableList.of( new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS)), new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS))); @@ -1928,14 +1943,14 @@ public void testListRegionAddressesWithOptions() { EasyMock.replay(computeRpcMock); Page
    page = compute.listRegionAddresses(REGION_ADDRESS_ID.getRegion(), ADDRESS_LIST_PAGE_SIZE, ADDRESS_LIST_PAGE_TOKEN, ADDRESS_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(addressList.toArray(), Iterables.toArray(page.values(), Address.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(addressList.toArray(), Iterables.toArray(page.getValues(), Address.class)); } @Test public void testAggregatedListAddresses() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList
    addressList = ImmutableList.of( new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS)), new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS))); @@ -1944,15 +1959,15 @@ public void testAggregatedListAddresses() { EasyMock.expect(computeRpcMock.listAddresses(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page
    page = compute.listAddresses(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(addressList.toArray(), Iterables.toArray(page.values(), Address.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(addressList.toArray(), Iterables.toArray(page.getValues(), Address.class)); } @Test public void testAggregatedListAddressesNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList
    addressList = ImmutableList.of( new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS)), new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS))); @@ -1968,11 +1983,12 @@ public void testAggregatedListAddressesNextPage() { EasyMock.expect(computeRpcMock.listAddresses(nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page
    page = compute.listAddresses(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(addressList.toArray(), Iterables.toArray(page.values(), Address.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextAddressList.toArray(), Iterables.toArray(page.values(), Address.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(addressList.toArray(), Iterables.toArray(page.getValues(), Address.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextAddressList.toArray(), + Iterables.toArray(page.getValues(), Address.class)); } @Test @@ -1982,16 +1998,16 @@ public void testAggregatedListEmptyAddresses() { ComputeRpc.Tuple.>of(null, addresses); EasyMock.expect(computeRpcMock.listAddresses(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Page
    page = compute.listAddresses(); - assertNull(page.nextPageCursor()); - assertArrayEquals(addresses.toArray(), Iterables.toArray(page.values(), Address.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(addresses.toArray(), Iterables.toArray(page.getValues(), Address.class)); } @Test public void testAggregatedListAddressesWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList
    addressList = ImmutableList.of( new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS)), new Address(compute, new AddressInfo.BuilderImpl(REGION_ADDRESS))); @@ -2001,8 +2017,8 @@ public void testAggregatedListAddressesWithOptions() { EasyMock.replay(computeRpcMock); Page
    page = compute.listAddresses(ADDRESS_AGGREGATED_LIST_PAGE_SIZE, ADDRESS_AGGREGATED_LIST_PAGE_TOKEN, ADDRESS_AGGREGATED_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(addressList.toArray(), Iterables.toArray(page.values(), Address.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(addressList.toArray(), Iterables.toArray(page.getValues(), Address.class)); } @Test @@ -2010,7 +2026,7 @@ public void testCreateGlobalAddress() { EasyMock.expect(computeRpcMock.createGlobalAddress(GLOBAL_ADDRESS.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); AddressId incompleteId = GlobalAddressId.of("address"); Operation operation = compute.create(GLOBAL_ADDRESS.toBuilder().setAddressId(incompleteId).build()); @@ -2024,7 +2040,7 @@ public void testCreateGlobalAddressWithOptions() { computeRpcMock.createGlobalAddress(eq(GLOBAL_ADDRESS.toPb()), capture(capturedOptions))) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.create(GLOBAL_ADDRESS, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -2040,7 +2056,7 @@ public void testCreateRegionAddress() { EasyMock.expect(computeRpcMock.createRegionAddress(REGION_ADDRESS_ID.getRegion(), REGION_ADDRESS.toPb(), EMPTY_RPC_OPTIONS)).andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); AddressId incompleteId = RegionAddressId.of("region", "address"); Operation operation = compute.create(REGION_ADDRESS.toBuilder().setAddressId(incompleteId).build()); @@ -2053,7 +2069,7 @@ public void testCreateRegionAddressWithOptions() { EasyMock.expect(computeRpcMock.createRegionAddress(eq(REGION_ADDRESS_ID.getRegion()), eq(REGION_ADDRESS.toPb()), capture(capturedOptions))).andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.create(REGION_ADDRESS, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -2069,7 +2085,7 @@ public void testCreateSnapshot() { EasyMock.expect(computeRpcMock.createSnapshot(DISK_ID.getZone(), DISK_ID.getDisk(), SNAPSHOT_ID.getSnapshot(), null, EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.create(SNAPSHOT); assertEquals(zoneOperation, operation); } @@ -2081,7 +2097,7 @@ public void testCreateSnapshotWithOptions() { eq(SNAPSHOT_ID.getSnapshot()), EasyMock.isNull(), capture(capturedOptions))) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.create(SNAPSHOT, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -2097,7 +2113,7 @@ public void testGetSnapshot() { EasyMock.expect(computeRpcMock.getSnapshot(SNAPSHOT_ID.getSnapshot(), EMPTY_RPC_OPTIONS)) .andReturn(SNAPSHOT.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Snapshot snapshot = compute.getSnapshot(SNAPSHOT_ID.getSnapshot()); assertEquals(new Snapshot(compute, new SnapshotInfo.BuilderImpl(SNAPSHOT)), snapshot); } @@ -2107,7 +2123,7 @@ public void testGetSnapshot_Null() { EasyMock.expect(computeRpcMock.getSnapshot(SNAPSHOT_ID.getSnapshot(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getSnapshot(SNAPSHOT_ID.getSnapshot())); } @@ -2117,7 +2133,7 @@ public void testGetSnapshotWithSelectedFields() { EasyMock.expect(computeRpcMock.getSnapshot(eq(SNAPSHOT_ID.getSnapshot()), capture(capturedOptions))).andReturn(SNAPSHOT.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Snapshot snapshot = compute.getSnapshot(SNAPSHOT_ID.getSnapshot(), SNAPSHOT_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(SNAPSHOT_OPTION_FIELDS.getRpcOption()); @@ -2133,7 +2149,7 @@ public void testDeleteSnapshot_Operation() { EasyMock.expect(computeRpcMock.deleteSnapshot(SNAPSHOT_ID.getSnapshot(), EMPTY_RPC_OPTIONS)) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(globalOperation, compute.deleteSnapshot(SNAPSHOT_ID.getSnapshot())); } @@ -2143,7 +2159,7 @@ public void testDeleteSnapshotWithSelectedFields_Operation() { EasyMock.expect(computeRpcMock.deleteSnapshot(eq(SNAPSHOT_ID.getSnapshot()), capture(capturedOptions))).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.deleteSnapshot(SNAPSHOT_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -2159,14 +2175,14 @@ public void testDeleteSnapshot_Null() { EasyMock.expect(computeRpcMock.deleteSnapshot(SNAPSHOT_ID.getSnapshot(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.deleteSnapshot(SNAPSHOT_ID)); } @Test public void testListSnapshots() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList snapshotList = ImmutableList.of( new Snapshot(compute, new SnapshotInfo.BuilderImpl(SNAPSHOT)), new Snapshot(compute, new SnapshotInfo.BuilderImpl(SNAPSHOT))); @@ -2175,15 +2191,15 @@ public void testListSnapshots() { EasyMock.expect(computeRpcMock.listSnapshots(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listSnapshots(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(snapshotList.toArray(), Iterables.toArray(page.values(), Snapshot.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(snapshotList.toArray(), Iterables.toArray(page.getValues(), Snapshot.class)); } @Test public void testListSnapshotsNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList snapshotList = ImmutableList.of( new Snapshot(compute, new SnapshotInfo.BuilderImpl(SNAPSHOT)), new Snapshot(compute, new SnapshotInfo.BuilderImpl(SNAPSHOT))); @@ -2199,30 +2215,31 @@ public void testListSnapshotsNextPage() { EasyMock.expect(computeRpcMock.listSnapshots(nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listSnapshots(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(snapshotList.toArray(), Iterables.toArray(page.values(), Snapshot.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextSnapshotList.toArray(), Iterables.toArray(page.values(), Snapshot.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(snapshotList.toArray(), Iterables.toArray(page.getValues(), Snapshot.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextSnapshotList.toArray(), + Iterables.toArray(page.getValues(), Snapshot.class)); } @Test public void testListEmptySnapshots() { - compute = options.service(); + compute = options.getService(); ImmutableList snapshots = ImmutableList.of(); ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, snapshots); EasyMock.expect(computeRpcMock.listSnapshots(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listSnapshots(); - assertNull(page.nextPageCursor()); - assertArrayEquals(snapshots.toArray(), Iterables.toArray(page.values(), Snapshot.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(snapshots.toArray(), Iterables.toArray(page.getValues(), Snapshot.class)); } @Test public void testListSnapshotsWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList snapshotList = ImmutableList.of( new Snapshot(compute, new SnapshotInfo.BuilderImpl(SNAPSHOT)), new Snapshot(compute, new SnapshotInfo.BuilderImpl(SNAPSHOT))); @@ -2232,8 +2249,8 @@ public void testListSnapshotsWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listSnapshots(SNAPSHOT_LIST_PAGE_SIZE, SNAPSHOT_LIST_PAGE_TOKEN, SNAPSHOT_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(snapshotList.toArray(), Iterables.toArray(page.values(), Snapshot.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(snapshotList.toArray(), Iterables.toArray(page.getValues(), Snapshot.class)); } @Test @@ -2241,7 +2258,7 @@ public void testCreateImage() { EasyMock.expect(computeRpcMock.createImage(IMAGE.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.create(IMAGE); assertEquals(globalOperation, operation); } @@ -2252,7 +2269,7 @@ public void testCreateImageWithOptions() { EasyMock.expect(computeRpcMock.createImage(eq(IMAGE.toPb()), capture(capturedOptions))) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.create(IMAGE, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -2269,7 +2286,7 @@ public void testGetImage() { computeRpcMock.getImage(IMAGE_ID.getProject(), IMAGE_ID.getImage(), EMPTY_RPC_OPTIONS)) .andReturn(IMAGE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Image image = compute.getImage(IMAGE_ID); assertEquals(new Image(compute, new ImageInfo.BuilderImpl(IMAGE)), image); } @@ -2280,7 +2297,7 @@ public void testGetImage_Null() { computeRpcMock.getImage(IMAGE_ID.getProject(), IMAGE_ID.getImage(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getImage(IMAGE_ID)); } @@ -2290,7 +2307,7 @@ public void testGetImageWithSelectedFields() { EasyMock.expect(computeRpcMock.getImage(eq(IMAGE_ID.getProject()), eq(IMAGE_ID.getImage()), capture(capturedOptions))).andReturn(IMAGE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Image image = compute.getImage(IMAGE_ID, IMAGE_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(IMAGE_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); @@ -2307,7 +2324,7 @@ public void testDeleteImage_Operation() { EasyMock.expect(computeRpcMock.deleteImage(IMAGE_ID.getProject(), IMAGE_ID.getImage(), EMPTY_RPC_OPTIONS)).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(globalOperation, compute.deleteImage(IMAGE_ID)); } @@ -2317,7 +2334,7 @@ public void testDeleteImageWithSelectedFields_Operation() { EasyMock.expect(computeRpcMock.deleteImage(eq(PROJECT), eq(IMAGE_ID.getImage()), capture(capturedOptions))).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.deleteImage(ImageId.of("image"), OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -2333,7 +2350,7 @@ public void testDeleteImage_Null() { EasyMock.expect(computeRpcMock.deleteImage(IMAGE_ID.getProject(), IMAGE_ID.getImage(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.deleteImage(IMAGE_ID)); } @@ -2342,7 +2359,7 @@ public void testDeprecateImage_Operation() { EasyMock.expect(computeRpcMock.deprecateImage(IMAGE_ID.getProject(), IMAGE_ID.getImage(), DEPRECATION_STATUS.toPb(), EMPTY_RPC_OPTIONS)).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(globalOperation, compute.deprecate(IMAGE_ID, DEPRECATION_STATUS)); } @@ -2352,7 +2369,7 @@ public void testDeprecateImageWithSelectedFields_Operation() { EasyMock.expect(computeRpcMock.deprecateImage(eq(PROJECT), eq(IMAGE_ID.getImage()), eq(DEPRECATION_STATUS.toPb()), capture(capturedOptions))).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.deprecate(ImageId.of("image"), DEPRECATION_STATUS, OPERATION_OPTION_FIELDS); String selector = @@ -2369,14 +2386,14 @@ public void testDeprecateImage_Null() { EasyMock.expect(computeRpcMock.deprecateImage(IMAGE_ID.getProject(), IMAGE_ID.getImage(), DEPRECATION_STATUS.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.deprecate(IMAGE_ID, DEPRECATION_STATUS)); } @Test public void testListImages() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList imageList = ImmutableList.of( new Image(compute, new ImageInfo.BuilderImpl(IMAGE)), new Image(compute, new ImageInfo.BuilderImpl(IMAGE))); @@ -2385,15 +2402,15 @@ public void testListImages() { EasyMock.expect(computeRpcMock.listImages(PROJECT, EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listImages(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(imageList.toArray(), Iterables.toArray(page.values(), Image.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(imageList.toArray(), Iterables.toArray(page.getValues(), Image.class)); } @Test public void testListImagesNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList imageList = ImmutableList.of( new Image(compute, new ImageInfo.BuilderImpl(IMAGE)), new Image(compute, new ImageInfo.BuilderImpl(IMAGE))); @@ -2409,17 +2426,17 @@ public void testListImagesNextPage() { EasyMock.expect(computeRpcMock.listImages(PROJECT, nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listImages(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(imageList.toArray(), Iterables.toArray(page.values(), Image.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextImageList.toArray(), Iterables.toArray(page.values(), Image.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(imageList.toArray(), Iterables.toArray(page.getValues(), Image.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextImageList.toArray(), Iterables.toArray(page.getValues(), Image.class)); } @Test public void testListImagesForProject() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList imageList = ImmutableList.of( new Image(compute, new ImageInfo.BuilderImpl(IMAGE)), new Image(compute, new ImageInfo.BuilderImpl(IMAGE))); @@ -2428,40 +2445,40 @@ public void testListImagesForProject() { EasyMock.expect(computeRpcMock.listImages("otherProject", EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listImages("otherProject"); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(imageList.toArray(), Iterables.toArray(page.values(), Image.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(imageList.toArray(), Iterables.toArray(page.getValues(), Image.class)); } @Test public void testListEmptyImages() { - compute = options.service(); + compute = options.getService(); ImmutableList images = ImmutableList.of(); ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, images); EasyMock.expect(computeRpcMock.listImages(PROJECT, EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listImages(); - assertNull(page.nextPageCursor()); - assertArrayEquals(images.toArray(), Iterables.toArray(page.values(), Image.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(images.toArray(), Iterables.toArray(page.getValues(), Image.class)); } @Test public void testListEmptyImagesForProject() { - compute = options.service(); + compute = options.getService(); ImmutableList images = ImmutableList.of(); ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, images); EasyMock.expect(computeRpcMock.listImages("otherProject", EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listImages("otherProject"); - assertNull(page.nextPageCursor()); - assertArrayEquals(images.toArray(), Iterables.toArray(page.values(), Image.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(images.toArray(), Iterables.toArray(page.getValues(), Image.class)); } @Test public void testListImagesWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList imageList = ImmutableList.of( new Image(compute, new ImageInfo.BuilderImpl(IMAGE)), new Image(compute, new ImageInfo.BuilderImpl(IMAGE))); @@ -2471,14 +2488,14 @@ public void testListImagesWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listImages(IMAGE_LIST_PAGE_SIZE, IMAGE_LIST_PAGE_TOKEN, IMAGE_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(imageList.toArray(), Iterables.toArray(page.values(), Image.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(imageList.toArray(), Iterables.toArray(page.getValues(), Image.class)); } @Test public void testListImagesForProjectWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList imageList = ImmutableList.of( new Image(compute, new ImageInfo.BuilderImpl(IMAGE)), new Image(compute, new ImageInfo.BuilderImpl(IMAGE))); @@ -2488,8 +2505,8 @@ public void testListImagesForProjectWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listImages("other", IMAGE_LIST_PAGE_SIZE, IMAGE_LIST_PAGE_TOKEN, IMAGE_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(imageList.toArray(), Iterables.toArray(page.values(), Image.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(imageList.toArray(), Iterables.toArray(page.getValues(), Image.class)); } @Test @@ -2497,7 +2514,7 @@ public void testGetDisk() { EasyMock.expect(computeRpcMock.getDisk(DISK_ID.getZone(), DISK_ID.getDisk(), EMPTY_RPC_OPTIONS)) .andReturn(DISK.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Disk disk = compute.getDisk(DISK_ID); assertEquals(new Disk(compute, new DiskInfo.BuilderImpl(DISK)), disk); } @@ -2507,7 +2524,7 @@ public void testGetDisk_Null() { EasyMock.expect(computeRpcMock.getDisk(DISK_ID.getZone(), DISK_ID.getDisk(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getDisk(DISK_ID)); } @@ -2517,7 +2534,7 @@ public void testGetDiskWithSelectedFields() { EasyMock.expect(computeRpcMock.getDisk(eq(DISK_ID.getZone()), eq(DISK_ID.getDisk()), capture(capturedOptions))).andReturn(DISK.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Disk disk = compute.getDisk(DISK_ID, DISK_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(DISK_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); @@ -2536,7 +2553,7 @@ public void testDeleteDisk_Operation() { DISK_ID.getZone(), DISK_ID.getDisk(), EMPTY_RPC_OPTIONS)) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.deleteDisk(DISK_ID)); } @@ -2546,7 +2563,7 @@ public void testDeleteDiskWithSelectedFields_Operation() { EasyMock.expect(computeRpcMock.deleteDisk(eq(DISK_ID.getZone()), eq(DISK_ID.getDisk()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.deleteDisk(DISK_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -2563,14 +2580,14 @@ public void testDeleteDisk_Null() { DISK_ID.getZone(), DISK_ID.getDisk(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.deleteDisk(DISK_ID)); } @Test public void testListDisks() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList diskList = ImmutableList.of( new Disk(compute, new DiskInfo.BuilderImpl(DISK)), new Disk(compute, new DiskInfo.BuilderImpl(DISK))); @@ -2580,15 +2597,15 @@ public void testListDisks() { .andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listDisks(DISK_ID.getZone()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(diskList.toArray(), Iterables.toArray(page.values(), Disk.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(diskList.toArray(), Iterables.toArray(page.getValues(), Disk.class)); } @Test public void testListDisksNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList diskList = ImmutableList.of( new Disk(compute, new DiskInfo.BuilderImpl(DISK)), new Disk(compute, new DiskInfo.BuilderImpl(DISK))); @@ -2604,16 +2621,16 @@ public void testListDisksNextPage() { EasyMock.expect(computeRpcMock.listDisks(DISK_ID.getZone(), nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listDisks(DISK_ID.getZone()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(diskList.toArray(), Iterables.toArray(page.values(), Disk.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextDiskList.toArray(), Iterables.toArray(page.values(), Disk.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(diskList.toArray(), Iterables.toArray(page.getValues(), Disk.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextDiskList.toArray(), Iterables.toArray(page.getValues(), Disk.class)); } @Test public void testListEmptyDisks() { - compute = options.service(); + compute = options.getService(); ImmutableList disks = ImmutableList.of(); ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, disks); @@ -2621,14 +2638,14 @@ public void testListEmptyDisks() { .andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listDisks(DISK_ID.getZone()); - assertNull(page.nextPageCursor()); - assertArrayEquals(disks.toArray(), Iterables.toArray(page.values(), Disk.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(disks.toArray(), Iterables.toArray(page.getValues(), Disk.class)); } @Test public void testListDisksWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList diskList = ImmutableList.of( new Disk(compute, new DiskInfo.BuilderImpl(DISK)), new Disk(compute, new DiskInfo.BuilderImpl(DISK))); @@ -2639,14 +2656,14 @@ public void testListDisksWithOptions() { EasyMock.replay(computeRpcMock); Page page =compute.listDisks( DISK_ID.getZone(), DISK_LIST_PAGE_SIZE, DISK_LIST_PAGE_TOKEN, DISK_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(diskList.toArray(), Iterables.toArray(page.values(), Disk.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(diskList.toArray(), Iterables.toArray(page.getValues(), Disk.class)); } @Test public void testAggregatedListDisks() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList diskList = ImmutableList.of( new Disk(compute, new DiskInfo.BuilderImpl(DISK)), new Disk(compute, new DiskInfo.BuilderImpl(DISK))); @@ -2655,15 +2672,15 @@ public void testAggregatedListDisks() { EasyMock.expect(computeRpcMock.listDisks(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listDisks(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(diskList.toArray(), Iterables.toArray(page.values(), Disk.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(diskList.toArray(), Iterables.toArray(page.getValues(), Disk.class)); } @Test public void testAggregatedListDisksNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList diskList = ImmutableList.of( new Disk(compute, new DiskInfo.BuilderImpl(DISK)), new Disk(compute, new DiskInfo.BuilderImpl(DISK))); @@ -2678,30 +2695,30 @@ public void testAggregatedListDisksNextPage() { EasyMock.expect(computeRpcMock.listDisks(nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listDisks(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(diskList.toArray(), Iterables.toArray(page.values(), Disk.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextDiskList.toArray(), Iterables.toArray(page.values(), Disk.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(diskList.toArray(), Iterables.toArray(page.getValues(), Disk.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextDiskList.toArray(), Iterables.toArray(page.getValues(), Disk.class)); } @Test public void testAggregatedListEmptyDisks() { - compute = options.service(); + compute = options.getService(); ImmutableList diskList = ImmutableList.of(); ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, diskList); EasyMock.expect(computeRpcMock.listDisks(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listDisks(); - assertNull(page.nextPageCursor()); - assertArrayEquals(diskList.toArray(), Iterables.toArray(page.values(), Disk.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(diskList.toArray(), Iterables.toArray(page.getValues(), Disk.class)); } @Test public void testAggregatedListDisksWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList diskList = ImmutableList.of( new Disk(compute, new DiskInfo.BuilderImpl(DISK)), new Disk(compute, new DiskInfo.BuilderImpl(DISK))); @@ -2711,8 +2728,8 @@ public void testAggregatedListDisksWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listDisks(DISK_AGGREGATED_LIST_PAGE_SIZE, DISK_AGGREGATED_LIST_PAGE_TOKEN, DISK_AGGREGATED_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(diskList.toArray(), Iterables.toArray(page.values(), Disk.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(diskList.toArray(), Iterables.toArray(page.getValues(), Disk.class)); } @Test @@ -2720,7 +2737,7 @@ public void testCreateDisk() { EasyMock.expect(computeRpcMock.createDisk(DISK_ID.getZone(), DISK.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); DiskId diskId = DiskId.of("zone", "disk"); DiskTypeId diskTypeId = DiskTypeId.of("zone", "diskType"); DiskInfo disk = DISK.toBuilder() @@ -2737,7 +2754,7 @@ public void testCreateDiskWithOptions() { EasyMock.expect(computeRpcMock.createDisk(eq(DISK_ID.getZone()), eq(DISK.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.create(DISK, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -2753,7 +2770,7 @@ public void testResizeDisk_Operation() { EasyMock.expect(computeRpcMock.resizeDisk(DISK_ID.getZone(), DISK_ID.getDisk(), 42L, EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.resize(DISK_ID, 42L)); } @@ -2763,7 +2780,7 @@ public void testResizeDiskWithSelectedFields_Operation() { EasyMock.expect(computeRpcMock.resizeDisk(eq(DISK_ID.getZone()), eq(DISK_ID.getDisk()), eq(42L), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.resize(DISK_ID, 42L, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -2779,7 +2796,7 @@ public void testResizeDisk_Null() { EasyMock.expect(computeRpcMock.resizeDisk(DISK_ID.getZone(), DISK_ID.getDisk(), 42L, EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.resize(DISK_ID, 42L)); } @@ -2789,7 +2806,7 @@ public void testGetSubnetwork() { SUBNETWORK_ID.getRegion(), SUBNETWORK_ID.getSubnetwork(), EMPTY_RPC_OPTIONS)) .andReturn(SUBNETWORK.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Subnetwork subnetwork = compute.getSubnetwork(SUBNETWORK_ID); assertEquals(new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK)), subnetwork); } @@ -2800,7 +2817,7 @@ public void testGetSubnetwork_Null() { SUBNETWORK_ID.getRegion(), SUBNETWORK_ID.getSubnetwork(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getSubnetwork(SUBNETWORK_ID)); } @@ -2810,7 +2827,7 @@ public void testGetSubnetworkWithSelectedFields() { EasyMock.expect(computeRpcMock.getSubnetwork(eq(SUBNETWORK_ID.getRegion()), eq(SUBNETWORK_ID.getSubnetwork()), capture(capturedOptions))).andReturn(SUBNETWORK.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Subnetwork subnetwork = compute.getSubnetwork(SUBNETWORK_ID, SUBNETWORK_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(SUBNETWORK_OPTION_FIELDS.getRpcOption()); @@ -2826,7 +2843,7 @@ public void testDeleteSubnetwork_Operation() { EasyMock.expect(computeRpcMock.deleteSubnetwork(SUBNETWORK_ID.getRegion(), SUBNETWORK_ID.getSubnetwork(), EMPTY_RPC_OPTIONS)).andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(regionOperation, compute.deleteSubnetwork(SUBNETWORK_ID)); } @@ -2837,7 +2854,7 @@ public void testDeleteSubnetworkWithSelectedFields_Operation() { eq(SUBNETWORK_ID.getSubnetwork()), capture(capturedOptions))) .andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.deleteSubnetwork(SUBNETWORK_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -2853,14 +2870,14 @@ public void testDeleteSubnetwork_Null() { EasyMock.expect(computeRpcMock.deleteSubnetwork(SUBNETWORK_ID.getRegion(), SUBNETWORK_ID.getSubnetwork(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.deleteSubnetwork(SUBNETWORK_ID)); } @Test public void testListSubnetworks() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList subnetworkList = ImmutableList.of( new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK)), new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK))); @@ -2871,15 +2888,16 @@ public void testListSubnetworks() { .andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listSubnetworks(SUBNETWORK_ID.getRegion()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(subnetworkList.toArray(), Iterables.toArray(page.values(), Subnetwork.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(subnetworkList.toArray(), + Iterables.toArray(page.getValues(), Subnetwork.class)); } @Test public void testListSubnetworksNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList subnetworkList = ImmutableList.of( new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK)), new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK))); @@ -2898,17 +2916,18 @@ public void testListSubnetworksNextPage() { .andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listSubnetworks(SUBNETWORK_ID.getRegion()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(subnetworkList.toArray(), Iterables.toArray(page.values(), Subnetwork.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(subnetworkList.toArray(), + Iterables.toArray(page.getValues(), Subnetwork.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); assertArrayEquals(nextSubnetworkList.toArray(), - Iterables.toArray(page.values(), Subnetwork.class)); + Iterables.toArray(page.getValues(), Subnetwork.class)); } @Test public void testListEmptySubnetworks() { - compute = options.service(); + compute = options.getService(); ImmutableList subnetworks = ImmutableList.of(); ComputeRpc.Tuple> result = @@ -2918,14 +2937,14 @@ public void testListEmptySubnetworks() { .andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listSubnetworks(SUBNETWORK_ID.getRegion()); - assertNull(page.nextPageCursor()); - assertArrayEquals(subnetworks.toArray(), Iterables.toArray(page.values(), Subnetwork.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(subnetworks.toArray(), Iterables.toArray(page.getValues(), Subnetwork.class)); } @Test public void testListSubnetworksWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList subnetworkList = ImmutableList.of( new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK)), new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK))); @@ -2938,14 +2957,15 @@ public void testListSubnetworksWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listSubnetworks(SUBNETWORK_ID.getRegion(), SUBNETWORK_LIST_PAGE_SIZE, SUBNETWORK_LIST_PAGE_TOKEN, SUBNETWORK_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(subnetworkList.toArray(), Iterables.toArray(page.values(), Subnetwork.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(subnetworkList.toArray(), + Iterables.toArray(page.getValues(), Subnetwork.class)); } @Test public void testAggregatedListSubnetworks() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList subnetworkList = ImmutableList.of( new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK)), new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK))); @@ -2955,15 +2975,16 @@ public void testAggregatedListSubnetworks() { EasyMock.expect(computeRpcMock.listSubnetworks(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listSubnetworks(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(subnetworkList.toArray(), Iterables.toArray(page.values(), Subnetwork.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(subnetworkList.toArray(), + Iterables.toArray(page.getValues(), Subnetwork.class)); } @Test public void testAggregatedListSubnetworksNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList subnetworkList = ImmutableList.of( new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK)), new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK))); @@ -2980,17 +3001,18 @@ public void testAggregatedListSubnetworksNextPage() { EasyMock.expect(computeRpcMock.listSubnetworks(nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listSubnetworks(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(subnetworkList.toArray(), Iterables.toArray(page.values(), Subnetwork.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(subnetworkList.toArray(), + Iterables.toArray(page.getValues(), Subnetwork.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); assertArrayEquals(nextSubnetworkList.toArray(), - Iterables.toArray(page.values(), Subnetwork.class)); + Iterables.toArray(page.getValues(), Subnetwork.class)); } @Test public void testAggregatedListEmptySubnetworks() { - compute = options.service(); + compute = options.getService(); ImmutableList subnetworks = ImmutableList.of(); ComputeRpc.Tuple> result = @@ -2999,14 +3021,14 @@ public void testAggregatedListEmptySubnetworks() { EasyMock.expect(computeRpcMock.listSubnetworks(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listSubnetworks(); - assertNull(page.nextPageCursor()); - assertArrayEquals(subnetworks.toArray(), Iterables.toArray(page.values(), Subnetwork.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(subnetworks.toArray(), Iterables.toArray(page.getValues(), Subnetwork.class)); } @Test public void testAggregatedListSubnetworksWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList subnetworkList = ImmutableList.of( new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK)), new Subnetwork(compute, new SubnetworkInfo.BuilderImpl(SUBNETWORK))); @@ -3017,8 +3039,9 @@ public void testAggregatedListSubnetworksWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listSubnetworks(SUBNETWORK_AGGREGATED_LIST_PAGE_SIZE, SUBNETWORK_AGGREGATED_LIST_PAGE_TOKEN, SUBNETWORK_AGGREGATED_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(subnetworkList.toArray(), Iterables.toArray(page.values(), Subnetwork.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(subnetworkList.toArray(), + Iterables.toArray(page.getValues(), Subnetwork.class)); } @Test @@ -3026,7 +3049,7 @@ public void testCreateSubnetwork() { EasyMock.expect(computeRpcMock.createSubnetwork(SUBNETWORK_ID.getRegion(), SUBNETWORK.toPb(), EMPTY_RPC_OPTIONS)).andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); SubnetworkId subnetworkId = SubnetworkId.of("region", "network"); NetworkId networkId = NetworkId.of("network"); SubnetworkInfo subnetwork = SubnetworkInfo.of(subnetworkId, networkId, "192.168.0.0/16"); @@ -3040,7 +3063,7 @@ public void testCreateSubnetworkWithOptions() { EasyMock.expect(computeRpcMock.createSubnetwork(eq(SUBNETWORK_ID.getRegion()), eq(SUBNETWORK.toPb()), capture(capturedOptions))).andReturn(regionOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.create(SUBNETWORK, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -3056,7 +3079,7 @@ public void testGetNetwork() { EasyMock.expect(computeRpcMock.getNetwork(NETWORK_ID.getNetwork(), EMPTY_RPC_OPTIONS)) .andReturn(NETWORK.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Network network = compute.getNetwork(NETWORK_ID.getNetwork()); assertEquals(new Network(compute, new NetworkInfo.BuilderImpl(NETWORK)), network); } @@ -3066,7 +3089,7 @@ public void testGetNetwork_Null() { EasyMock.expect(computeRpcMock.getNetwork(NETWORK_ID.getNetwork(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getNetwork(NETWORK_ID.getNetwork())); } @@ -3077,7 +3100,7 @@ public void testGetNetworkWithSelectedFields() { NETWORK_ID.getNetwork()), capture(capturedOptions))) .andReturn(NETWORK.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Network network = compute.getNetwork(NETWORK_ID.getNetwork(), NETWORK_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(NETWORK_OPTION_FIELDS.getRpcOption()); assertTrue(selector.contains("selfLink")); @@ -3094,7 +3117,7 @@ public void testDeleteNetwork_Operation() { EasyMock.expect(computeRpcMock.deleteNetwork(NETWORK_ID.getNetwork(), EMPTY_RPC_OPTIONS)) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(globalOperation, compute.deleteNetwork(NETWORK_ID)); } @@ -3104,7 +3127,7 @@ public void testDeleteNetworkWithSelectedFields_Operation() { EasyMock.expect(computeRpcMock.deleteNetwork(eq(NETWORK_ID.getNetwork()), capture(capturedOptions))).andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.deleteNetwork(NETWORK_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -3120,14 +3143,14 @@ public void testDeleteNetwork_Null() { EasyMock.expect(computeRpcMock.deleteNetwork(NETWORK_ID.getNetwork(), EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.deleteNetwork(NETWORK_ID)); } @Test public void testListNetworks() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList networkList = ImmutableList.of( new Network(compute, new NetworkInfo.BuilderImpl(NETWORK)), new Network(compute, new NetworkInfo.BuilderImpl(NETWORK))); @@ -3136,15 +3159,15 @@ public void testListNetworks() { EasyMock.expect(computeRpcMock.listNetworks(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listNetworks(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(networkList.toArray(), Iterables.toArray(page.values(), Network.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(networkList.toArray(), Iterables.toArray(page.getValues(), Network.class)); } @Test public void testListNetworksNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList networkList = ImmutableList.of( new Network(compute, new NetworkInfo.BuilderImpl(NETWORK)), new Network(compute, new NetworkInfo.BuilderImpl(NETWORK))); @@ -3160,30 +3183,31 @@ public void testListNetworksNextPage() { EasyMock.expect(computeRpcMock.listNetworks(nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listNetworks(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(networkList.toArray(), Iterables.toArray(page.values(), Network.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextNetworkList.toArray(), Iterables.toArray(page.values(), Network.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(networkList.toArray(), Iterables.toArray(page.getValues(), Network.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextNetworkList.toArray(), + Iterables.toArray(page.getValues(), Network.class)); } @Test public void testListEmptyNetworks() { - compute = options.service(); + compute = options.getService(); ImmutableList networks = ImmutableList.of(); ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, networks); EasyMock.expect(computeRpcMock.listNetworks(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listNetworks(); - assertNull(page.nextPageCursor()); - assertArrayEquals(networks.toArray(), Iterables.toArray(page.values(), Network.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(networks.toArray(), Iterables.toArray(page.getValues(), Network.class)); } @Test public void testListNetworksWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList networkList = ImmutableList.of( new Network(compute, new NetworkInfo.BuilderImpl(NETWORK)), new Network(compute, new NetworkInfo.BuilderImpl(NETWORK))); @@ -3193,8 +3217,8 @@ public void testListNetworksWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listNetworks(NETWORK_LIST_PAGE_SIZE, NETWORK_LIST_PAGE_TOKEN, NETWORK_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(networkList.toArray(), Iterables.toArray(page.values(), Network.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(networkList.toArray(), Iterables.toArray(page.getValues(), Network.class)); } @Test @@ -3202,7 +3226,7 @@ public void testCreateNetwork() { EasyMock.expect(computeRpcMock.createNetwork(NETWORK.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); NetworkInfo network = NetworkInfo.of(NetworkId.of("network"), StandardNetworkConfiguration.of("192.168.0.0/16")); Operation operation = compute.create(network); @@ -3215,7 +3239,7 @@ public void testCreateNetworkWithOptions() { EasyMock.expect(computeRpcMock.createNetwork(eq(NETWORK.toPb()), capture(capturedOptions))) .andReturn(globalOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.create(NETWORK, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -3231,7 +3255,7 @@ public void testGetInstance() { EasyMock.expect(computeRpcMock.getInstance(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(INSTANCE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Instance instance = compute.getInstance(INSTANCE_ID); assertEquals(new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE)), instance); } @@ -3241,7 +3265,7 @@ public void testGetInstance_Null() { EasyMock.expect(computeRpcMock.getInstance(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getInstance(INSTANCE_ID)); } @@ -3252,7 +3276,7 @@ public void testGetInstanceWithSelectedFields() { eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), capture(capturedOptions))) .andReturn(INSTANCE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Instance instance = compute.getInstance(INSTANCE_ID, INSTANCE_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(INSTANCE_OPTION_FIELDS.getRpcOption()); @@ -3268,7 +3292,7 @@ public void testDeleteInstance_Operation() { EasyMock.expect(computeRpcMock.deleteInstance(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.deleteInstance(INSTANCE_ID)); } @@ -3278,7 +3302,7 @@ public void testDeleteInstanceWithSelectedFields_Operation() { EasyMock.expect(computeRpcMock.deleteInstance(eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.deleteInstance(INSTANCE_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -3294,14 +3318,14 @@ public void testDeleteInstance_Null() { EasyMock.expect(computeRpcMock.deleteInstance(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.deleteInstance(INSTANCE_ID)); } @Test public void testListInstances() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList instanceList = ImmutableList.of( new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE)), new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE))); @@ -3311,15 +3335,15 @@ public void testListInstances() { .andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listInstances(INSTANCE_ID.getZone()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.values(), Instance.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.getValues(), Instance.class)); } @Test public void testListInstancesNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList instanceList = ImmutableList.of( new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE)), new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE))); @@ -3337,16 +3361,17 @@ public void testListInstancesNextPage() { .andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listInstances(INSTANCE_ID.getZone()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.values(), Instance.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextInstanceList.toArray(), Iterables.toArray(page.values(), Instance.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.getValues(), Instance.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextInstanceList.toArray(), + Iterables.toArray(page.getValues(), Instance.class)); } @Test public void testListEmptyInstances() { - compute = options.service(); + compute = options.getService(); ImmutableList instances = ImmutableList.of(); ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, instances); @@ -3354,14 +3379,14 @@ public void testListEmptyInstances() { .andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listInstances(INSTANCE_ID.getZone()); - assertNull(page.nextPageCursor()); - assertArrayEquals(instances.toArray(), Iterables.toArray(page.values(), Instance.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(instances.toArray(), Iterables.toArray(page.getValues(), Instance.class)); } @Test public void testListInstancesWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList instanceList = ImmutableList.of( new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE)), new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE))); @@ -3372,14 +3397,14 @@ public void testListInstancesWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listInstances(INSTANCE_ID.getZone(), INSTANCE_LIST_PAGE_SIZE, INSTANCE_LIST_PAGE_TOKEN, INSTANCE_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.values(), Instance.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.getValues(), Instance.class)); } @Test public void testAggregatedListInstances() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList instanceList = ImmutableList.of( new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE)), new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE))); @@ -3388,15 +3413,15 @@ public void testAggregatedListInstances() { EasyMock.expect(computeRpcMock.listInstances(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listInstances(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.values(), Instance.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.getValues(), Instance.class)); } @Test public void testAggregatedListInstancesNextPage() { String cursor = "cursor"; String nextCursor = "nextCursor"; - compute = options.service(); + compute = options.getService(); ImmutableList instanceList = ImmutableList.of( new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE)), new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE))); @@ -3412,16 +3437,17 @@ public void testAggregatedListInstancesNextPage() { EasyMock.expect(computeRpcMock.listInstances(nextOptions)).andReturn(nextResult); EasyMock.replay(computeRpcMock); Page page = compute.listInstances(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.values(), Instance.class)); - page = page.nextPage(); - assertEquals(nextCursor, page.nextPageCursor()); - assertArrayEquals(nextInstanceList.toArray(), Iterables.toArray(page.values(), Instance.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.getValues(), Instance.class)); + page = page.getNextPage(); + assertEquals(nextCursor, page.getNextPageCursor()); + assertArrayEquals(nextInstanceList.toArray(), + Iterables.toArray(page.getValues(), Instance.class)); } @Test public void testAggregatedListEmptyInstances() { - compute = options.service(); + compute = options.getService(); ImmutableList instanceList = ImmutableList.of(); ComputeRpc.Tuple> result = ComputeRpc.Tuple.>of(null, @@ -3429,14 +3455,14 @@ public void testAggregatedListEmptyInstances() { EasyMock.expect(computeRpcMock.listInstances(EMPTY_RPC_OPTIONS)).andReturn(result); EasyMock.replay(computeRpcMock); Page page = compute.listInstances(); - assertNull(page.nextPageCursor()); - assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.values(), Instance.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.getValues(), Instance.class)); } @Test public void testAggregatedListInstancesWithOptions() { String cursor = "cursor"; - compute = options.service(); + compute = options.getService(); ImmutableList instanceList = ImmutableList.of( new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE)), new Instance(compute, new InstanceInfo.BuilderImpl(INSTANCE))); @@ -3446,8 +3472,8 @@ public void testAggregatedListInstancesWithOptions() { EasyMock.replay(computeRpcMock); Page page = compute.listInstances(INSTANCE_AGGREGATED_LIST_PAGE_SIZE, INSTANCE_AGGREGATED_LIST_PAGE_TOKEN, INSTANCE_AGGREGATED_LIST_FILTER); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.values(), Instance.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(instanceList.toArray(), Iterables.toArray(page.getValues(), Instance.class)); } @Test @@ -3455,7 +3481,7 @@ public void testCreateInstance() { EasyMock.expect(computeRpcMock.createInstance(INSTANCE_ID.getZone(), INSTANCE.toPb(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); InstanceInfo instance = InstanceInfo.of(InstanceId.of("zone", "instance"), MachineTypeId.of("zone", "type"), ATTACHED_DISK, NetworkInterface.of(NetworkId.of("network"))); @@ -3469,7 +3495,7 @@ public void testCreateInstanceWithOptions() { EasyMock.expect(computeRpcMock.createInstance(eq(INSTANCE_ID.getZone()), eq(INSTANCE.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.create(INSTANCE, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -3487,7 +3513,7 @@ public void testAddAccessConfig_Operation() { "networkInterface", accessConfig.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.addAccessConfig(INSTANCE_ID, "networkInterface", accessConfig)); } @@ -3500,7 +3526,7 @@ public void testAddAccessConfigWithSelectedFields_Operation() { eq(INSTANCE_ID.getInstance()), eq("networkInterface"), eq(accessConfig.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.addAccessConfig(INSTANCE_ID, "networkInterface", accessConfig, OPERATION_OPTION_FIELDS); String selector = @@ -3518,7 +3544,7 @@ public void testAddAccessConfig_Null() { EasyMock.expect(computeRpcMock.addAccessConfig(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), "networkInterface", accessConfig.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.addAccessConfig(INSTANCE_ID, "networkInterface", accessConfig)); } @@ -3528,7 +3554,7 @@ public void testAttachDisk_Operation() { EasyMock.expect(computeRpcMock.attachDisk(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), attachedDisk.toPb(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.attachDisk(INSTANCE_ID, PERSISTENT_DISK_CONFIGURATION)); } @@ -3540,7 +3566,7 @@ public void testAttachDiskWithSelectedFields_Operation() { eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), eq(attachedDisk.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.attachDisk(INSTANCE_ID, PERSISTENT_DISK_CONFIGURATION, OPERATION_OPTION_FIELDS); String selector = @@ -3558,7 +3584,7 @@ public void testAttachDisk_Null() { EasyMock.expect(computeRpcMock.attachDisk(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), attachedDisk.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.attachDisk(INSTANCE_ID, PERSISTENT_DISK_CONFIGURATION)); } @@ -3568,7 +3594,7 @@ public void testAttachDiskName_Operation() { EasyMock.expect(computeRpcMock.attachDisk(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), attachedDisk.toPb(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.attachDisk(INSTANCE_ID, "dev0", PERSISTENT_DISK_CONFIGURATION)); } @@ -3581,7 +3607,7 @@ public void testAttachDiskNameWithSelectedFields_Operation() { eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), eq(attachedDisk.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.attachDisk(INSTANCE_ID, "dev0", PERSISTENT_DISK_CONFIGURATION, OPERATION_OPTION_FIELDS); String selector = @@ -3599,7 +3625,7 @@ public void testAttachDiskName_Null() { EasyMock.expect(computeRpcMock.attachDisk(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), attachedDisk.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.attachDisk(INSTANCE_ID, "dev0", PERSISTENT_DISK_CONFIGURATION)); } @@ -3609,7 +3635,7 @@ public void testDeleteAccessConfig_Operation() { INSTANCE_ID.getInstance(), "networkInterface", "accessConfig", EMPTY_RPC_OPTIONS)) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.deleteAccessConfig(INSTANCE_ID, "networkInterface", "accessConfig")); } @@ -3621,7 +3647,7 @@ public void testDeleteAccessConfigWithSelectedFields_Operation() { eq(INSTANCE_ID.getInstance()), eq("networkInterface"), eq("accessConfig"), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.deleteAccessConfig(INSTANCE_ID, "networkInterface", "accessConfig", OPERATION_OPTION_FIELDS); String selector = @@ -3639,7 +3665,7 @@ public void testDeleteAccessConfig_Null() { INSTANCE_ID.getInstance(), "networkInterface", "accessConfig", EMPTY_RPC_OPTIONS)) .andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.deleteAccessConfig(INSTANCE_ID, "networkInterface", "accessConfig")); } @@ -3648,7 +3674,7 @@ public void testDetachDisk_Operation() { EasyMock.expect(computeRpcMock.detachDisk(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), "device", EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.detachDisk(INSTANCE_ID, "device")); } @@ -3659,7 +3685,7 @@ public void testDetachDiskWithSelectedFields_Operation() { eq(INSTANCE_ID.getInstance()), eq("device"), capture(capturedOptions))) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.detachDisk(INSTANCE_ID, "device", OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -3675,7 +3701,7 @@ public void testDetachDisk_Null() { EasyMock.expect(computeRpcMock.detachDisk(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), "device", EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.detachDisk(INSTANCE_ID, "device")); } @@ -3685,7 +3711,7 @@ public void testSerialPortOutputFromPort() { EasyMock.expect(computeRpcMock.getSerialPortOutput(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), 2, EMPTY_RPC_OPTIONS)).andReturn(output); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(output, compute.getSerialPortOutput(INSTANCE_ID, 2)); } @@ -3695,7 +3721,7 @@ public void testSerialPortOutputDefault() { EasyMock.expect(computeRpcMock.getSerialPortOutput(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), null, EMPTY_RPC_OPTIONS)).andReturn(output); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(output, compute.getSerialPortOutput(INSTANCE_ID)); } @@ -3704,7 +3730,7 @@ public void testSerialPortOutputFromPort_Null() { EasyMock.expect(computeRpcMock.getSerialPortOutput(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), 2, EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getSerialPortOutput(INSTANCE_ID, 2)); } @@ -3713,7 +3739,7 @@ public void testSerialPortOutputDefault_Null() { EasyMock.expect(computeRpcMock.getSerialPortOutput(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), null, EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.getSerialPortOutput(INSTANCE_ID)); } @@ -3722,7 +3748,7 @@ public void testResetInstance_Operation() { EasyMock.expect(computeRpcMock.reset(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.reset(INSTANCE_ID)); } @@ -3732,7 +3758,7 @@ public void testResetInstanceWithSelectedFields_Operation() { EasyMock.expect(computeRpcMock.reset(eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.reset(INSTANCE_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -3748,7 +3774,7 @@ public void testResetInstance_Null() { EasyMock.expect(computeRpcMock.reset(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.reset(INSTANCE_ID)); } @@ -3758,7 +3784,7 @@ public void testSetDiskAutodelete_Operation() { INSTANCE_ID.getInstance(), "device", true, EMPTY_RPC_OPTIONS)) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.setDiskAutoDelete(INSTANCE_ID, "device", true)); } @@ -3769,7 +3795,7 @@ public void testSetDiskAutodeleteWithSelectedFields_Operation() { eq(INSTANCE_ID.getInstance()), eq("device"), eq(true), capture(capturedOptions))) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.setDiskAutoDelete(INSTANCE_ID, "device", true, OPERATION_OPTION_FIELDS); String selector = @@ -3786,7 +3812,7 @@ public void testSetDiskAutodelete_Null() { EasyMock.expect(computeRpcMock.setDiskAutoDelete(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), "device", false, EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.setDiskAutoDelete(INSTANCE_ID, "device", false)); } @@ -3795,7 +3821,7 @@ public void testSetMachineType_Operation() { EasyMock.expect(computeRpcMock.setMachineType(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), MACHINE_TYPE_ID.getSelfLink(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.setMachineType(INSTANCE_ID, MachineTypeId.of("zone", "type"))); } @@ -3807,7 +3833,7 @@ public void testSetMachineTypeWithOptions_Operation() { eq(INSTANCE_ID.getInstance()), eq(MACHINE_TYPE_ID.getSelfLink()), capture(capturedOptions))) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.setMachineType(INSTANCE_ID, MachineTypeId.of("zone", "type"), OPERATION_OPTION_FIELDS); String selector = @@ -3824,7 +3850,7 @@ public void testSetMachineType_Null() { EasyMock.expect(computeRpcMock.setMachineType(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), MACHINE_TYPE_ID.getSelfLink(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.setMachineType(INSTANCE_ID, MachineTypeId.of("zone", "type"))); } @@ -3837,7 +3863,7 @@ public void testSetMetadata_Operation() { EasyMock.expect(computeRpcMock.setMetadata(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), metadata.toPb(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.setMetadata(INSTANCE_ID, metadata)); } @@ -3852,7 +3878,7 @@ public void testSetMetadataWithOptions_Operation() { eq(INSTANCE_ID.getInstance()), eq(metadata.toPb()), capture(capturedOptions))) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.setMetadata(INSTANCE_ID, metadata, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -3872,7 +3898,7 @@ public void testSetMetadata_Null() { EasyMock.expect(computeRpcMock.setMetadata(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), metadata.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.setMetadata(INSTANCE_ID, metadata)); } @@ -3883,7 +3909,7 @@ public void testSetSchedulingOptions_Operation() { EasyMock.expect(computeRpcMock.setScheduling(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), schedulingOptions.toPb(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.setSchedulingOptions(INSTANCE_ID, schedulingOptions)); } @@ -3896,7 +3922,7 @@ public void testSetSchedulingOptionsWithOptions_Operation() { eq(INSTANCE_ID.getInstance()), eq(schedulingOptions.toPb()), capture(capturedOptions))) .andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.setSchedulingOptions(INSTANCE_ID, schedulingOptions, OPERATION_OPTION_FIELDS); String selector = @@ -3915,7 +3941,7 @@ public void testSetSchedulingOptions_Null() { EasyMock.expect(computeRpcMock.setScheduling(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), schedulingOptions.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.setSchedulingOptions(INSTANCE_ID, schedulingOptions)); } @@ -3925,7 +3951,7 @@ public void testTags_Operation() { EasyMock.expect(computeRpcMock.setTags(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), tags.toPb(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.setTags(INSTANCE_ID, tags)); } @@ -3936,7 +3962,7 @@ public void testSetTagsWithOptions_Operation() { EasyMock.expect(computeRpcMock.setTags(eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), eq(tags.toPb()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.setTags(INSTANCE_ID, tags, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -3953,7 +3979,7 @@ public void testSetTags_Null() { EasyMock.expect(computeRpcMock.setTags(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), tags.toPb(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.setTags(INSTANCE_ID, tags)); } @@ -3962,7 +3988,7 @@ public void testStartInstance_Operation() { EasyMock.expect(computeRpcMock.start(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.start(INSTANCE_ID)); } @@ -3972,7 +3998,7 @@ public void testStartInstanceWithSelectedFields_Operation() { EasyMock.expect(computeRpcMock.start(eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.start(INSTANCE_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -3988,7 +4014,7 @@ public void testStartInstance_Null() { EasyMock.expect(computeRpcMock.start(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.start(INSTANCE_ID)); } @@ -3997,7 +4023,7 @@ public void testStopInstance_Operation() { EasyMock.expect(computeRpcMock.stop(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertEquals(zoneOperation, compute.stop(INSTANCE_ID)); } @@ -4007,7 +4033,7 @@ public void testStopInstanceWithSelectedFields_Operation() { EasyMock.expect(computeRpcMock.stop(eq(INSTANCE_ID.getZone()), eq(INSTANCE_ID.getInstance()), capture(capturedOptions))).andReturn(zoneOperation.toPb()); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); Operation operation = compute.stop(INSTANCE_ID, OPERATION_OPTION_FIELDS); String selector = (String) capturedOptions.getValue().get(OPERATION_OPTION_FIELDS.getRpcOption()); @@ -4023,7 +4049,7 @@ public void testStopInstance_Null() { EasyMock.expect(computeRpcMock.stop(INSTANCE_ID.getZone(), INSTANCE_ID.getInstance(), EMPTY_RPC_OPTIONS)).andReturn(null); EasyMock.replay(computeRpcMock); - compute = options.service(); + compute = options.getService(); assertNull(compute.stop(INSTANCE_ID)); } @@ -4034,7 +4060,8 @@ public void testRetryableException() { .andThrow(new ComputeException(500, "InternalError")) .andReturn(DISK_TYPE.toPb()); EasyMock.replay(computeRpcMock); - compute = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); + compute = + options.toBuilder().setRetryParams(RetryParams.getDefaultInstance()).build().getService(); DiskType diskType = compute.getDiskType(DISK_TYPE_ID); assertEquals(DISK_TYPE, diskType); } @@ -4046,7 +4073,8 @@ public void testNonRetryableException() { DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andThrow(new ComputeException(501, exceptionMessage)); EasyMock.replay(computeRpcMock); - compute = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); + compute = + options.toBuilder().setRetryParams(RetryParams.getDefaultInstance()).build().getService(); thrown.expect(ComputeException.class); thrown.expectMessage(exceptionMessage); compute.getDiskType(DISK_TYPE_ID); @@ -4059,7 +4087,8 @@ public void testRuntimeException() { DISK_TYPE_ID.getZone(), DISK_TYPE_ID.getType(), EMPTY_RPC_OPTIONS)) .andThrow(new RuntimeException(exceptionMessage)); EasyMock.replay(computeRpcMock); - compute = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); + compute = + options.toBuilder().setRetryParams(RetryParams.getDefaultInstance()).build().getService(); thrown.expect(ComputeException.class); thrown.expectMessage(exceptionMessage); compute.getDiskType(DISK_TYPE_ID); diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTest.java index 24b214d6a5bd..1e7f7e0720dc 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/DiskTest.java @@ -80,7 +80,7 @@ public class DiskTest { private Disk imageDisk; private void initializeExpectedDisk(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); standardDisk = new Disk.Builder(serviceMockReturnsOptions, DISK_ID, DISK_CONFIGURATION) .setGeneratedId(GENERATED_ID) @@ -276,7 +276,7 @@ public void testToAndFromPb() { @Test public void testDeleteOperation() { initializeExpectedDisk(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "zone", "op")) .build(); @@ -289,7 +289,7 @@ public void testDeleteOperation() { @Test public void testDeleteNull() { initializeExpectedDisk(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.deleteDisk(DISK_ID)).andReturn(null); replay(compute); initializeDisk(); @@ -300,7 +300,7 @@ public void testDeleteNull() { public void testExists_True() throws Exception { initializeExpectedDisk(3); Compute.DiskOption[] expectedOptions = {Compute.DiskOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getDisk(DISK_ID, expectedOptions)).andReturn(imageDisk); replay(compute); initializeDisk(); @@ -312,7 +312,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { initializeExpectedDisk(3); Compute.DiskOption[] expectedOptions = {Compute.DiskOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getDisk(DISK_ID, expectedOptions)).andReturn(null); replay(compute); initializeDisk(); @@ -323,7 +323,7 @@ public void testExists_False() throws Exception { @Test public void testReload() throws Exception { initializeExpectedDisk(5); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getDisk(DISK_ID)).andReturn(imageDisk); replay(compute); initializeDisk(); @@ -335,7 +335,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedDisk(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getDisk(DISK_ID)).andReturn(null); replay(compute); initializeDisk(); @@ -346,7 +346,7 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedDisk(5); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getDisk(DISK_ID, Compute.DiskOption.fields())).andReturn(imageDisk); replay(compute); initializeDisk(); @@ -358,7 +358,7 @@ public void testReloadWithOptions() throws Exception { @Test public void testCreateSnapshot() { initializeExpectedDisk(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "zone", "op")) .build(); @@ -373,7 +373,7 @@ public void testCreateSnapshot() { @Test public void testCreateSnapshotWithDescription() { initializeExpectedDisk(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "zone", "op")) .build(); @@ -390,7 +390,7 @@ public void testCreateSnapshotWithDescription() { @Test public void testCreateSnapshotWithOptions() { initializeExpectedDisk(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "zone", "op")) .build(); @@ -406,7 +406,7 @@ public void testCreateSnapshotWithOptions() { @Test public void testCreateSnapshotWithDescriptionAndOptions() { initializeExpectedDisk(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "zone", "op")) .build(); @@ -418,13 +418,14 @@ public void testCreateSnapshotWithDescriptionAndOptions() { replay(compute); initializeDisk(); assertSame(operation, - disk.createSnapshot(SNAPSHOT.getSnapshot(), "description", Compute.OperationOption.fields())); + disk.createSnapshot(SNAPSHOT.getSnapshot(), "description", + Compute.OperationOption.fields())); } @Test public void testCreateImage() { initializeExpectedDisk(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(GlobalOperationId.of("project", "op")) .build(); @@ -439,7 +440,7 @@ public void testCreateImage() { @Test public void testCreateImageWithDescription() { initializeExpectedDisk(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(GlobalOperationId.of("project", "op")) .build(); @@ -456,7 +457,7 @@ public void testCreateImageWithDescription() { @Test public void testCreateImageWithOptions() { initializeExpectedDisk(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(GlobalOperationId.of("project", "op")) .build(); @@ -471,7 +472,7 @@ public void testCreateImageWithOptions() { @Test public void testCreateImageWithDescriptionAndOptions() { initializeExpectedDisk(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(GlobalOperationId.of("project", "op")) .build(); @@ -489,7 +490,7 @@ public void testCreateImageWithDescriptionAndOptions() { @Test public void testResizeOperation() { initializeExpectedDisk(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "zone", "op")) .build(); @@ -502,7 +503,7 @@ public void testResizeOperation() { @Test public void testResizeNull() { initializeExpectedDisk(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.resize(DISK_ID, 42L)).andReturn(null); replay(compute); initializeDisk(); @@ -511,7 +512,7 @@ public void testResizeNull() { public void compareDisk(Disk expected, Disk value) { assertEquals(expected, value); - assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getCompute().getOptions(), value.getCompute().getOptions()); assertEquals(expected.getDiskId(), value.getDiskId()); assertEquals(expected.getConfiguration(), value.getConfiguration()); assertEquals(expected.getGeneratedId(), value.getGeneratedId()); diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageTest.java index 2dc8694361c5..7de3b608cf35 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/ImageTest.java @@ -74,7 +74,7 @@ public class ImageTest { private Image storageImage; private void initializeExpectedImage(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); diskImage = new Image.Builder(serviceMockReturnsOptions, IMAGE_ID, DISK_CONFIGURATION) .setGeneratedId(GENERATED_ID) @@ -224,7 +224,7 @@ public void testToAndFromPb() { @Test public void testDeleteOperation() { initializeExpectedImage(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(GlobalOperationId.of("project", "op")) .build(); @@ -237,7 +237,7 @@ public void testDeleteOperation() { @Test public void testDeleteNull() { initializeExpectedImage(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.deleteImage(IMAGE_ID)).andReturn(null); replay(compute); initializeImage(); @@ -248,7 +248,7 @@ public void testDeleteNull() { public void testExists_True() throws Exception { initializeExpectedImage(2); Compute.ImageOption[] expectedOptions = {Compute.ImageOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getImage(IMAGE_ID, expectedOptions)).andReturn(diskImage); replay(compute); initializeImage(); @@ -260,7 +260,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { initializeExpectedImage(2); Compute.ImageOption[] expectedOptions = {Compute.ImageOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getImage(IMAGE_ID, expectedOptions)).andReturn(null); replay(compute); initializeImage(); @@ -271,7 +271,7 @@ public void testExists_False() throws Exception { @Test public void testReload() throws Exception { initializeExpectedImage(5); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getImage(IMAGE_ID)).andReturn(storageImage); replay(compute); initializeImage(); @@ -283,7 +283,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedImage(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getImage(IMAGE_ID)).andReturn(null); replay(compute); initializeImage(); @@ -294,7 +294,7 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedImage(5); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getImage(IMAGE_ID, Compute.ImageOption.fields())).andReturn(storageImage); replay(compute); initializeImage(); @@ -306,7 +306,7 @@ public void testReloadWithOptions() throws Exception { @Test public void testDeprecateImage() { initializeExpectedImage(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(GlobalOperationId.of("project", "op")) .build(); @@ -321,7 +321,7 @@ public void testDeprecateImage() { @Test public void testDeprecateNull() { initializeExpectedImage(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); DeprecationStatus status = DeprecationStatus.of(DeprecationStatus.Status.DEPRECATED, IMAGE_ID); expect(compute.deprecate(IMAGE_ID, status)).andReturn(null); @@ -332,7 +332,7 @@ public void testDeprecateNull() { public void compareImage(Image expected, Image value) { assertEquals(expected, value); - assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getCompute().getOptions(), value.getCompute().getOptions()); assertEquals(expected.getGeneratedId(), value.getGeneratedId()); assertEquals(expected.getImageId(), value.getImageId()); assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceTest.java index eacc72f12ab6..c7f61fd9d724 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/InstanceTest.java @@ -76,7 +76,7 @@ public class InstanceTest { private Instance expectedInstance; private void initializeExpectedInstance(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); expectedInstance = new Instance.Builder(serviceMockReturnsOptions, INSTANCE_ID, MACHINE_TYPE, ATTACHED_DISK, NETWORK_INTERFACE) @@ -227,7 +227,7 @@ public void testToAndFromPb() { @Test public void testDeleteOperation() { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -240,7 +240,7 @@ public void testDeleteOperation() { @Test public void testDeleteNull() { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.deleteInstance(INSTANCE_ID)).andReturn(null); replay(compute); initializeInstance(); @@ -251,7 +251,7 @@ public void testDeleteNull() { public void testExists_True() throws Exception { initializeExpectedInstance(1); Compute.InstanceOption[] expectedOptions = {Compute.InstanceOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getInstance(INSTANCE_ID, expectedOptions)).andReturn(expectedInstance); replay(compute); initializeInstance(); @@ -263,7 +263,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { initializeExpectedInstance(1); Compute.InstanceOption[] expectedOptions = {Compute.InstanceOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getInstance(INSTANCE_ID, expectedOptions)).andReturn(null); replay(compute); initializeInstance(); @@ -274,7 +274,7 @@ public void testExists_False() throws Exception { @Test public void testReload() throws Exception { initializeExpectedInstance(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getInstance(INSTANCE_ID)).andReturn(expectedInstance); replay(compute); initializeInstance(); @@ -286,7 +286,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getInstance(INSTANCE_ID)).andReturn(null); replay(compute); initializeInstance(); @@ -297,7 +297,7 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedInstance(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getInstance(INSTANCE_ID, Compute.InstanceOption.fields())).andReturn(expectedInstance); replay(compute); @@ -310,7 +310,7 @@ public void testReloadWithOptions() throws Exception { @Test public void testAddAccessConfig() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.of("192.168.1.1"); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) @@ -324,7 +324,7 @@ public void testAddAccessConfig() throws Exception { @Test public void testAddAccessConfig_Null() throws Exception { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.of("192.168.1.1"); expect(compute.addAccessConfig(INSTANCE_ID, "nic0", accessConfig)).andReturn(null); replay(compute); @@ -335,7 +335,7 @@ public void testAddAccessConfig_Null() throws Exception { @Test public void testAddAccessConfigWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); NetworkInterface.AccessConfig accessConfig = NetworkInterface.AccessConfig.of("192.168.1.1"); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) @@ -352,7 +352,7 @@ public void testAddAccessConfigWithOptions() throws Exception { @Test public void testAttachDisk() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); Operation operation = new Operation.Builder(serviceMockReturnsOptions) @@ -367,7 +367,7 @@ public void testAttachDisk() throws Exception { @Test public void testAttachDisk_Null() throws Exception { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); expect(compute.attachDisk(INSTANCE_ID, configuration)).andReturn(null); @@ -379,7 +379,7 @@ public void testAttachDisk_Null() throws Exception { @Test public void testAttachDiskWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); Operation operation = new Operation.Builder(serviceMockReturnsOptions) @@ -395,7 +395,7 @@ public void testAttachDiskWithOptions() throws Exception { @Test public void testAttachDiskName() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); Operation operation = new Operation.Builder(serviceMockReturnsOptions) @@ -410,7 +410,7 @@ public void testAttachDiskName() throws Exception { @Test public void testAttachDiskName_Null() throws Exception { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); expect(compute.attachDisk(INSTANCE_ID, "dev0", configuration)).andReturn(null); @@ -422,7 +422,7 @@ public void testAttachDiskName_Null() throws Exception { @Test public void testAttachDiskNameWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); Operation operation = new Operation.Builder(serviceMockReturnsOptions) @@ -439,7 +439,7 @@ public void testAttachDiskNameWithOptions() throws Exception { @Test public void testAttachDiskNameIndex() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); Operation operation = new Operation.Builder(serviceMockReturnsOptions) @@ -454,7 +454,7 @@ public void testAttachDiskNameIndex() throws Exception { @Test public void testAttachDiskNameIndex_Null() throws Exception { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); expect(compute.attachDisk(INSTANCE_ID, "dev0", configuration, 1)).andReturn(null); @@ -466,7 +466,7 @@ public void testAttachDiskNameIndex_Null() throws Exception { @Test public void testAttachDiskNameIndexWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); AttachedDisk.PersistentDiskConfiguration configuration = AttachedDisk.PersistentDiskConfiguration.of(DISK_ID); Operation operation = new Operation.Builder(serviceMockReturnsOptions) @@ -484,7 +484,7 @@ public void testAttachDiskNameIndexWithOptions() throws Exception { @Test public void testDeleteAccessConfig() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -497,7 +497,7 @@ public void testDeleteAccessConfig() throws Exception { @Test public void testDeleteAccessConfig_Null() throws Exception { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.deleteAccessConfig(INSTANCE_ID, "nic0", "NAT")).andReturn(null); replay(compute); initializeInstance(); @@ -507,7 +507,7 @@ public void testDeleteAccessConfig_Null() throws Exception { @Test public void testDeleteAccessConfigWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -523,7 +523,7 @@ public void testDeleteAccessConfigWithOptions() throws Exception { @Test public void testDetachDisk() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -536,7 +536,7 @@ public void testDetachDisk() throws Exception { @Test public void testDetachDisk_Null() throws Exception { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.detachDisk(INSTANCE_ID, "dev0")).andReturn(null); replay(compute); initializeInstance(); @@ -546,7 +546,7 @@ public void testDetachDisk_Null() throws Exception { @Test public void testDetachDiskWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -560,7 +560,7 @@ public void testDetachDiskWithOptions() throws Exception { @Test public void testGetSerialPortOutputWithNumber() throws Exception { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getSerialPortOutput(INSTANCE_ID, 2)).andReturn("output"); replay(compute); initializeInstance(); @@ -570,7 +570,7 @@ public void testGetSerialPortOutputWithNumber() throws Exception { @Test public void testGetSerialPortOutput() throws Exception { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getSerialPortOutput(INSTANCE_ID)).andReturn("output"); replay(compute); initializeInstance(); @@ -580,7 +580,7 @@ public void testGetSerialPortOutput() throws Exception { @Test public void testResetOperation() { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -593,7 +593,7 @@ public void testResetOperation() { @Test public void testResetNull() { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.reset(INSTANCE_ID)).andReturn(null); replay(compute); initializeInstance(); @@ -603,7 +603,7 @@ public void testResetNull() { @Test public void testSetDiskAutodelete() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -616,7 +616,7 @@ public void testSetDiskAutodelete() throws Exception { @Test public void testSetDiskAutodelete_Null() throws Exception { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.setDiskAutoDelete(INSTANCE_ID, "dev0", false)).andReturn(null); replay(compute); initializeInstance(); @@ -626,7 +626,7 @@ public void testSetDiskAutodelete_Null() throws Exception { @Test public void testSetDiskAutodeleteWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -641,7 +641,7 @@ public void testSetDiskAutodeleteWithOptions() throws Exception { @Test public void testSetMachineType() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -654,7 +654,7 @@ public void testSetMachineType() throws Exception { @Test public void testSetMachineType_Null() throws Exception { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.setMachineType(INSTANCE_ID, MACHINE_TYPE)).andReturn(null); replay(compute); initializeInstance(); @@ -664,7 +664,7 @@ public void testSetMachineType_Null() throws Exception { @Test public void testSetMachineTypeWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -678,7 +678,7 @@ public void testSetMachineTypeWithOptions() throws Exception { @Test public void testSetMetadata() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -692,7 +692,7 @@ public void testSetMetadata() throws Exception { @Test public void testSetMetadata_Null() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Metadata metadata = Metadata.newBuilder().add("k", "v").setFingerprint("fingerprint").build(); expect(compute.setMetadata(INSTANCE_ID, metadata)).andReturn(null); replay(compute); @@ -703,7 +703,7 @@ public void testSetMetadata_Null() throws Exception { @Test public void testSetMetadataWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -718,7 +718,7 @@ public void testSetMetadataWithOptions() throws Exception { @Test public void testSetMetadataFromMap() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -734,7 +734,7 @@ public void testSetMetadataFromMap() throws Exception { @Test public void testSetMetadataFromMap_Null() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Map metadataMap = ImmutableMap.of("k", "v"); Metadata metadata = Metadata.newBuilder().setValues(metadataMap).setFingerprint("fingerprint").build(); @@ -747,7 +747,7 @@ public void testSetMetadataFromMap_Null() throws Exception { @Test public void testSetMetadataFromMapWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -764,7 +764,7 @@ public void testSetMetadataFromMapWithOptions() throws Exception { @Test public void testSetSchedulingOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -779,7 +779,7 @@ public void testSetSchedulingOptions() throws Exception { @Test public void testSetSchedulingOptions_Null() throws Exception { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); SchedulingOptions schedulingOptions = SchedulingOptions.standard(true, SchedulingOptions.Maintenance.MIGRATE); expect(compute.setSchedulingOptions(INSTANCE_ID, schedulingOptions)).andReturn(null); @@ -791,7 +791,7 @@ public void testSetSchedulingOptions_Null() throws Exception { @Test public void testSetSchedulingOptionsWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -809,7 +809,7 @@ public void testSetSchedulingOptionsWithOptions() throws Exception { @Test public void testSetTags() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -823,7 +823,7 @@ public void testSetTags() throws Exception { @Test public void testSetTags_Null() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Tags tags = Tags.newBuilder().setValues("v1", "v2").setFingerprint("fingerprint").build(); expect(compute.setTags(INSTANCE_ID, tags)).andReturn(null); replay(compute); @@ -834,7 +834,7 @@ public void testSetTags_Null() throws Exception { @Test public void testSetTagsWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -849,7 +849,7 @@ public void testSetTagsWithOptions() throws Exception { @Test public void testSetTagsFromList() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -864,7 +864,7 @@ public void testSetTagsFromList() throws Exception { @Test public void testSetTagsFromList_Null() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); List tagList = ImmutableList.of("v1", "v2"); Tags tags = Tags.newBuilder().setValues(tagList).setFingerprint("fingerprint").build(); expect(compute.setTags(INSTANCE_ID, tags)).andReturn(null); @@ -876,7 +876,7 @@ public void testSetTagsFromList_Null() throws Exception { @Test public void testSetTagsFromListWithOptions() throws Exception { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -892,7 +892,7 @@ public void testSetTagsFromListWithOptions() throws Exception { @Test public void testStartOperation() { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -905,7 +905,7 @@ public void testStartOperation() { @Test public void testStartNull() { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.start(INSTANCE_ID)).andReturn(null); replay(compute); initializeInstance(); @@ -915,7 +915,7 @@ public void testStartNull() { @Test public void testStopOperation() { initializeExpectedInstance(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(ZoneOperationId.of("project", "op")) .build(); @@ -928,7 +928,7 @@ public void testStopOperation() { @Test public void testStopNull() { initializeExpectedInstance(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.stop(INSTANCE_ID)).andReturn(null); replay(compute); initializeInstance(); @@ -937,7 +937,7 @@ public void testStopNull() { public void compareInstance(Instance expected, Instance value) { assertEquals(expected, value); - assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getCompute().getOptions(), value.getCompute().getOptions()); assertEquals(expected.getGeneratedId(), value.getGeneratedId()); assertEquals(expected.getInstanceId(), value.getInstanceId()); assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkTest.java index 73ba3a346799..64eca576d48f 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/NetworkTest.java @@ -58,7 +58,7 @@ public class NetworkTest { private Network subnetNetwork; private void initializeExpectedNetwork(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); standardNetwork = new Network.Builder(serviceMockReturnsOptions, NETWORK_ID, NETWORK_CONFIGURATION) @@ -151,7 +151,7 @@ public void testToAndFromPb() { @Test public void testDeleteOperation() { initializeExpectedNetwork(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(GlobalOperationId.of("project", "op")) .build(); @@ -164,7 +164,7 @@ public void testDeleteOperation() { @Test public void testDeleteNull() { initializeExpectedNetwork(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.deleteNetwork(NETWORK_ID.getNetwork())).andReturn(null); replay(compute); initializeNetwork(); @@ -175,7 +175,7 @@ public void testDeleteNull() { public void testExists_True() throws Exception { initializeExpectedNetwork(2); Compute.NetworkOption[] expectedOptions = {Compute.NetworkOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getNetwork(NETWORK_ID.getNetwork(), expectedOptions)) .andReturn(standardNetwork); replay(compute); @@ -188,7 +188,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { initializeExpectedNetwork(2); Compute.NetworkOption[] expectedOptions = {Compute.NetworkOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getNetwork(NETWORK_ID.getNetwork(), expectedOptions)).andReturn(null); replay(compute); initializeNetwork(); @@ -199,7 +199,7 @@ public void testExists_False() throws Exception { @Test public void testReload() throws Exception { initializeExpectedNetwork(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getNetwork(NETWORK_ID.getNetwork())).andReturn(standardNetwork); replay(compute); initializeNetwork(); @@ -211,7 +211,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedNetwork(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getNetwork(NETWORK_ID.getNetwork())).andReturn(null); replay(compute); initializeNetwork(); @@ -222,7 +222,7 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedNetwork(4); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getNetwork(NETWORK_ID.getNetwork(), Compute.NetworkOption.fields())) .andReturn(standardNetwork); replay(compute); @@ -238,7 +238,7 @@ public void testCreateSubnetwork() throws Exception { Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(RegionOperationId.of(SUBNETWORK1.getRegionId(), "op")) .build(); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.create(SubnetworkInfo.of(SUBNETWORK1, NETWORK_ID, IP_RANGE))) .andReturn(operation); replay(compute); @@ -253,7 +253,7 @@ public void testCreateSubnetworkWithOptions() throws Exception { Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(RegionOperationId.of(SUBNETWORK1.getRegionId(), "op")) .build(); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.create(SubnetworkInfo.of(SUBNETWORK1, NETWORK_ID, IP_RANGE), Compute.OperationOption.fields())).andReturn(operation); replay(compute); @@ -265,7 +265,7 @@ public void testCreateSubnetworkWithOptions() throws Exception { public void compareNetwork(Network expected, Network value) { assertEquals(expected, value); - assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getCompute().getOptions(), value.getCompute().getOptions()); assertEquals(expected.getGeneratedId(), value.getGeneratedId()); assertEquals(expected.getNetworkId(), value.getNetworkId()); assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/OperationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/OperationTest.java index 1a499b0f67ea..1e6537727527 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/OperationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/OperationTest.java @@ -93,7 +93,7 @@ public class OperationTest { private Operation operation; private void initializeExpectedOperation(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); globalOperation = new Operation.Builder(serviceMockReturnsOptions) .getGeneratedId(GENERATED_ID) @@ -350,7 +350,7 @@ public void testToAndFromPb() { @Test public void testDeleteTrue() { initializeExpectedOperation(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.deleteOperation(GLOBAL_OPERATION_ID)).andReturn(true); replay(compute); initializeOperation(); @@ -361,7 +361,7 @@ public void testDeleteTrue() { @Test public void testDeleteFalse() { initializeExpectedOperation(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.deleteOperation(GLOBAL_OPERATION_ID)).andReturn(false); replay(compute); initializeOperation(); @@ -373,7 +373,7 @@ public void testDeleteFalse() { public void testExists_True() throws Exception { initializeExpectedOperation(3); Compute.OperationOption[] expectedOptions = {Compute.OperationOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(globalOperation); replay(compute); initializeOperation(); @@ -385,7 +385,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { initializeExpectedOperation(3); Compute.OperationOption[] expectedOptions = {Compute.OperationOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(null); replay(compute); initializeOperation(); @@ -398,7 +398,7 @@ public void testIsDone_True() throws Exception { initializeExpectedOperation(3); Compute.OperationOption[] expectedOptions = {Compute.OperationOption.fields(Compute.OperationField.STATUS)}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(globalOperation); replay(compute); initializeOperation(); @@ -411,7 +411,7 @@ public void testIsDone_False() throws Exception { initializeExpectedOperation(4); Compute.OperationOption[] expectedOptions = {Compute.OperationOption.fields(Compute.OperationField.STATUS)}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn( Operation.fromPb(serviceMockReturnsOptions, globalOperation.toPb().setStatus("PENDING"))); replay(compute); @@ -424,7 +424,7 @@ public void testIsDone_NotExists() throws Exception { initializeExpectedOperation(3); Compute.OperationOption[] expectedOptions = {Compute.OperationOption.fields(Compute.OperationField.STATUS)}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(null); replay(compute); initializeOperation(); @@ -439,8 +439,8 @@ public void testWaitFor() throws InterruptedException, TimeoutException { {Compute.OperationOption.fields(Compute.OperationField.STATUS)}; Operation successOperation = Operation.fromPb(serviceMockReturnsOptions, globalOperation.toPb().setError(null)); - expect(compute.options()).andReturn(mockOptions); - expect(mockOptions.clock()).andReturn(Clock.defaultClock()); + expect(compute.getOptions()).andReturn(mockOptions); + expect(mockOptions.getClock()).andReturn(Clock.defaultClock()); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(successOperation); expect(compute.getOperation(GLOBAL_OPERATION_ID)).andReturn(successOperation); replay(compute, mockOptions); @@ -454,8 +454,8 @@ public void testWaitFor_Null() throws InterruptedException, TimeoutException { initializeExpectedOperation(3); Compute.OperationOption[] expectedOptions = {Compute.OperationOption.fields(Compute.OperationField.STATUS)}; - expect(compute.options()).andReturn(mockOptions); - expect(mockOptions.clock()).andReturn(Clock.defaultClock()); + expect(compute.getOptions()).andReturn(mockOptions); + expect(mockOptions.getClock()).andReturn(Clock.defaultClock()); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(null); expect(compute.getOperation(GLOBAL_OPERATION_ID)).andReturn(null); replay(compute, mockOptions); @@ -476,8 +476,8 @@ public void testWaitForCheckingPeriod() throws InterruptedException, TimeoutExce globalOperation.toPb().setError(null).setStatus("RUNNING")); Operation completedOperation = Operation.fromPb(serviceMockReturnsOptions, globalOperation.toPb().setError(null)); - expect(compute.options()).andReturn(mockOptions); - expect(mockOptions.clock()).andReturn(Clock.defaultClock()); + expect(compute.getOptions()).andReturn(mockOptions); + expect(mockOptions.getClock()).andReturn(Clock.defaultClock()); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(runningOperation); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)) .andReturn(completedOperation); @@ -498,8 +498,8 @@ public void testWaitForCheckingPeriod_Null() throws InterruptedException, Timeou EasyMock.expectLastCall(); Operation runningOperation = Operation.fromPb(serviceMockReturnsOptions, globalOperation.toPb().setError(null).setStatus("RUNNING")); - expect(compute.options()).andReturn(mockOptions); - expect(mockOptions.clock()).andReturn(Clock.defaultClock()); + expect(compute.getOptions()).andReturn(mockOptions); + expect(mockOptions.getClock()).andReturn(Clock.defaultClock()); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(runningOperation); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(null); expect(compute.getOperation(GLOBAL_OPERATION_ID)).andReturn(null); @@ -523,8 +523,8 @@ public void testWaitForWithTimeout() throws InterruptedException, TimeoutExcepti expect(clock.millis()).andReturn(3L); Operation runningOperation = Operation.fromPb(serviceMockReturnsOptions, globalOperation.toPb().setError(null).setStatus("RUNNING")); - expect(compute.options()).andReturn(mockOptions); - expect(mockOptions.clock()).andReturn(clock); + expect(compute.getOptions()).andReturn(mockOptions); + expect(mockOptions.getClock()).andReturn(clock); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(runningOperation); expect(compute.getOperation(GLOBAL_OPERATION_ID, expectedOptions)).andReturn(runningOperation); replay(compute, timeUnit, clock, mockOptions); @@ -538,7 +538,7 @@ public void testWaitForWithTimeout() throws InterruptedException, TimeoutExcepti @Test public void testReload() throws Exception { initializeExpectedOperation(5); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getOperation(GLOBAL_OPERATION_ID)).andReturn(globalOperation); replay(compute); initializeOperation(); @@ -550,7 +550,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedOperation(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getOperation(GLOBAL_OPERATION_ID)).andReturn(null); replay(compute); initializeOperation(); @@ -561,7 +561,7 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedOperation(5); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getOperation(GLOBAL_OPERATION_ID, Compute.OperationOption.fields())) .andReturn(globalOperation); replay(compute); @@ -573,7 +573,7 @@ public void testReloadWithOptions() throws Exception { private void compareOperation(Operation expected, Operation value) { assertEquals(expected, value); - assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getCompute().getOptions(), value.getCompute().getOptions()); assertEquals(expected.getOperationId(), value.getOperationId()); assertEquals(expected.getClientOperationId(), value.getClientOperationId()); assertEquals(expected.getOperationType(), value.getOperationType()); diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java index ea3b7be1e1c9..eb9d52bfea5b 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SerializationTest.java @@ -32,7 +32,7 @@ public class SerializationTest extends BaseSerializationTest { - private static final Compute COMPUTE = ComputeOptions.builder().projectId("p").build().service(); + private static final Compute COMPUTE = ComputeOptions.newBuilder().setProjectId("p").build().getService(); private static final Long CREATION_TIMESTAMP = 1453293540000L; private static final String DESCRIPTION = "description"; private static final String VALID_DISK_SIZE = "10GB-10TB"; @@ -263,14 +263,14 @@ public class SerializationTest extends BaseSerializationTest { @Override protected Serializable[] serializableObjects() { - ComputeOptions options = ComputeOptions.builder() - .projectId("p1") - .authCredentials(AuthCredentials.createForAppEngine()) + ComputeOptions options = ComputeOptions.newBuilder() + .setProjectId("p1") + .setAuthCredentials(AuthCredentials.createForAppEngine()) .build(); ComputeOptions otherOptions = options.toBuilder() - .projectId("p2") - .retryParams(RetryParams.defaultInstance()) - .authCredentials(null) + .setProjectId("p2") + .setRetryParams(RetryParams.getDefaultInstance()) + .setAuthCredentials(null) .build(); return new Serializable[]{DISK_TYPE_ID, DISK_TYPE, MACHINE_TYPE_ID, MACHINE_TYPE, REGION_ID, REGION, ZONE_ID, ZONE, LICENSE_ID, LICENSE, DEPRECATION_STATUS, GLOBAL_OPERATION_ID, diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotTest.java index 22620bba8df1..a81fbcafbaa6 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SnapshotTest.java @@ -56,7 +56,7 @@ public class SnapshotTest { private Snapshot expectedSnapshot; private void initializeExpectedSnapshot(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); expectedSnapshot = new Snapshot.Builder(serviceMockReturnsOptions, SNAPSHOT_ID, SOURCE_DISK) .setGeneratedId(GENERATED_ID) @@ -188,7 +188,7 @@ public void testToAndFromPb() { @Test public void testDeleteOperation() { initializeExpectedSnapshot(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(GlobalOperationId.of("project", "op")) .build(); @@ -201,7 +201,7 @@ public void testDeleteOperation() { @Test public void testDeleteNull() { initializeExpectedSnapshot(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.deleteSnapshot(SNAPSHOT_ID)).andReturn(null); replay(compute); initializeSnapshot(); @@ -212,7 +212,7 @@ public void testDeleteNull() { public void testExists_True() throws Exception { initializeExpectedSnapshot(1); Compute.SnapshotOption[] expectedOptions = {Compute.SnapshotOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getSnapshot(SNAPSHOT_ID.getSnapshot(), expectedOptions)) .andReturn(expectedSnapshot); replay(compute); @@ -225,7 +225,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { initializeExpectedSnapshot(1); Compute.SnapshotOption[] expectedOptions = {Compute.SnapshotOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getSnapshot(SNAPSHOT_ID.getSnapshot(), expectedOptions)).andReturn(null); replay(compute); initializeSnapshot(); @@ -236,7 +236,7 @@ public void testExists_False() throws Exception { @Test public void testReload() throws Exception { initializeExpectedSnapshot(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getSnapshot(SNAPSHOT_ID.getSnapshot())).andReturn(expectedSnapshot); replay(compute); initializeSnapshot(); @@ -248,7 +248,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedSnapshot(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getSnapshot(SNAPSHOT_ID.getSnapshot())).andReturn(null); replay(compute); initializeSnapshot(); @@ -259,7 +259,7 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedSnapshot(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getSnapshot(SNAPSHOT_ID.getSnapshot(), Compute.SnapshotOption.fields())) .andReturn(expectedSnapshot); replay(compute); @@ -271,7 +271,7 @@ public void testReloadWithOptions() throws Exception { public void compareSnapshot(Snapshot expected, Snapshot value) { assertEquals(expected, value); - assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getCompute().getOptions(), value.getCompute().getOptions()); assertEquals(expected.getGeneratedId(), value.getGeneratedId()); assertEquals(expected.getSnapshotId(), value.getSnapshotId()); assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/StorageImageConfigurationTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/StorageImageConfigurationTest.java index 5d819ae58562..9ae845113996 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/StorageImageConfigurationTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/StorageImageConfigurationTest.java @@ -26,8 +26,10 @@ public class StorageImageConfigurationTest { private static final String SOURCE = "source"; - private static final ImageConfiguration.SourceType SOURCE_TYPE = ImageConfiguration.SourceType.RAW; - private static final StorageImageConfiguration.ContainerType CONTAINER_TYPE = StorageImageConfiguration.ContainerType.TAR; + private static final ImageConfiguration.SourceType SOURCE_TYPE = + ImageConfiguration.SourceType.RAW; + private static final StorageImageConfiguration.ContainerType CONTAINER_TYPE = + StorageImageConfiguration.ContainerType.TAR; private static final Long ARCHIVE_SIZE_BYTES = 42L; private static final String SHA1 = "sha1"; private static final StorageImageConfiguration CONFIGURATION = diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkTest.java index cb52b74522eb..5fef6ebcfe10 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/SubnetworkTest.java @@ -46,7 +46,7 @@ public class SubnetworkTest { private Subnetwork expectedSubnetwork; private void initializeExpectedSubnetwork(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); expectedSubnetwork = new Subnetwork.Builder(serviceMockReturnsOptions, SUBNETWORK_ID, NETWORK_ID, IP_RANGE) @@ -127,7 +127,7 @@ public void testToAndFromPb() { @Test public void testDeleteOperation() { initializeExpectedSubnetwork(2); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); Operation operation = new Operation.Builder(serviceMockReturnsOptions) .setOperationId(GlobalOperationId.of("project", "op")) .build(); @@ -140,7 +140,7 @@ public void testDeleteOperation() { @Test public void testDeleteNull() { initializeExpectedSubnetwork(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.deleteSubnetwork(SUBNETWORK_ID)).andReturn(null); replay(compute); initializeSubnetwork(); @@ -151,7 +151,7 @@ public void testDeleteNull() { public void testExists_True() throws Exception { initializeExpectedSubnetwork(1); Compute.SubnetworkOption[] expectedOptions = {Compute.SubnetworkOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getSubnetwork(SUBNETWORK_ID, expectedOptions)) .andReturn(expectedSubnetwork); replay(compute); @@ -164,7 +164,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { initializeExpectedSubnetwork(1); Compute.SubnetworkOption[] expectedOptions = {Compute.SubnetworkOption.fields()}; - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getSubnetwork(SUBNETWORK_ID, expectedOptions)).andReturn(null); replay(compute); initializeSubnetwork(); @@ -175,7 +175,7 @@ public void testExists_False() throws Exception { @Test public void testReload() throws Exception { initializeExpectedSubnetwork(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getSubnetwork(SUBNETWORK_ID)).andReturn(expectedSubnetwork); replay(compute); initializeSubnetwork(); @@ -187,7 +187,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedSubnetwork(1); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getSubnetwork(SUBNETWORK_ID)).andReturn(null); replay(compute); initializeSubnetwork(); @@ -198,7 +198,7 @@ public void testReloadNull() throws Exception { @Test public void testReloadWithOptions() throws Exception { initializeExpectedSubnetwork(3); - expect(compute.options()).andReturn(mockOptions); + expect(compute.getOptions()).andReturn(mockOptions); expect(compute.getSubnetwork(SUBNETWORK_ID, Compute.SubnetworkOption.fields())) .andReturn(expectedSubnetwork); replay(compute); @@ -210,7 +210,7 @@ public void testReloadWithOptions() throws Exception { public void compareSubnetwork(Subnetwork expected, Subnetwork value) { assertEquals(expected, value); - assertEquals(expected.getCompute().options(), value.getCompute().options()); + assertEquals(expected.getCompute().getOptions(), value.getCompute().getOptions()); assertEquals(expected.getGeneratedId(), value.getGeneratedId()); assertEquals(expected.getSubnetworkId(), value.getSubnetworkId()); assertEquals(expected.getCreationTimestamp(), value.getCreationTimestamp()); diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/it/ITComputeTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/it/ITComputeTest.java index 9f7d234cdccb..1d7eb4b293ed 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/it/ITComputeTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/it/ITComputeTest.java @@ -108,7 +108,7 @@ public class ITComputeTest { @BeforeClass public static void beforeClass() { RemoteComputeHelper computeHelper = RemoteComputeHelper.create(); - compute = computeHelper.getOptions().service(); + compute = computeHelper.getOptions().getService(); } @Test diff --git a/google-cloud-compute/src/test/java/com/google/cloud/compute/testing/RemoteComputeHelperTest.java b/google-cloud-compute/src/test/java/com/google/cloud/compute/testing/RemoteComputeHelperTest.java index 5e57e658d509..a859c49f9451 100644 --- a/google-cloud-compute/src/test/java/com/google/cloud/compute/testing/RemoteComputeHelperTest.java +++ b/google-cloud-compute/src/test/java/com/google/cloud/compute/testing/RemoteComputeHelperTest.java @@ -76,14 +76,14 @@ public void testCreateFromStream() { RemoteComputeHelper helper = RemoteComputeHelper.create(PROJECT_ID, JSON_KEY_STREAM); ComputeOptions options = helper.getOptions(); assertEquals(options, helper.options()); - assertEquals(PROJECT_ID, options.projectId()); - assertEquals(60000, options.connectTimeout()); - assertEquals(60000, options.readTimeout()); - assertEquals(10, options.retryParams().retryMaxAttempts()); - assertEquals(6, options.retryParams().retryMinAttempts()); - assertEquals(30000, options.retryParams().maxRetryDelayMillis()); - assertEquals(120000, options.retryParams().totalRetryPeriodMillis()); - assertEquals(250, options.retryParams().initialRetryDelayMillis()); + assertEquals(PROJECT_ID, options.getProjectId()); + assertEquals(60000, options.getConnectTimeout()); + assertEquals(60000, options.getReadTimeout()); + assertEquals(10, options.getRetryParams().getRetryMaxAttempts()); + assertEquals(6, options.getRetryParams().getRetryMinAttempts()); + assertEquals(30000, options.getRetryParams().getMaxRetryDelayMillis()); + assertEquals(120000, options.getRetryParams().getTotalRetryPeriodMillis()); + assertEquals(250, options.getRetryParams().getInitialRetryDelayMillis()); } @Test diff --git a/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemProvider.java b/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemProvider.java index dc95dacca4c1..727327d215fd 100644 --- a/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemProvider.java +++ b/google-cloud-contrib/google-cloud-nio/src/main/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemProvider.java @@ -149,9 +149,9 @@ private void initStorage() { return; } if (storageOptions == null) { - this.storage = StorageOptions.defaultInstance().service(); + this.storage = StorageOptions.getDefaultInstance().getService(); } else { - this.storage = storageOptions.service(); + this.storage = storageOptions.getService(); } } @@ -653,8 +653,8 @@ private IOException asIoException(StorageException oops) { // RPC API can only throw StorageException, but CloudStorageFileSystemProvider // can only throw IOException. Square peg, round hole. // TODO(#810): Research if other codes should be translated similarly. - if (oops.code() == 404) { - return new NoSuchFileException(oops.reason()); + if (oops.getCode() == 404) { + return new NoSuchFileException(oops.getReason()); } Throwable cause = oops.getCause(); diff --git a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileAttributeViewTest.java b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileAttributeViewTest.java index cfdae1330689..30bfe1244b82 100644 --- a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileAttributeViewTest.java +++ b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileAttributeViewTest.java @@ -51,7 +51,7 @@ public class CloudStorageFileAttributeViewTest { @Before public void before() { - CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.options()); + CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.getOptions()); path = Paths.get(URI.create("gs://red/water")); } diff --git a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileAttributesTest.java b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileAttributesTest.java index e0196b0d674f..9a6ca7339151 100644 --- a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileAttributesTest.java +++ b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileAttributesTest.java @@ -47,7 +47,7 @@ public class CloudStorageFileAttributesTest { @Before public void before() { - CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.options()); + CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.getOptions()); path = Paths.get(URI.create("gs://bucket/randompath")); dir = Paths.get(URI.create("gs://bucket/randompath/")); } diff --git a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemProviderTest.java b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemProviderTest.java index c66de5dabb9e..86e87d0e71e1 100644 --- a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemProviderTest.java +++ b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemProviderTest.java @@ -89,7 +89,7 @@ public class CloudStorageFileSystemProviderTest { @Before public void before() { - CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.options()); + CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.getOptions()); } @Test diff --git a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemTest.java b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemTest.java index 66d2c730696c..ec856447b96a 100644 --- a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemTest.java +++ b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageFileSystemTest.java @@ -56,7 +56,7 @@ public class CloudStorageFileSystemTest { @Before public void before() { - CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.options()); + CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.getOptions()); } @Test @@ -131,7 +131,7 @@ public void testNullness() throws IOException, NoSuchMethodException, SecurityEx new NullPointerTester() .ignore(CloudStorageFileSystem.class.getMethod("equals", Object.class)) .setDefault(CloudStorageConfiguration.class, CloudStorageConfiguration.DEFAULT) - .setDefault(StorageOptions.class, LocalStorageHelper.options()); + .setDefault(StorageOptions.class, LocalStorageHelper.getOptions()); tester.testAllPublicStaticMethods(CloudStorageFileSystem.class); tester.testAllPublicInstanceMethods(fs); } diff --git a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageLateInitializationTest.java b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageLateInitializationTest.java index c52db94df1e9..4c5c0387f14d 100644 --- a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageLateInitializationTest.java +++ b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageLateInitializationTest.java @@ -47,14 +47,14 @@ public class CloudStorageLateInitializationTest { public void before() { mockOptions = mock(StorageOptions.class); Storage mockStorage = mock(Storage.class); - when(mockOptions.service()).thenReturn(mockStorage); + when(mockOptions.getService()).thenReturn(mockStorage); CloudStorageFileSystemProvider.setStorageOptions(mockOptions); } @Test public void ctorDoesNotCreateStorage() { new CloudStorageFileSystemProvider(); - verify(mockOptions, never()).service(); + verify(mockOptions, never()).getService(); } @Test @@ -62,7 +62,7 @@ public void getPathCreatesStorageOnce() { CloudStorageFileSystemProvider provider = new CloudStorageFileSystemProvider(); provider.getPath(URI.create("gs://bucket1/wat")); provider.getPath(URI.create("gs://bucket2/wat")); - verify(mockOptions, times(1)).service(); + verify(mockOptions, times(1)).getService(); } @Test @@ -70,7 +70,7 @@ public void getFileSystemCreatesStorageOnce() { CloudStorageFileSystemProvider provider = new CloudStorageFileSystemProvider(); provider.getFileSystem(URI.create("gs://bucket1")); provider.getFileSystem(URI.create("gs://bucket2")); - verify(mockOptions, times(1)).service(); + verify(mockOptions, times(1)).getService(); } } diff --git a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageOptionsTest.java b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageOptionsTest.java index 28e23c4e85c9..d5dd2592c39c 100644 --- a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageOptionsTest.java +++ b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStorageOptionsTest.java @@ -41,7 +41,7 @@ public class CloudStorageOptionsTest { @Before public void before() { - CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.options()); + CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.getOptions()); } @Test diff --git a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStoragePathTest.java b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStoragePathTest.java index 6b38288cda2e..179baa453bb3 100644 --- a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStoragePathTest.java +++ b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/CloudStoragePathTest.java @@ -46,7 +46,7 @@ public class CloudStoragePathTest { @Before public void before() { - CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.options()); + CloudStorageFileSystemProvider.setStorageOptions(LocalStorageHelper.getOptions()); } @Test diff --git a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/LocalStorageHelper.java b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/LocalStorageHelper.java index a27a0df3a43a..481ebc79a6c9 100644 --- a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/LocalStorageHelper.java +++ b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/LocalStorageHelper.java @@ -22,7 +22,7 @@ /** * Utility to create an in-memory storage configuration for testing. Storage options can be - * obtained via the {@link #options()} method. Returned options will point to FakeStorageRpc. + * obtained via the {@link #getOptions()} method. Returned options will point to FakeStorageRpc. */ class LocalStorageHelper { @@ -33,11 +33,11 @@ class LocalStorageHelper { * Returns a {@link StorageOptions} that use the static FakeStorageRpc instance, and resets it * first so you start from a clean slate. That instance will throw if you pass it any option. */ - public static StorageOptions options() { + public static StorageOptions getOptions() { instance.reset(); - return StorageOptions.builder() - .projectId("dummy-project-for-testing") - .serviceRpcFactory( + return StorageOptions.newBuilder() + .setProjectId("dummy-project-for-testing") + .setServiceRpcFactory( new ServiceRpcFactory() { @Override public StorageRpc create(StorageOptions options) { @@ -52,9 +52,9 @@ public StorageRpc create(StorageOptions options) { * option. */ public static StorageOptions customOptions(final boolean throwIfOptions) { - return StorageOptions.builder() - .projectId("dummy-project-for-testing") - .serviceRpcFactory( + return StorageOptions.newBuilder() + .setProjectId("dummy-project-for-testing") + .setServiceRpcFactory( new ServiceRpcFactory() { @Override public StorageRpc create(StorageOptions options) { diff --git a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/it/ITGcsNio.java b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/it/ITGcsNio.java index e874dcfaced3..602b2d7ff03f 100644 --- a/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/it/ITGcsNio.java +++ b/google-cloud-contrib/google-cloud-nio/src/test/java/com/google/cloud/storage/contrib/nio/it/ITGcsNio.java @@ -99,7 +99,7 @@ public static void beforeClass() throws IOException { // loads the credentials from local disk as par README RemoteStorageHelper gcsHelper = RemoteStorageHelper.create(); storageOptions = gcsHelper.getOptions(); - storage = storageOptions.service(); + storage = storageOptions.getService(); // create and populate test bucket storage.create(BucketInfo.of(BUCKET)); fillFile(storage, SML_FILE, SML_SIZE); diff --git a/google-cloud-core/src/main/java/com/google/cloud/AsyncPage.java b/google-cloud-core/src/main/java/com/google/cloud/AsyncPage.java index 8d7ff026e70d..ab836e6e4b89 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/AsyncPage.java +++ b/google-cloud-core/src/main/java/com/google/cloud/AsyncPage.java @@ -34,10 +34,10 @@ *
     {@code
      * AsyncPage page = ...; // get a AsyncPage instance
      * while (page != null) {
    - *   for (T value : page.values()) {
    + *   for (T value : page.getValues()) {
      *     // do something with value
      *   }
    - *   page = page.nextPageAsync().get();
    + *   page = page.getNextPageAsync().get();
      * }}
    * * @param the value type that the page holds @@ -48,5 +48,12 @@ public interface AsyncPage extends Page { * Returns a {@link Future} object for the next page. {@link Future#get()} returns {@code null} if * the last page has been reached. */ + @Deprecated Future> nextPageAsync(); + + /** + * Returns a {@link Future} object for the next page. {@link Future#get()} returns {@code null} if + * the last page has been reached. + */ + Future> getNextPageAsync(); } diff --git a/google-cloud-core/src/main/java/com/google/cloud/AsyncPageImpl.java b/google-cloud-core/src/main/java/com/google/cloud/AsyncPageImpl.java index 706316e362cd..c5734408d4bf 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/AsyncPageImpl.java +++ b/google-cloud-core/src/main/java/com/google/cloud/AsyncPageImpl.java @@ -41,7 +41,10 @@ public class AsyncPageImpl extends PageImpl implements AsyncPage { * @param the value type that the page holds */ public interface NextPageFetcher extends Serializable { + @Deprecated Future> nextPage(); + + Future> getNextPage(); } private static class SyncNextPageFetcher implements PageImpl.NextPageFetcher { @@ -56,9 +59,14 @@ private SyncNextPageFetcher(NextPageFetcher asyncPageFetcher) { @Override public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { try { return asyncPageFetcher != null - ? Uninterruptibles.getUninterruptibly(asyncPageFetcher.nextPage()) : null; + ? Uninterruptibles.getUninterruptibly(asyncPageFetcher.getNextPage()) : null; } catch (ExecutionException ex) { throw Throwables.propagate(ex.getCause()); } @@ -74,10 +82,16 @@ public AsyncPageImpl(NextPageFetcher asyncPageFetcher, String cursor, Iterabl } @Override + @Deprecated public Future> nextPageAsync() { - if (nextPageCursor() == null || asyncPageFetcher == null) { + return getNextPageAsync(); + } + + @Override + public Future> getNextPageAsync() { + if (getNextPageCursor() == null || asyncPageFetcher == null) { return Futures.immediateCheckedFuture(null); } - return asyncPageFetcher.nextPage(); + return asyncPageFetcher.getNextPage(); } } diff --git a/google-cloud-core/src/main/java/com/google/cloud/AuthCredentials.java b/google-cloud-core/src/main/java/com/google/cloud/AuthCredentials.java index 792831bb9edc..257e801c6f3b 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/AuthCredentials.java +++ b/google-cloud-core/src/main/java/com/google/cloud/AuthCredentials.java @@ -130,6 +130,11 @@ public GoogleCredentials createScoped(Collection scopes) { @Override public String account() { + return getAccount(); + } + + @Override + public String getAccount() { return account; } @@ -166,7 +171,13 @@ public boolean equals(Object obj) { } @Override + @Deprecated public AppEngineCredentials credentials() { + return getCredentials(); + } + + @Override + public AppEngineCredentials getCredentials() { if (credentials == null) { credentials = new AppEngineCredentials(); } @@ -179,13 +190,19 @@ public RestorableState capture() { } @Override + @Deprecated public String account() { - return credentials().account(); + return getAccount(); + } + + @Override + public String getAccount() { + return getCredentials().getAccount(); } @Override public byte[] sign(byte[] toSign) { - return credentials().sign(toSign); + return getCredentials().sign(toSign); } } @@ -247,19 +264,39 @@ public boolean equals(Object obj) { } @Override + @Deprecated public ServiceAccountCredentials credentials() { + return getCredentials(); + } + + @Override + public ServiceAccountCredentials getCredentials() { return credentials; } @Override + @Deprecated public String account() { return account; } + @Override + public String getAccount() { + return account; + } + /** * Returns the private key associated with the service account credentials. */ + @Deprecated public PrivateKey privateKey() { + return getPrivateKey(); + } + + /** + * Returns the private key associated with the service account credentials. + */ + public PrivateKey getPrivateKey() { return privateKey; } @@ -267,7 +304,7 @@ public PrivateKey privateKey() { public byte[] sign(byte[] toSign) { try { Signature signer = Signature.getInstance("SHA256withRSA"); - signer.initSign(privateKey()); + signer.initSign(getPrivateKey()); signer.update(toSign); return signer.sign(); } catch (NoSuchAlgorithmException | InvalidKeyException | SignatureException ex) { @@ -331,7 +368,13 @@ public boolean equals(Object obj) { } @Override + @Deprecated public GoogleCredentials credentials() { + return getCredentials(); + } + + @Override + public GoogleCredentials getCredentials() { return googleCredentials; } @@ -392,7 +435,13 @@ public boolean equals(Object obj) { } @Override + @Deprecated public GoogleCredentials credentials() { + return getCredentials(); + } + + @Override + public GoogleCredentials getCredentials() { return credentials; } @@ -436,7 +485,13 @@ public boolean equals(Object obj) { private NoAuthCredentials() {} @Override + @Deprecated public GoogleCredentials credentials() { + return getCredentials(); + } + + @Override + public GoogleCredentials getCredentials() { return null; } @@ -446,8 +501,11 @@ public RestorableState capture() { } } + @Deprecated public abstract GoogleCredentials credentials(); + public abstract GoogleCredentials getCredentials(); + public static AuthCredentials createForAppEngine() { return AppEngineAuthCredentials.INSTANCE; } diff --git a/google-cloud-core/src/main/java/com/google/cloud/BaseService.java b/google-cloud-core/src/main/java/com/google/cloud/BaseService.java index d0476b66c29c..f221ade32482 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/BaseService.java +++ b/google-cloud-core/src/main/java/com/google/cloud/BaseService.java @@ -38,15 +38,15 @@ public RetryResult afterEval(Exception exception, RetryResult retryResult) { @Override public RetryResult beforeEval(Exception exception) { if (exception instanceof BaseServiceException) { - boolean retriable = ((BaseServiceException) exception).retryable(); + boolean retriable = ((BaseServiceException) exception).isRetryable(); return retriable ? Interceptor.RetryResult.RETRY : Interceptor.RetryResult.NO_RETRY; } return Interceptor.RetryResult.CONTINUE_EVALUATION; } }; - public static final ExceptionHandler EXCEPTION_HANDLER = ExceptionHandler.builder() + public static final ExceptionHandler EXCEPTION_HANDLER = ExceptionHandler.newBuilder() .abortOn(RuntimeException.class) - .interceptor(EXCEPTION_HANDLER_INTERCEPTOR) + .addInterceptors(EXCEPTION_HANDLER_INTERCEPTOR) .build(); private final OptionsT options; @@ -56,7 +56,13 @@ protected BaseService(OptionsT options) { } @Override + @Deprecated public OptionsT options() { return options; } + + @Override + public OptionsT getOptions() { + return options; + } } diff --git a/google-cloud-core/src/main/java/com/google/cloud/BaseServiceException.java b/google-cloud-core/src/main/java/com/google/cloud/BaseServiceException.java index c22fcfd44a3a..d892d85b6b2b 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/BaseServiceException.java +++ b/google-cloud-core/src/main/java/com/google/cloud/BaseServiceException.java @@ -65,7 +65,15 @@ public Error(Integer code, String reason, boolean rejected) { /** * Returns the code associated with this exception. */ + @Deprecated public Integer code() { + return getCode(); + } + + /** + * Returns the code associated with this exception. + */ + public Integer getCode() { return code; } @@ -74,22 +82,41 @@ public Integer code() { * server. For instance, if the server returns a rate limit exceeded error, it certainly did not * process the request and this method will return {@code true}. */ + @Deprecated public boolean rejected() { + return isRejected(); + } + + /** + * Returns true if the error indicates that the API call was certainly not accepted by the + * server. For instance, if the server returns a rate limit exceeded error, it certainly did not + * process the request and this method will return {@code true}. + */ + public boolean isRejected() { return rejected; } /** * Returns the reason that caused the exception. */ + @Deprecated public String reason() { + return getReason(); + } + + /** + * Returns the reason that caused the exception. + */ + public String getReason() { return reason; } boolean isRetryable(boolean idempotent, Set retryableErrors) { for (Error retryableError : retryableErrors) { - if ((retryableError.code() == null || retryableError.code().equals(this.code())) - && (retryableError.reason() == null || retryableError.reason().equals(this.reason()))) { - return idempotent || retryableError.rejected(); + if ((retryableError.getCode() == null || retryableError.getCode().equals(this.getCode())) + && (retryableError.getReason() == null + || retryableError.getReason().equals(this.getReason()))) { + return idempotent || retryableError.isRejected(); } } return false; @@ -179,12 +206,17 @@ public BaseServiceException(ApiException apiException, boolean idempotent) { this.debugInfo = null; } + @Deprecated protected Set retryableErrors() { + return getRetryableErrors(); + } + + protected Set getRetryableErrors() { return Collections.emptySet(); } protected boolean isRetryable(boolean idempotent, Error error) { - return error.isRetryable(idempotent, retryableErrors()); + return error.isRetryable(idempotent, getRetryableErrors()); } protected boolean isRetryable(boolean idempotent, IOException exception) { @@ -197,28 +229,60 @@ protected boolean isRetryable(boolean idempotent, IOException exception) { /** * Returns the code associated with this exception. */ + @Deprecated public int code() { + return getCode(); + } + + /** + * Returns the code associated with this exception. + */ + public int getCode() { return code; } /** * Returns the reason that caused the exception. */ + @Deprecated public String reason() { + return getReason(); + } + + /** + * Returns the reason that caused the exception. + */ + public String getReason() { return reason; } /** * Returns {@code true} when it is safe to retry the operation that caused this exception. */ + @Deprecated public boolean retryable() { + return isRetryable(); + } + + /** + * Returns {@code true} when it is safe to retry the operation that caused this exception. + */ + public boolean isRetryable() { return retryable; } /** * Returns {@code true} when the operation that caused this exception had no side effects. */ + @Deprecated public boolean idempotent() { + return isIdempotent(); + } + + /** + * Returns {@code true} when the operation that caused this exception had no side effects. + */ + public boolean isIdempotent() { return idempotent; } @@ -226,11 +290,25 @@ public boolean idempotent() { * Returns the service location where the error causing the exception occurred. Returns {@code * null} if not available. */ + @Deprecated public String location() { + return getLocation(); + } + + /** + * Returns the service location where the error causing the exception occurred. Returns {@code + * null} if not available. + */ + public String getLocation() { return location; } + @Deprecated protected String debugInfo() { + return getDebugInfo(); + } + + protected String getDebugInfo() { return debugInfo; } diff --git a/google-cloud-core/src/main/java/com/google/cloud/BaseWriteChannel.java b/google-cloud-core/src/main/java/com/google/cloud/BaseWriteChannel.java index 038ef8c362de..aaef34149f69 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/BaseWriteChannel.java +++ b/google-cloud-core/src/main/java/com/google/cloud/BaseWriteChannel.java @@ -16,7 +16,6 @@ package com.google.cloud; -import com.google.cloud.BaseWriteChannel.BaseState; import com.google.common.base.MoreObjects; import java.io.IOException; @@ -46,56 +45,107 @@ public abstract class BaseWriteChannel< private byte[] buffer = new byte[0]; private int limit; private boolean isOpen = true; - private int chunkSize = defaultChunkSize(); + private int chunkSize = getDefaultChunkSize(); + @Deprecated protected int minChunkSize() { + return getMinChunkSize(); + } + + protected int getMinChunkSize() { return MIN_CHUNK_SIZE; } + @Deprecated protected int defaultChunkSize() { + return getDefaultChunkSize(); + } + + protected int getDefaultChunkSize() { return DEFAULT_CHUNK_SIZE; } /** - * Writes {@code length} bytes of {@link #buffer()} to the {@link #uploadId()} URL. + * Writes {@code length} bytes of {@link #getBuffer()} to the {@link #getUploadId()} URL. * - * @param length the number of bytes to write from {@link #buffer()} + * @param length the number of bytes to write from {@link #getBuffer()} * @param last if {@code true} the resumable session is closed */ protected abstract void flushBuffer(int length, boolean last); + @Deprecated protected ServiceOptionsT options() { return options; } + protected ServiceOptionsT getOptions() { + return options; + } + + @Deprecated protected EntityT entity() { + return getEntity(); + } + + protected EntityT getEntity() { return entity; } + @Deprecated protected String uploadId() { + return getUploadId(); + } + + protected String getUploadId() { return uploadId; } + @Deprecated protected int position() { + return getPosition(); + } + + protected int getPosition() { return position; } + @Deprecated protected byte[] buffer() { + return getBuffer(); + } + + protected byte[] getBuffer() { return buffer; } + @Deprecated protected int limit() { + return getLimit(); + } + + protected int getLimit() { return limit; } + @Deprecated protected int chunkSize() { + return getChunkSize(); + } + + protected int getChunkSize() { return chunkSize; } @Override + @Deprecated public final void chunkSize(int chunkSize) { - chunkSize = (chunkSize / minChunkSize()) * minChunkSize(); - this.chunkSize = Math.max(minChunkSize(), chunkSize); + setChunkSize(chunkSize); + } + + @Override + public final void setChunkSize(int chunkSize) { + chunkSize = (chunkSize / getMinChunkSize()) * getMinChunkSize(); + this.chunkSize = Math.max(getMinChunkSize(), chunkSize); } protected BaseWriteChannel(ServiceOptionsT options, EntityT entity, String uploadId) { @@ -106,7 +156,7 @@ protected BaseWriteChannel(ServiceOptionsT options, EntityT entity, String uploa private void flush() { if (limit >= chunkSize) { - final int length = limit - limit % minChunkSize(); + final int length = limit - limit % getMinChunkSize(); flushBuffer(length, false); position += length; limit -= length; @@ -166,10 +216,10 @@ public RestorableState capture() { bufferToSave = Arrays.copyOf(buffer, limit); } return stateBuilder() - .position(position) - .buffer(bufferToSave) - .isOpen(isOpen) - .chunkSize(chunkSize) + .setPosition(position) + .setBuffer(bufferToSave) + .setIsOpen(isOpen) + .setChunkSize(chunkSize) .build(); } @@ -235,22 +285,42 @@ protected Builder(ServiceOptionsT options, EntityT entity, String uploadId) { this.uploadId = uploadId; } + @Deprecated public Builder position(int position) { + return setPosition(position); + } + + public Builder setPosition(int position) { this.position = position; return this; } + @Deprecated public Builder buffer(byte[] buffer) { + return setBuffer(buffer); + } + + public Builder setBuffer(byte[] buffer) { this.buffer = buffer; return this; } + @Deprecated public Builder isOpen(boolean isOpen) { + return setIsOpen(isOpen); + } + + public Builder setIsOpen(boolean isOpen) { this.isOpen = isOpen; return this; } + @Deprecated public Builder chunkSize(int chunkSize) { + return setChunkSize(chunkSize); + } + + public Builder setChunkSize(int chunkSize) { this.chunkSize = chunkSize; return this; } diff --git a/google-cloud-core/src/main/java/com/google/cloud/ByteArray.java b/google-cloud-core/src/main/java/com/google/cloud/ByteArray.java index 3a23a17ba4d7..0c719fb18d98 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/ByteArray.java +++ b/google-cloud-core/src/main/java/com/google/cloud/ByteArray.java @@ -41,7 +41,7 @@ protected ByteArray(ByteString byteString) { } protected ByteArray(ByteArray byteArray) { - this.byteString = byteArray.byteString(); + this.byteString = byteArray.getByteString(); } @Override @@ -108,7 +108,12 @@ public final InputStream asInputStream() { return byteString.newInput(); } + @Deprecated protected ByteString byteString() { + return getByteString(); + } + + protected ByteString getByteString() { return byteString; } diff --git a/google-cloud-core/src/main/java/com/google/cloud/ExceptionHandler.java b/google-cloud-core/src/main/java/com/google/cloud/ExceptionHandler.java index e72eb1edcf88..91534885a1ab 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/ExceptionHandler.java +++ b/google-cloud-core/src/main/java/com/google/cloud/ExceptionHandler.java @@ -38,7 +38,7 @@ public final class ExceptionHandler implements Serializable { private static final long serialVersionUID = -2460707015779532919L; private static final ExceptionHandler DEFAULT_INSTANCE = - builder().retryOn(Exception.class).abortOn(RuntimeException.class).build(); + newBuilder().retryOn(Exception.class).abortOn(RuntimeException.class).build(); private final ImmutableList interceptors; private final ImmutableSet> retriableExceptions; @@ -93,7 +93,18 @@ private Builder() {} * @param interceptors the interceptors for this exception handler * @return the Builder for chaining */ + @Deprecated public Builder interceptor(Interceptor... interceptors) { + return addInterceptors(interceptors); + } + + /** + * Adds the exception handler interceptors. Call order will be maintained. + * + * @param interceptors the interceptors for this exception handler + * @return the Builder for chaining + */ + public Builder addInterceptors(Interceptor... interceptors) { for (Interceptor interceptor : interceptors) { this.interceptors.add(interceptor); } @@ -232,14 +243,24 @@ void verifyCaller(Callable callable) { } } + @Deprecated public Set> retriableExceptions() { + return getRetriableExceptions(); + } + + public Set> getRetriableExceptions() { return retriableExceptions; } + @Deprecated public Set> nonRetriableExceptions() { return nonRetriableExceptions; } + public Set> getNonRetriableExceptions() { + return nonRetriableExceptions; + } + boolean shouldRetry(Exception ex) { for (Interceptor interceptor : interceptors) { Interceptor.RetryResult retryResult = checkNotNull(interceptor.beforeEval(ex)); @@ -283,11 +304,24 @@ public boolean equals(Object obj) { /** * Returns an instance which retry any checked exception and abort on any runtime exception. */ + @Deprecated public static ExceptionHandler defaultInstance() { + return getDefaultInstance(); + } + + /** + * Returns an instance which retry any checked exception and abort on any runtime exception. + */ + public static ExceptionHandler getDefaultInstance() { return DEFAULT_INSTANCE; } + @Deprecated public static Builder builder() { + return newBuilder(); + } + + public static Builder newBuilder() { return new Builder(); } } diff --git a/google-cloud-core/src/main/java/com/google/cloud/FieldSelector.java b/google-cloud-core/src/main/java/com/google/cloud/FieldSelector.java index 5a46d058648d..37190a3c2e03 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/FieldSelector.java +++ b/google-cloud-core/src/main/java/com/google/cloud/FieldSelector.java @@ -35,8 +35,15 @@ public interface FieldSelector { * Returns a string selector. This selector is passed to a Google Cloud service (possibly with * other field selectors) to specify which resource fields should be returned by an API call. */ + @Deprecated String selector(); + /** + * Returns a string selector. This selector is passed to a Google Cloud service (possibly with + * other field selectors) to specify which resource fields should be returned by an API call. + */ + String getSelector(); + /** * A helper class used to build composite selectors given a number of fields. This class is not * supposed to be used directly by users. @@ -51,7 +58,7 @@ private Helper() {} new Function() { @Override public String apply(FieldSelector fieldSelector) { - return fieldSelector.selector(); + return fieldSelector.getSelector(); } }; diff --git a/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java b/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java index a4991ae312d1..e0017e09191c 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java +++ b/google-cloud-core/src/main/java/com/google/cloud/GrpcServiceOptions.java @@ -158,19 +158,42 @@ protected Builder(GrpcServiceOptions options) { * * @return the builder */ + @Deprecated public B executorFactory(ExecutorFactory executorFactory) { + return setExecutorFactory(executorFactory); + } + + /** + * Sets the scheduled executor factory. This method can be used to provide an user-defined + * scheduled executor to execute requests. + * + * @return the builder + */ + public B setExecutorFactory(ExecutorFactory executorFactory) { this.executorFactory = executorFactory; return self(); } /** * Sets the timeout for the initial RPC, in milliseconds. Subsequent calls will use this value - * adjusted according to {@link #timeoutMultiplier(double)}. Default value is 20000. + * adjusted according to {@link #setTimeoutMultiplier(double)}. Default value is 20000. * * @return the builder * @throws IllegalArgumentException if the provided timeout is < 0 */ + @Deprecated public B initialTimeout(int initialTimeout) { + return setInitialTimeout(initialTimeout); + } + + /** + * Sets the timeout for the initial RPC, in milliseconds. Subsequent calls will use this value + * adjusted according to {@link #setTimeoutMultiplier(double)}. Default value is 20000. + * + * @return the builder + * @throws IllegalArgumentException if the provided timeout is < 0 + */ + public B setInitialTimeout(int initialTimeout) { Preconditions.checkArgument(initialTimeout > 0, "Initial timeout must be > 0"); this.initialTimeout = initialTimeout; return self(); @@ -183,7 +206,19 @@ public B initialTimeout(int initialTimeout) { * @return the builder * @throws IllegalArgumentException if the provided timeout multiplier is < 0 */ + @Deprecated public B timeoutMultiplier(double timeoutMultiplier) { + return setTimeoutMultiplier(timeoutMultiplier); + } + + /** + * Sets the timeout multiplier. This value is used to compute the timeout for a retried RPC. + * Timeout is computed as {@code timeoutMultiplier * previousTimeout}. Default value is 1.5. + * + * @return the builder + * @throws IllegalArgumentException if the provided timeout multiplier is < 0 + */ + public B setTimeoutMultiplier(double timeoutMultiplier) { Preconditions.checkArgument(timeoutMultiplier >= 1.0, "Timeout multiplier must be >= 1"); this.timeoutMultiplier = timeoutMultiplier; return self(); @@ -191,12 +226,24 @@ public B timeoutMultiplier(double timeoutMultiplier) { /** * Sets the maximum timeout for a RPC call, in milliseconds. Default value is 100000. If - * {@code maxTimeout} is lower than the initial timeout the {@link #initialTimeout(int)} value - * is used instead. + * {@code maxTimeout} is lower than the initial timeout the {@link #setInitialTimeout(int)} + * value is used instead. * * @return the builder */ + @Deprecated public B maxTimeout(int maxTimeout) { + return setMaxTimeout(maxTimeout); + } + + /** + * Sets the maximum timeout for a RPC call, in milliseconds. Default value is 100000. If + * {@code maxTimeout} is lower than the initial timeout the {@link #setInitialTimeout(int)} + * value is used instead. + * + * @return the builder + */ + public B setMaxTimeout(int maxTimeout) { this.maxTimeout = maxTimeout; return self(); } @@ -219,47 +266,80 @@ protected GrpcServiceOptions( /** * Returns a scheduled executor service provider. */ + @Deprecated protected ExecutorFactory executorFactory() { + return getExecutorFactory(); + } + + /** + * Returns a scheduled executor service provider. + */ + protected ExecutorFactory getExecutorFactory() { return executorFactory; } /** * Returns a builder for API call settings. */ + @Deprecated protected UnaryCallSettings.Builder apiCallSettings() { + return getApiCallSettings(); + } + + /** + * Returns a builder for API call settings. + */ + protected UnaryCallSettings.Builder getApiCallSettings() { // todo(mziccard): specify timeout these settings: // retryParams().retryMaxAttempts(), retryParams().retryMinAttempts() final RetrySettings.Builder builder = RetrySettings.newBuilder() - .setTotalTimeout(Duration.millis(retryParams().totalRetryPeriodMillis())) - .setInitialRpcTimeout(Duration.millis(initialTimeout())) - .setRpcTimeoutMultiplier(timeoutMultiplier()) - .setMaxRpcTimeout(Duration.millis(maxTimeout())) - .setInitialRetryDelay(Duration.millis(retryParams().initialRetryDelayMillis())) - .setRetryDelayMultiplier(retryParams().retryDelayBackoffFactor()) - .setMaxRetryDelay(Duration.millis(retryParams().maxRetryDelayMillis())); + .setTotalTimeout(Duration.millis(getRetryParams().getTotalRetryPeriodMillis())) + .setInitialRpcTimeout(Duration.millis(getInitialTimeout())) + .setRpcTimeoutMultiplier(getTimeoutMultiplier()) + .setMaxRpcTimeout(Duration.millis(getMaxTimeout())) + .setInitialRetryDelay(Duration.millis(getRetryParams().getInitialRetryDelayMillis())) + .setRetryDelayMultiplier(getRetryParams().getRetryDelayBackoffFactor()) + .setMaxRetryDelay(Duration.millis(getRetryParams().getMaxRetryDelayMillis())); return UnaryCallSettings.newBuilder().setRetrySettingsBuilder(builder); } /** * Returns a builder for connection-related settings. */ + @Deprecated protected ConnectionSettings.Builder connectionSettings() { - HostAndPort hostAndPort = HostAndPort.fromString(host()); + return getConnectionSettings(); + } + + /** + * Returns a builder for connection-related settings. + */ + protected ConnectionSettings.Builder getConnectionSettings() { + HostAndPort hostAndPort = HostAndPort.fromString(getHost()); ConnectionSettings.Builder builder = ConnectionSettings.newBuilder() .setServiceAddress(hostAndPort.getHostText()) .setPort(hostAndPort.getPort()); - GoogleCredentials credentials = authCredentials().credentials(); + GoogleCredentials credentials = getAuthCredentials().getCredentials(); if (credentials != null) { - builder.provideCredentialsWith(credentials.createScoped(scopes())); + builder.provideCredentialsWith(credentials.createScoped(getScopes())); } return builder; } /** * Returns the timeout for the initial RPC, in milliseconds. Subsequent calls will use this value - * adjusted according to {@link #timeoutMultiplier()}. Default value is 20000. + * adjusted according to {@link #getTimeoutMultiplier()}. Default value is 20000. */ + @Deprecated public int initialTimeout() { + return getInitialTimeout(); + } + + /** + * Returns the timeout for the initial RPC, in milliseconds. Subsequent calls will use this value + * adjusted according to {@link #getTimeoutMultiplier()}. Default value is 20000. + */ + public int getInitialTimeout() { return initialTimeout; } @@ -267,14 +347,31 @@ public int initialTimeout() { * Returns the timeout multiplier. This values is used to compute the timeout for a RPC. Timeout * is computed as {@code timeoutMultiplier * previousTimeout}. Default value is 1.5. */ + @Deprecated public double timeoutMultiplier() { + return getTimeoutMultiplier(); + } + + /** + * Returns the timeout multiplier. This values is used to compute the timeout for a RPC. Timeout + * is computed as {@code timeoutMultiplier * previousTimeout}. Default value is 1.5. + */ + public double getTimeoutMultiplier() { return timeoutMultiplier; } /** * Returns the maximum timeout for a RPC call, in milliseconds. Default value is 100000. */ + @Deprecated public int maxTimeout() { + return getMaxTimeout(); + } + + /** + * Returns the maximum timeout for a RPC call, in milliseconds. Default value is 100000. + */ + public int getMaxTimeout() { return maxTimeout; } diff --git a/google-cloud-core/src/main/java/com/google/cloud/HttpServiceOptions.java b/google-cloud-core/src/main/java/com/google/cloud/HttpServiceOptions.java index eca411849eaf..9e49d537f375 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/HttpServiceOptions.java +++ b/google-cloud-core/src/main/java/com/google/cloud/HttpServiceOptions.java @@ -116,7 +116,17 @@ protected B self() { * * @return the builder */ + @Deprecated public B httpTransportFactory(HttpTransportFactory httpTransportFactory) { + return setHttpTransportFactory(httpTransportFactory); + } + + /** + * Sets the HTTP transport factory. + * + * @return the builder + */ + public B setHttpTransportFactory(HttpTransportFactory httpTransportFactory) { this.httpTransportFactory = httpTransportFactory; return self(); } @@ -128,7 +138,19 @@ public B httpTransportFactory(HttpTransportFactory httpTransportFactory) { * negative number for the default value (20000). * @return the builder */ + @Deprecated public B connectTimeout(int connectTimeout) { + return setConnectTimeout(connectTimeout); + } + + /** + * Sets the timeout in milliseconds to establish a connection. + * + * @param connectTimeout connection timeout in milliseconds. 0 for an infinite timeout, a + * negative number for the default value (20000). + * @return the builder + */ + public B setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; return self(); } @@ -140,7 +162,19 @@ public B connectTimeout(int connectTimeout) { * for the default value (20000). * @return the builder */ + @Deprecated public B readTimeout(int readTimeout) { + return setReadTimeout(readTimeout); + } + + /** + * Sets the timeout in milliseconds to read data from an established connection. + * + * @param readTimeout read timeout in milliseconds. 0 for an infinite timeout, a negative number + * for the default value (20000). + * @return the builder + */ + public B setReadTimeout(int readTimeout) { this.readTimeout = readTimeout; return self(); } @@ -161,19 +195,36 @@ protected HttpServiceOptions( /** * Returns the HTTP transport factory. */ + @Deprecated public HttpTransportFactory httpTransportFactory() { - return httpTransportFactory; + return getHttpTransportFactory(); } + /** + * Returns the HTTP transport factory. + */ + public HttpTransportFactory getHttpTransportFactory() { + return httpTransportFactory; + } /** * Returns a request initializer responsible for initializing requests according to service * options. */ + @Deprecated public HttpRequestInitializer httpRequestInitializer() { + return getHttpRequestInitializer(); + } + + /** + * Returns a request initializer responsible for initializing requests according to service + * options. + */ + public HttpRequestInitializer getHttpRequestInitializer() { final HttpRequestInitializer delegate = - authCredentials() != null && authCredentials().credentials() != null - ? new HttpCredentialsAdapter(authCredentials().credentials().createScoped(scopes())) + getAuthCredentials() != null && getAuthCredentials().getCredentials() != null + ? new HttpCredentialsAdapter( + getAuthCredentials().getCredentials().createScoped(getScopes())) : null; return new HttpRequestInitializer() { @Override @@ -196,6 +247,14 @@ public void initialize(HttpRequest httpRequest) throws IOException { * negative number is the default value (20000). */ public int connectTimeout() { + return getConnectTimeout(); + } + + /** + * Returns the timeout in milliseconds to establish a connection. 0 is an infinite timeout, a + * negative number is the default value (20000). + */ + public int getConnectTimeout() { return connectTimeout; } @@ -203,7 +262,16 @@ public int connectTimeout() { * Returns the timeout in milliseconds to read from an established connection. 0 is an infinite * timeout, a negative number is the default value (20000). */ + @Deprecated public int readTimeout() { + return getReadTimeout(); + } + + /** + * Returns the timeout in milliseconds to read from an established connection. 0 is an infinite + * timeout, a negative number is the default value (20000). + */ + public int getReadTimeout() { return readTimeout; } diff --git a/google-cloud-core/src/main/java/com/google/cloud/Identity.java b/google-cloud-core/src/main/java/com/google/cloud/Identity.java index 783e99f79652..c82005a38d44 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/Identity.java +++ b/google-cloud-core/src/main/java/com/google/cloud/Identity.java @@ -86,7 +86,12 @@ private Identity(Type type, String value) { this.value = value; } + @Deprecated public Type type() { + return getType(); + } + + public Type getType() { return type; } @@ -100,7 +105,22 @@ public Type type() { * {@code ALL_AUTHENTICATED_USERS}) * */ + @Deprecated public String value() { + return getValue(); + } + + /** + * Returns the string identifier for this identity. The value corresponds to: + *
      + *
    • email address (for identities of type {@code USER}, {@code SERVICE_ACCOUNT}, and + * {@code GROUP}) + *
    • domain (for identities of type {@code DOMAIN}) + *
    • {@code null} (for identities of type {@code ALL_USERS} and + * {@code ALL_AUTHENTICATED_USERS}) + *
    + */ + public String getValue() { return value; } @@ -176,7 +196,7 @@ public boolean equals(Object obj) { return false; } Identity other = (Identity) obj; - return Objects.equals(value, other.value()) && Objects.equals(type, other.type()); + return Objects.equals(value, other.getValue()) && Objects.equals(type, other.getType()); } /** diff --git a/google-cloud-core/src/main/java/com/google/cloud/Page.java b/google-cloud-core/src/main/java/com/google/cloud/Page.java index 8881a98b46ae..dde285e3aaa1 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/Page.java +++ b/google-cloud-core/src/main/java/com/google/cloud/Page.java @@ -34,10 +34,10 @@ *
     {@code
      * Page page = ...; // get a Page instance
      * while (page != null) {
    - *   for (T value : page.values()) {
    + *   for (T value : page.getValues()) {
      *     // do something with value
      *   }
    - *   page = page.nextPage();
    + *   page = page.getNextPage();
      * }}
    * * @param the value type that the page holds @@ -47,8 +47,14 @@ public interface Page { /** * Returns the values contained in this page. */ + @Deprecated Iterable values(); + /** + * Returns the values contained in this page. + */ + Iterable getValues(); + /** * Returns an iterator for all values, possibly also in the next pages. Once current page's values * are traversed the iterator fetches next page, if any. @@ -58,11 +64,22 @@ public interface Page { /** * Returns the cursor for the nextPage or {@code null} if no more results. */ + @Deprecated String nextPageCursor(); + /** + * Returns the cursor for the nextPage or {@code null} if no more results. + */ + String getNextPageCursor(); + /** * Returns the next page of results or {@code null} if no more result. */ + @Deprecated Page nextPage(); + /** + * Returns the next page of results or {@code null} if no more result. + */ + Page getNextPage(); } diff --git a/google-cloud-core/src/main/java/com/google/cloud/PageImpl.java b/google-cloud-core/src/main/java/com/google/cloud/PageImpl.java index de1a3506b750..99c675dea375 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/PageImpl.java +++ b/google-cloud-core/src/main/java/com/google/cloud/PageImpl.java @@ -44,7 +44,10 @@ public class PageImpl implements Page, Serializable { * @param the value type that the page holds */ public interface NextPageFetcher extends Serializable { + @Deprecated Page nextPage(); + + Page getNextPage(); } static class PageIterator extends AbstractIterator { @@ -53,18 +56,18 @@ static class PageIterator extends AbstractIterator { private Page currentPage; PageIterator(Page currentPage) { - this.currentPageIterator = currentPage.values().iterator(); + this.currentPageIterator = currentPage.getValues().iterator(); this.currentPage = currentPage; } @Override protected T computeNext() { while (!currentPageIterator.hasNext()) { - currentPage = currentPage.nextPage(); + currentPage = currentPage.getNextPage(); if (currentPage == null) { return endOfData(); } - currentPageIterator = currentPage.values().iterator(); + currentPageIterator = currentPage.getValues().iterator(); } return currentPageIterator.next(); } @@ -81,7 +84,13 @@ public PageImpl(NextPageFetcher pageFetcher, String cursor, Iterable resul } @Override + @Deprecated public Iterable values() { + return getValues(); + } + + @Override + public Iterable getValues() { return results == null ? Collections.emptyList() : results; } @@ -91,16 +100,28 @@ public Iterator iterateAll() { } @Override + @Deprecated public String nextPageCursor() { + return getNextPageCursor(); + } + + @Override + public String getNextPageCursor() { return cursor; } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { if (cursor == null || pageFetcher == null) { return null; } - return pageFetcher.nextPage(); + return pageFetcher.getNextPage(); } @Override diff --git a/google-cloud-core/src/main/java/com/google/cloud/Policy.java b/google-cloud-core/src/main/java/com/google/cloud/Policy.java index 2a8009d4038f..4307f1dffdfc 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/Policy.java +++ b/google-cloud-core/src/main/java/com/google/cloud/Policy.java @@ -87,11 +87,11 @@ protected Policy fromPb(com.google.iam.v1.Policy policyPb) { ImmutableSet.copyOf( Lists.transform(bindingPb.getMembersList(), IDENTITY_VALUE_OF_FUNCTION))); } - return builder() - .bindings(bindings) - .etag(policyPb.getEtag().isEmpty() ? null + return newBuilder() + .setBindings(bindings) + .setEtag(policyPb.getEtag().isEmpty() ? null : BaseEncoding.base64().encode(policyPb.getEtag().toByteArray())) - .version(policyPb.getVersion()) + .setVersion(policyPb.getVersion()) .build(); } @@ -99,9 +99,9 @@ protected Policy fromPb(com.google.iam.v1.Policy policyPb) { protected com.google.iam.v1.Policy toPb(Policy policy) { com.google.iam.v1.Policy.Builder policyBuilder = com.google.iam.v1.Policy.newBuilder(); List bindingPbList = new LinkedList<>(); - for (Map.Entry> binding : policy.bindings().entrySet()) { + for (Map.Entry> binding : policy.getBindings().entrySet()) { com.google.iam.v1.Binding.Builder bindingBuilder = com.google.iam.v1.Binding.newBuilder(); - bindingBuilder.setRole(binding.getKey().value()); + bindingBuilder.setRole(binding.getKey().getValue()); bindingBuilder.addAllMembers( Lists.transform(new ArrayList<>(binding.getValue()), IDENTITY_STR_VALUE_FUNCTION)); bindingPbList.add(bindingBuilder.build()); @@ -127,9 +127,9 @@ public static class Builder { protected Builder() {} protected Builder(Policy policy) { - bindings(policy.bindings); - etag(policy.etag); - version(policy.version); + setBindings(policy.bindings); + setEtag(policy.etag); + setVersion(policy.version); } /** @@ -138,7 +138,18 @@ protected Builder(Policy policy) { * @throws NullPointerException if the given map is null or contains any null keys or values * @throws IllegalArgumentException if any identities in the given map are null */ + @Deprecated public final Builder bindings(Map> bindings) { + return setBindings(bindings); + } + + /** + * Replaces the builder's map of bindings with the given map of bindings. + * + * @throws NullPointerException if the given map is null or contains any null keys or values + * @throws IllegalArgumentException if any identities in the given map are null + */ + public final Builder setBindings(Map> bindings) { checkNotNull(bindings, "The provided map of bindings cannot be null."); for (Map.Entry> binding : bindings.entrySet()) { checkNotNull(binding.getKey(), "The role cannot be null."); @@ -212,7 +223,23 @@ public final Builder removeIdentity(Role role, Identity first, Identity... other * applied to the same version of the policy. If no etag is provided in the call to * setIamPolicy, then the existing policy is overwritten blindly. */ + @Deprecated protected final Builder etag(String etag) { + return setEtag(etag); + } + + /** + * Sets the policy's etag. + * + *

    Etags are used for optimistic concurrency control as a way to help prevent simultaneous + * updates of a policy from overwriting each other. It is strongly suggested that systems make + * use of the etag in the read-modify-write cycle to perform policy updates in order to avoid + * race conditions. An etag is returned in the response to getIamPolicy, and systems are + * expected to put that etag in the request to setIamPolicy to ensure that their change will be + * applied to the same version of the policy. If no etag is provided in the call to + * setIamPolicy, then the existing policy is overwritten blindly. + */ + protected final Builder setEtag(String etag) { this.etag = etag; return this; } @@ -221,7 +248,16 @@ protected final Builder etag(String etag) { * Sets the version of the policy. The default version is 0, meaning only the "owner", "editor", * and "viewer" roles are permitted. If the version is 1, you may also use other roles. */ + @Deprecated protected final Builder version(int version) { + return setVersion(version); + } + + /** + * Sets the version of the policy. The default version is 0, meaning only the "owner", "editor", + * and "viewer" roles are permitted. If the version is 1, you may also use other roles. + */ + protected final Builder setVersion(int version) { this.version = version; return this; } @@ -254,7 +290,15 @@ public Builder toBuilder() { /** * Returns the map of bindings that comprises the policy. */ + @Deprecated public Map> bindings() { + return getBindings(); + } + + /** + * Returns the map of bindings that comprises the policy. + */ + public Map> getBindings() { return bindings; } @@ -269,7 +313,23 @@ public Map> bindings() { * applied to the same version of the policy. If no etag is provided in the call to * setIamPolicy, then the existing policy is overwritten blindly. */ + @Deprecated public String etag() { + return getEtag(); + } + + /** + * Returns the policy's etag. + * + *

    Etags are used for optimistic concurrency control as a way to help prevent simultaneous + * updates of a policy from overwriting each other. It is strongly suggested that systems make + * use of the etag in the read-modify-write cycle to perform policy updates in order to avoid + * race conditions. An etag is returned in the response to getIamPolicy, and systems are + * expected to put that etag in the request to setIamPolicy to ensure that their change will be + * applied to the same version of the policy. If no etag is provided in the call to + * setIamPolicy, then the existing policy is overwritten blindly. + */ + public String getEtag() { return etag; } @@ -277,7 +337,16 @@ public String etag() { * Returns the version of the policy. The default version is 0, meaning only the "owner", * "editor", and "viewer" roles are permitted. If the version is 1, you may also use other roles. */ + @Deprecated public int version() { + return getVersion(); + } + + /** + * Returns the version of the policy. The default version is 0, meaning only the "owner", + * "editor", and "viewer" roles are permitted. If the version is 1, you may also use other roles. + */ + public int getVersion() { return version; } @@ -304,15 +373,23 @@ public boolean equals(Object obj) { return false; } Policy other = (Policy) obj; - return Objects.equals(bindings, other.bindings()) - && Objects.equals(etag, other.etag()) - && Objects.equals(version, other.version()); + return Objects.equals(bindings, other.getBindings()) + && Objects.equals(etag, other.getEtag()) + && Objects.equals(version, other.getVersion()); } /** * Returns a builder for {@code Policy} objects. */ + @Deprecated public static Builder builder() { + return newBuilder(); + } + + /** + * Returns a builder for {@code Policy} objects. + */ + public static Builder newBuilder() { return new Builder(); } } diff --git a/google-cloud-core/src/main/java/com/google/cloud/ReadChannel.java b/google-cloud-core/src/main/java/com/google/cloud/ReadChannel.java index 1ac45902b27d..a09752692884 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/ReadChannel.java +++ b/google-cloud-core/src/main/java/com/google/cloud/ReadChannel.java @@ -44,8 +44,15 @@ public interface ReadChannel extends ReadableByteChannel, Closeable, Restorable< * Sets the minimum size that will be read by a single RPC. * Read data will be locally buffered until consumed. */ + @Deprecated void chunkSize(int chunkSize); + /** + * Sets the minimum size that will be read by a single RPC. + * Read data will be locally buffered until consumed. + */ + void setChunkSize(int chunkSize); + /** * Captures the read channel state so that it can be saved and restored afterwards. * diff --git a/google-cloud-core/src/main/java/com/google/cloud/RetryHelper.java b/google-cloud-core/src/main/java/com/google/cloud/RetryHelper.java index bd59070d4754..b23a516ccac4 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/RetryHelper.java +++ b/google-cloud-core/src/main/java/com/google/cloud/RetryHelper.java @@ -192,9 +192,9 @@ private V doRetry() throws RetryHelperException { } exception = e; } - if (attemptNumber >= params.retryMaxAttempts() - || attemptNumber >= params.retryMinAttempts() - && clock.millis() - start >= params.totalRetryPeriodMillis()) { + if (attemptNumber >= params.getRetryMaxAttempts() + || attemptNumber >= params.getRetryMinAttempts() + && clock.millis() - start >= params.getTotalRetryPeriodMillis()) { throw new RetriesExhaustedException(this + ": Too many failures, giving up", exception); } long sleepDurationMillis = getSleepDuration(params, attemptNumber); @@ -213,9 +213,9 @@ private V doRetry() throws RetryHelperException { @VisibleForTesting static long getSleepDuration(RetryParams retryParams, int attemptsSoFar) { - long initialDelay = retryParams.initialRetryDelayMillis(); - double backoffFactor = retryParams.retryDelayBackoffFactor(); - long maxDelay = retryParams.maxRetryDelayMillis(); + long initialDelay = retryParams.getInitialRetryDelayMillis(); + double backoffFactor = retryParams.getRetryDelayBackoffFactor(); + long maxDelay = retryParams.getMaxRetryDelayMillis(); long retryDelay = getExponentialValue(initialDelay, backoffFactor, maxDelay, attemptsSoFar); return (long) ((random() / 2.0 + .75) * retryDelay); } @@ -226,8 +226,8 @@ private static long getExponentialValue(long initialDelay, double backoffFactor, } public static V runWithRetries(Callable callable) throws RetryHelperException { - return runWithRetries(callable, RetryParams.defaultInstance(), - ExceptionHandler.defaultInstance()); + return runWithRetries(callable, RetryParams.getDefaultInstance(), + ExceptionHandler.getDefaultInstance()); } public static V runWithRetries(Callable callable, RetryParams params, diff --git a/google-cloud-core/src/main/java/com/google/cloud/RetryParams.java b/google-cloud-core/src/main/java/com/google/cloud/RetryParams.java index 02ffda18134f..e835ad5d3cd7 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/RetryParams.java +++ b/google-cloud-core/src/main/java/com/google/cloud/RetryParams.java @@ -38,8 +38,8 @@ * {@code RetryParams}, first create a {@link RetryParams.Builder}. The builder is mutable and each * of the parameters can be set (any unset parameters will fallback to the defaults). The * {@code Builder} can be then used to create an immutable {@code RetryParams} object. For default - * {@code RetryParams} use {@link #defaultInstance}. Default settings are subject to change release - * to release. If you require specific settings, explicitly create an instance of + * {@code RetryParams} use {@link #getDefaultInstance}. Default settings are subject to change + * release to release. If you require specific settings, explicitly create an instance of * {@code RetryParams} with all the required settings. * * @see RetryHelper @@ -71,7 +71,7 @@ public final class RetryParams implements Serializable { // requirement differs from the default parameters used here. private static final RetryParams DEFAULT_INSTANCE = new RetryParams(new Builder()); private static final RetryParams NO_RETRIES = - builder().retryMaxAttempts(1).retryMinAttempts(1).build(); + newBuilder().setRetryMaxAttempts(1).setRetryMinAttempts(1).build(); /** * RetryParams builder. @@ -98,12 +98,12 @@ private Builder() { retryDelayBackoffFactor = DEFAULT_RETRY_DELAY_BACKOFF_FACTOR; totalRetryPeriodMillis = DEFAULT_TOTAL_RETRY_PERIOD_MILLIS; } else { - retryMinAttempts = retryParams.retryMinAttempts(); - retryMaxAttempts = retryParams.retryMaxAttempts(); - initialRetryDelayMillis = retryParams.initialRetryDelayMillis(); - maxRetryDelayMillis = retryParams.maxRetryDelayMillis(); - retryDelayBackoffFactor = retryParams.retryDelayBackoffFactor(); - totalRetryPeriodMillis = retryParams.totalRetryPeriodMillis(); + retryMinAttempts = retryParams.getRetryMinAttempts(); + retryMaxAttempts = retryParams.getRetryMaxAttempts(); + initialRetryDelayMillis = retryParams.getInitialRetryDelayMillis(); + maxRetryDelayMillis = retryParams.getMaxRetryDelayMillis(); + retryDelayBackoffFactor = retryParams.getRetryDelayBackoffFactor(); + totalRetryPeriodMillis = retryParams.getTotalRetryPeriodMillis(); } } @@ -113,7 +113,18 @@ private Builder() { * @param retryMinAttempts the retryMinAttempts to set * @return the Builder for chaining */ + @Deprecated public Builder retryMinAttempts(int retryMinAttempts) { + return setRetryMinAttempts(retryMinAttempts); + } + + /** + * Sets retryMinAttempts. + * + * @param retryMinAttempts the retryMinAttempts to set + * @return the Builder for chaining + */ + public Builder setRetryMinAttempts(int retryMinAttempts) { this.retryMinAttempts = retryMinAttempts; return this; } @@ -124,7 +135,18 @@ public Builder retryMinAttempts(int retryMinAttempts) { * @param retryMaxAttempts the retryMaxAttempts to set * @return the Builder for chaining */ + @Deprecated public Builder retryMaxAttempts(int retryMaxAttempts) { + return setRetryMaxAttempts(retryMaxAttempts); + } + + /** + * Sets retryMaxAttempts. + * + * @param retryMaxAttempts the retryMaxAttempts to set + * @return the Builder for chaining + */ + public Builder setRetryMaxAttempts(int retryMaxAttempts) { this.retryMaxAttempts = retryMaxAttempts; return this; } @@ -135,7 +157,18 @@ public Builder retryMaxAttempts(int retryMaxAttempts) { * @param initialRetryDelayMillis the initialRetryDelayMillis to set * @return the Builder for chaining */ + @Deprecated public Builder initialRetryDelayMillis(long initialRetryDelayMillis) { + return setInitialRetryDelayMillis(initialRetryDelayMillis); + } + + /** + * Sets initialRetryDelayMillis. + * + * @param initialRetryDelayMillis the initialRetryDelayMillis to set + * @return the Builder for chaining + */ + public Builder setInitialRetryDelayMillis(long initialRetryDelayMillis) { this.initialRetryDelayMillis = initialRetryDelayMillis; return this; } @@ -146,7 +179,18 @@ public Builder initialRetryDelayMillis(long initialRetryDelayMillis) { * @param maxRetryDelayMillis the maxRetryDelayMillis to set * @return the Builder for chaining */ + @Deprecated public Builder maxRetryDelayMillis(long maxRetryDelayMillis) { + return setMaxRetryDelayMillis(maxRetryDelayMillis); + } + + /** + * Sets maxRetryDelayMillis. + * + * @param maxRetryDelayMillis the maxRetryDelayMillis to set + * @return the Builder for chaining + */ + public Builder setMaxRetryDelayMillis(long maxRetryDelayMillis) { this.maxRetryDelayMillis = maxRetryDelayMillis; return this; } @@ -157,7 +201,18 @@ public Builder maxRetryDelayMillis(long maxRetryDelayMillis) { * @param retryDelayBackoffFactor the retryDelayBackoffFactor to set * @return the Builder for chaining */ + @Deprecated public Builder retryDelayBackoffFactor(double retryDelayBackoffFactor) { + return setRetryDelayBackoffFactor(retryDelayBackoffFactor); + } + + /** + * Sets retryDelayBackoffFactor. + * + * @param retryDelayBackoffFactor the retryDelayBackoffFactor to set + * @return the Builder for chaining + */ + public Builder setRetryDelayBackoffFactor(double retryDelayBackoffFactor) { this.retryDelayBackoffFactor = retryDelayBackoffFactor; return this; } @@ -170,7 +225,20 @@ public Builder retryDelayBackoffFactor(double retryDelayBackoffFactor) { * @param totalRetryPeriodMillis the totalRetryPeriodMillis to set * @return the Builder for chaining */ + @Deprecated public Builder totalRetryPeriodMillis(long totalRetryPeriodMillis) { + return setTotalRetryPeriodMillis(totalRetryPeriodMillis); + } + + /** + * Sets totalRetryPeriodMillis. Note that App Engine Standard Environment front-end modules have + * a 60 second deadline for HTTP requests. For that reason, you should set the total retry + * period to under 60 seconds if you are using it on an App Engine front-end module. + * + * @param totalRetryPeriodMillis the totalRetryPeriodMillis to set + * @return the Builder for chaining + */ + public Builder setTotalRetryPeriodMillis(long totalRetryPeriodMillis) { this.totalRetryPeriodMillis = totalRetryPeriodMillis; return this; } @@ -210,7 +278,15 @@ private RetryParams(Builder builder) { /** * Returns an instance with the default parameters. */ + @Deprecated public static RetryParams defaultInstance() { + return getDefaultInstance(); + } + + /** + * Returns an instance with the default parameters. + */ + public static RetryParams getDefaultInstance() { return DEFAULT_INSTANCE; } @@ -225,14 +301,30 @@ public static RetryParams noRetries() { /** * Returns the retryMinAttempts. Default value is {@value #DEFAULT_RETRY_MIN_ATTEMPTS}. */ + @Deprecated public int retryMinAttempts() { + return getRetryMinAttempts(); + } + + /** + * Returns the retryMinAttempts. Default value is {@value #DEFAULT_RETRY_MIN_ATTEMPTS}. + */ + public int getRetryMinAttempts() { return retryMinAttempts; } /** * Returns the retryMaxAttempts. Default value is {@value #DEFAULT_RETRY_MAX_ATTEMPTS}. */ + @Deprecated public int retryMaxAttempts() { + return getRetryMaxAttempts(); + } + + /** + * Returns the retryMaxAttempts. Default value is {@value #DEFAULT_RETRY_MAX_ATTEMPTS}. + */ + public int getRetryMaxAttempts() { return retryMaxAttempts; } @@ -240,14 +332,31 @@ public int retryMaxAttempts() { * Returns the initialRetryDelayMillis. Default value is * {@value #DEFAULT_INITIAL_RETRY_DELAY_MILLIS}. */ + @Deprecated public long initialRetryDelayMillis() { + return getInitialRetryDelayMillis(); + } + + /** + * Returns the initialRetryDelayMillis. Default value is + * {@value #DEFAULT_INITIAL_RETRY_DELAY_MILLIS}. + */ + public long getInitialRetryDelayMillis() { return initialRetryDelayMillis; } /** * Returns the maxRetryDelayMillis. Default values is {@value #DEFAULT_MAX_RETRY_DELAY_MILLIS}. */ + @Deprecated public long maxRetryDelayMillis() { + return getMaxRetryDelayMillis(); + } + + /** + * Returns the maxRetryDelayMillis. Default values is {@value #DEFAULT_MAX_RETRY_DELAY_MILLIS}. + */ + public long getMaxRetryDelayMillis() { return maxRetryDelayMillis; } @@ -255,7 +364,16 @@ public long maxRetryDelayMillis() { * Returns the maxRetryDelayBackoffFactor. Default values is * {@value #DEFAULT_RETRY_DELAY_BACKOFF_FACTOR}. */ + @Deprecated public double retryDelayBackoffFactor() { + return getRetryDelayBackoffFactor(); + } + + /** + * Returns the maxRetryDelayBackoffFactor. Default values is + * {@value #DEFAULT_RETRY_DELAY_BACKOFF_FACTOR}. + */ + public double getRetryDelayBackoffFactor() { return retryDelayBackoffFactor; } @@ -263,7 +381,16 @@ public double retryDelayBackoffFactor() { * Returns the totalRetryPeriodMillis. Default value is * {@value #DEFAULT_TOTAL_RETRY_PERIOD_MILLIS}. */ + @Deprecated public long totalRetryPeriodMillis() { + return getTotalRetryPeriodMillis(); + } + + /** + * Returns the totalRetryPeriodMillis. Default value is + * {@value #DEFAULT_TOTAL_RETRY_PERIOD_MILLIS}. + */ + public long getTotalRetryPeriodMillis() { return totalRetryPeriodMillis; } @@ -301,7 +428,12 @@ public String toString() { return toStringHelper.toString(); } + @Deprecated public static Builder builder() { + return newBuilder(); + } + + public static Builder newBuilder() { return new Builder(); } diff --git a/google-cloud-core/src/main/java/com/google/cloud/Role.java b/google-cloud-core/src/main/java/com/google/cloud/Role.java index 60f826d3a9d7..9444421e6b69 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/Role.java +++ b/google-cloud-core/src/main/java/com/google/cloud/Role.java @@ -44,7 +44,16 @@ private Role(String value) { * Returns the string identifier for this role. For example, {@code "roles/viewer"}, * {@code "roles/editor"}, or {@code "roles/owner"}. */ + @Deprecated public String value() { + return getValue(); + } + + /** + * Returns the string identifier for this role. For example, {@code "roles/viewer"}, + * {@code "roles/editor"}, or {@code "roles/owner"}. + */ + public String getValue() { return value; } @@ -104,6 +113,6 @@ public String toString() { @Override public boolean equals(Object obj) { - return obj instanceof Role && Objects.equals(value, ((Role) obj).value()); + return obj instanceof Role && Objects.equals(value, ((Role) obj).getValue()); } } diff --git a/google-cloud-core/src/main/java/com/google/cloud/Service.java b/google-cloud-core/src/main/java/com/google/cloud/Service.java index a3797eca30b9..4c64e6fab2fd 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/Service.java +++ b/google-cloud-core/src/main/java/com/google/cloud/Service.java @@ -22,5 +22,8 @@ * @param the {@code ServiceOptions} subclass corresponding to the service */ public interface Service> { + @Deprecated OptionsT options(); + + OptionsT getOptions(); } diff --git a/google-cloud-core/src/main/java/com/google/cloud/ServiceAccountSigner.java b/google-cloud-core/src/main/java/com/google/cloud/ServiceAccountSigner.java index c68d14116aa8..29202c69d0ae 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/ServiceAccountSigner.java +++ b/google-cloud-core/src/main/java/com/google/cloud/ServiceAccountSigner.java @@ -54,8 +54,14 @@ public int hashCode() { /** * Returns the service account associated with the signer. */ + @Deprecated String account(); + /** + * Returns the service account associated with the signer. + */ + String getAccount(); + /** * Signs the provided bytes using the private key associated with the service account. * diff --git a/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java b/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java index acd1611797f7..f918cd2188c4 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java +++ b/google-cloud-core/src/main/java/com/google/cloud/ServiceOptions.java @@ -70,7 +70,7 @@ public abstract class ServiceOptions, Service private static final String MANIFEST_VERSION_KEY = "Implementation-Version"; private static final String ARTIFACT_ID = "google-cloud-core"; private static final String LIBRARY_NAME = "gcloud-java"; - private static final String LIBRARY_VERSION = getLibraryVersion(); + private static final String LIBRARY_VERSION = defaultLibraryVersion(); private static final String APPLICATION_NAME = LIBRARY_VERSION == null ? LIBRARY_NAME : LIBRARY_NAME + "/" + LIBRARY_VERSION; private static final long serialVersionUID = 3049375916337507361L; @@ -131,7 +131,15 @@ protected B self() { /** * Sets the service factory. */ + @Deprecated public B serviceFactory(ServiceFactory serviceFactory) { + return setServiceFactory(serviceFactory); + } + + /** + * Sets the service factory. + */ + public B setServiceFactory(ServiceFactory serviceFactory) { this.serviceFactory = serviceFactory; return self(); } @@ -143,7 +151,19 @@ public B serviceFactory(ServiceFactory serviceFactory) { * @param clock the clock to set * @return the builder */ + @Deprecated public B clock(Clock clock) { + return setClock(clock); + } + + /** + * Sets the service's clock. The clock is mainly used for testing purpose. {@link Clock} will be + * replaced by Java8's {@code java.time.Clock}. + * + * @param clock the clock to set + * @return the builder + */ + public B setClock(Clock clock) { this.clock = clock; return self(); } @@ -153,7 +173,17 @@ public B clock(Clock clock) { * * @return the builder */ + @Deprecated public B projectId(String projectId) { + return setProjectId(projectId); + } + + /** + * Sets project id. + * + * @return the builder + */ + public B setProjectId(String projectId) { this.projectId = projectId; return self(); } @@ -163,7 +193,17 @@ public B projectId(String projectId) { * * @return the builder */ + @Deprecated public B host(String host) { + return setHost(host); + } + + /** + * Sets service host. + * + * @return the builder + */ + public B setHost(String host) { this.host = host; return self(); } @@ -173,19 +213,41 @@ public B host(String host) { * * @return the builder */ + @Deprecated public B authCredentials(AuthCredentials authCredentials) { + return setAuthCredentials(authCredentials); + } + + /** + * Sets the service authentication credentials. + * + * @return the builder + */ + public B setAuthCredentials(AuthCredentials authCredentials) { this.authCredentials = authCredentials; return self(); } /** * Sets configuration parameters for request retries. If no configuration is set - * {@link RetryParams#defaultInstance()} is used. To disable retries, supply + * {@link RetryParams#getDefaultInstance()} is used. To disable retries, supply * {@link RetryParams#noRetries()} here. * * @return the builder */ + @Deprecated public B retryParams(RetryParams retryParams) { + return setRetryParams(retryParams); + } + + /** + * Sets configuration parameters for request retries. If no configuration is set + * {@link RetryParams#getDefaultInstance()} is used. To disable retries, supply + * {@link RetryParams#noRetries()} here. + * + * @return the builder + */ + public B setRetryParams(RetryParams retryParams) { this.retryParams = retryParams; return self(); } @@ -195,7 +257,17 @@ public B retryParams(RetryParams retryParams) { * * @return the builder */ + @Deprecated public B serviceRpcFactory(ServiceRpcFactory serviceRpcFactory) { + return setServiceRpcFactory(serviceRpcFactory); + } + + /** + * Sets the factory for rpc services. + * + * @return the builder + */ + public B setServiceRpcFactory(ServiceRpcFactory serviceRpcFactory) { this.serviceRpcFactory = serviceRpcFactory; return self(); } @@ -204,23 +276,23 @@ public B serviceRpcFactory(ServiceRpcFactory serviceRpcFa protected ServiceOptions(Class> serviceFactoryClass, Class> rpcFactoryClass, Builder builder) { - projectId = builder.projectId != null ? builder.projectId : defaultProject(); + projectId = builder.projectId != null ? builder.projectId : getDefaultProject(); if (projectIdRequired()) { checkArgument( projectId != null, "A project ID is required for this service but could not be determined from the builder " + "or the environment. Please set a project ID using the builder."); } - host = firstNonNull(builder.host, defaultHost()); + host = firstNonNull(builder.host, getDefaultHost()); authCredentials = builder.authCredentials != null ? builder.authCredentials : defaultAuthCredentials(); authCredentialsState = authCredentials != null ? authCredentials.capture() : null; retryParams = firstNonNull(builder.retryParams, defaultRetryParams()); serviceFactory = firstNonNull(builder.serviceFactory, - getFromServiceLoader(serviceFactoryClass, defaultServiceFactory())); + getFromServiceLoader(serviceFactoryClass, getDefaultServiceFactory())); serviceFactoryClassName = serviceFactory.getClass().getName(); serviceRpcFactory = firstNonNull(builder.serviceRpcFactory, - getFromServiceLoader(rpcFactoryClass, defaultRpcFactory())); + getFromServiceLoader(rpcFactoryClass, getDefaultRpcFactory())); serviceRpcFactoryClassName = serviceRpcFactory.getClass().getName(); clock = firstNonNull(builder.clock, Clock.defaultClock()); } @@ -256,11 +328,21 @@ protected static String appEngineAppId() { return System.getProperty("com.google.appengine.application.id"); } + @Deprecated protected String defaultHost() { + return getDefaultHost(); + } + + protected String getDefaultHost() { return DEFAULT_HOST; } + @Deprecated protected String defaultProject() { + return getDefaultProject(); + } + + protected String getDefaultProject() { String projectId = System.getProperty(PROJECT_ENV_NAME, System.getenv(PROJECT_ENV_NAME)); if (projectId == null) { projectId = @@ -385,16 +467,26 @@ protected static String serviceAccountProjectId() { return project; } - @SuppressWarnings("unchecked") + @Deprecated public ServiceT service() { + return getService(); + } + + @SuppressWarnings("unchecked") + public ServiceT getService() { if (service == null) { service = serviceFactory.create((OptionsT) this); } return service; } - @SuppressWarnings("unchecked") + @Deprecated public ServiceRpcT rpc() { + return getRpc(); + } + + @SuppressWarnings("unchecked") + public ServiceRpcT getRpc() { if (rpc == null) { rpc = serviceRpcFactory.create((OptionsT) this); } @@ -405,29 +497,63 @@ public ServiceRpcT rpc() { * Returns the project id. Return value can be null (for services that don't require a project * id). */ + @Deprecated public String projectId() { + return getProjectId(); + } + + /** + * Returns the project id. Return value can be null (for services that don't require a project + * id). + */ + public String getProjectId() { return projectId; } /** * Returns the service host. */ + @Deprecated public String host() { + return getHost(); + } + + /** + * Returns the service host. + */ + public String getHost() { return host; } /** * Returns the authentication credentials. */ + @Deprecated public AuthCredentials authCredentials() { + return getAuthCredentials(); + } + + /** + * Returns the authentication credentials. + */ + public AuthCredentials getAuthCredentials() { return authCredentials; } /** * Returns configuration parameters for request retries. By default requests are retried: - * {@link RetryParams#defaultInstance()} is used. + * {@link RetryParams#getDefaultInstance()} is used. */ + @Deprecated public RetryParams retryParams() { + return getRetryParams(); + } + + /** + * Returns configuration parameters for request retries. By default requests are retried: + * {@link RetryParams#getDefaultInstance()} is used. + */ + public RetryParams getRetryParams() { return retryParams; } @@ -435,21 +561,46 @@ public RetryParams retryParams() { * Returns the service's clock. Default time source uses {@link System#currentTimeMillis()} to get * current time. */ + @Deprecated public Clock clock() { + return getClock(); + } + + /** + * Returns the service's clock. Default time source uses {@link System#currentTimeMillis()} to get + * current time. + */ + public Clock getClock() { return clock; } /** * Returns the application's name as a string in the format {@code gcloud-java/[version]}. */ + @Deprecated public String applicationName() { + return getApplicationName(); + } + + /** + * Returns the application's name as a string in the format {@code gcloud-java/[version]}. + */ + public String getApplicationName() { return APPLICATION_NAME; } /** * Returns the library's name, {@code gcloud-java}, as a string. */ + @Deprecated public String libraryName() { + return getLibraryName(); + } + + /** + * Returns the library's name, {@code gcloud-java}, as a string. + */ + public String getLibraryName() { return LIBRARY_NAME; } @@ -457,6 +608,13 @@ public String libraryName() { * Returns the library's version as a string. */ public String libraryVersion() { + return getLibraryVersion(); + } + + /** + * Returns the library's version as a string. + */ + public String getLibraryVersion() { return LIBRARY_VERSION; } @@ -491,11 +649,26 @@ static T newInstance(String className) throws IOException, ClassNotFoundExce } } - protected abstract ServiceFactory defaultServiceFactory(); + @Deprecated + protected ServiceFactory defaultServiceFactory() { + return getDefaultServiceFactory(); + } + + protected abstract ServiceFactory getDefaultServiceFactory(); + + @Deprecated + protected ServiceRpcFactory defaultRpcFactory() { + return getDefaultRpcFactory(); + } + + protected abstract ServiceRpcFactory getDefaultRpcFactory(); - protected abstract ServiceRpcFactory defaultRpcFactory(); + @Deprecated + protected Set scopes() { + return getScopes(); + } - protected abstract Set scopes(); + protected abstract Set getScopes(); public abstract > B toBuilder(); @@ -505,14 +678,14 @@ static T newInstance(String className) throws IOException, ClassNotFoundExce * default parameters listed in {@link RetryParams}. */ protected RetryParams defaultRetryParams() { - return RetryParams.defaultInstance(); + return RetryParams.getDefaultInstance(); } static T getFromServiceLoader(Class clazz, T defaultInstance) { return Iterables.getFirst(ServiceLoader.load(clazz), defaultInstance); } - private static String getLibraryVersion() { + private static String defaultLibraryVersion() { String version = null; try { Enumeration resources = diff --git a/google-cloud-core/src/main/java/com/google/cloud/WaitForOption.java b/google-cloud-core/src/main/java/com/google/cloud/WaitForOption.java index 8af7a074ab4d..1938f819943f 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/WaitForOption.java +++ b/google-cloud-core/src/main/java/com/google/cloud/WaitForOption.java @@ -63,14 +63,30 @@ private CheckingPeriod(long period, TimeUnit unit) { /** * Returns the checking period. */ + @Deprecated public long period() { + return getPeriod(); + } + + /** + * Returns the checking period. + */ + public long getPeriod() { return period; } /** - * Returns the time unit for {@link #period()}. + * Returns the time unit for {@link #getPeriod()}. */ + @Deprecated public TimeUnit unit() { + return getUnit(); + } + + /** + * Returns the time unit for {@link #getPeriod()}. + */ + public TimeUnit getUnit() { return unit; } @@ -139,7 +155,15 @@ private Timeout(long timeoutMillis) { /** * Returns the timeout in milliseconds. */ + @Deprecated public long timeoutMillis() { + return getTimeoutMillis(); + } + + /** + * Returns the timeout in milliseconds. + */ + public long getTimeoutMillis() { return timeoutMillis; } @@ -176,7 +200,7 @@ public static Timeout getOrDefault(WaitForOption... options) { } } - OptionType optionType() { + OptionType getOptionType() { return optionType; } diff --git a/google-cloud-core/src/main/java/com/google/cloud/WriteChannel.java b/google-cloud-core/src/main/java/com/google/cloud/WriteChannel.java index 636bc60d0243..f061f55ac581 100644 --- a/google-cloud-core/src/main/java/com/google/cloud/WriteChannel.java +++ b/google-cloud-core/src/main/java/com/google/cloud/WriteChannel.java @@ -33,8 +33,15 @@ public interface WriteChannel extends WritableByteChannel, Closeable, Restorable * Sets the minimum size that will be written by a single RPC. * Written data will be buffered and only flushed upon reaching this size or closing the channel. */ + @Deprecated void chunkSize(int chunkSize); + /** + * Sets the minimum size that will be written by a single RPC. + * Written data will be buffered and only flushed upon reaching this size or closing the channel. + */ + void setChunkSize(int chunkSize); + /** * Captures the write channel state so that it can be saved and restored afterwards. The original * {@code WriteChannel} and the restored one should not both be used. Closing one channel diff --git a/google-cloud-core/src/test/java/com/google/cloud/AsyncPageImplTest.java b/google-cloud-core/src/test/java/com/google/cloud/AsyncPageImplTest.java index 60189a055467..0767d205ecc1 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/AsyncPageImplTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/AsyncPageImplTest.java @@ -41,17 +41,40 @@ public class AsyncPageImplTest { .addAll(VALUES3) .build(); + private static class TestPageFetcher implements AsyncPageImpl.NextPageFetcher { + private static final long serialVersionUID = 4703765400378593176L; + + private final AsyncPageImpl nextResult; + + TestPageFetcher(AsyncPageImpl nextResult) { + this.nextResult = nextResult; + } + + @Override + public Future> nextPage() { + return getNextPage(); + } + + @Override + public Future> getNextPage() { + return Futures.>immediateFuture(nextResult); + } + } + @Test public void testPage() { final AsyncPageImpl nextResult = new AsyncPageImpl<>(null, "c", VALUES2); - AsyncPageImpl.NextPageFetcher fetcher = new AsyncPageImpl.NextPageFetcher() { - private static final long serialVersionUID = 4703765400378593176L; - - @Override - public Future> nextPage() { - return Futures.>immediateFuture(nextResult); - } - }; + AsyncPageImpl.NextPageFetcher fetcher = new TestPageFetcher(nextResult); + AsyncPageImpl result = new AsyncPageImpl<>(fetcher, "c", VALUES1); + assertEquals(nextResult, result.getNextPage()); + assertEquals("c", result.getNextPageCursor()); + assertEquals(VALUES1, result.getValues()); + } + + @Test + public void testPageDeprecated() { + final AsyncPageImpl nextResult = new AsyncPageImpl<>(null, "c", VALUES2); + AsyncPageImpl.NextPageFetcher fetcher = new TestPageFetcher(nextResult); AsyncPageImpl result = new AsyncPageImpl<>(fetcher, "c", VALUES1); assertEquals(nextResult, result.nextPage()); assertEquals("c", result.nextPageCursor()); @@ -61,14 +84,17 @@ public Future> nextPage() { @Test public void testPageAsync() throws ExecutionException, InterruptedException { final AsyncPageImpl nextResult = new AsyncPageImpl<>(null, "c", VALUES2); - AsyncPageImpl.NextPageFetcher fetcher = new AsyncPageImpl.NextPageFetcher() { - private static final long serialVersionUID = 4703765400378593176L; - - @Override - public Future> nextPage() { - return Futures.>immediateFuture(nextResult); - } - }; + AsyncPageImpl.NextPageFetcher fetcher = new TestPageFetcher(nextResult); + AsyncPageImpl result = new AsyncPageImpl<>(fetcher, "c", VALUES1); + assertEquals(nextResult, result.getNextPageAsync().get()); + assertEquals("c", result.getNextPageCursor()); + assertEquals(VALUES1, result.getValues()); + } + + @Test + public void testPageAsyncDeprecated() throws ExecutionException, InterruptedException { + final AsyncPageImpl nextResult = new AsyncPageImpl<>(null, "c", VALUES2); + AsyncPageImpl.NextPageFetcher fetcher = new TestPageFetcher(nextResult); AsyncPageImpl result = new AsyncPageImpl<>(fetcher, "c", VALUES1); assertEquals(nextResult, result.nextPageAsync().get()); assertEquals("c", result.nextPageCursor()); @@ -78,23 +104,9 @@ public Future> nextPage() { @Test public void testIterateAll() { final AsyncPageImpl nextResult2 = new AsyncPageImpl<>(null, "c3", VALUES3); - AsyncPageImpl.NextPageFetcher fetcher2 = new AsyncPageImpl.NextPageFetcher() { - private static final long serialVersionUID = -9203621430631884026L; - - @Override - public Future> nextPage() { - return Futures.>immediateFuture(nextResult2); - } - }; + AsyncPageImpl.NextPageFetcher fetcher2 = new TestPageFetcher(nextResult2); final AsyncPageImpl nextResult1 = new AsyncPageImpl<>(fetcher2, "c2", VALUES2); - AsyncPageImpl.NextPageFetcher fetcher1 = new AsyncPageImpl.NextPageFetcher() { - private static final long serialVersionUID = -9203621430631884026L; - - @Override - public Future> nextPage() { - return Futures.>immediateFuture(nextResult1); - } - }; + AsyncPageImpl.NextPageFetcher fetcher1 = new TestPageFetcher(nextResult1); AsyncPageImpl result = new AsyncPageImpl<>(fetcher1, "c1", VALUES1); assertEquals(ALL_VALUES, ImmutableList.copyOf(result.iterateAll())); } @@ -102,27 +114,13 @@ public Future> nextPage() { @Test public void testAsyncPageAndIterateAll() throws ExecutionException, InterruptedException { final AsyncPageImpl nextResult2 = new AsyncPageImpl<>(null, "c3", VALUES3); - AsyncPageImpl.NextPageFetcher fetcher2 = new AsyncPageImpl.NextPageFetcher() { - private static final long serialVersionUID = -9203621430631884026L; - - @Override - public Future> nextPage() { - return Futures.>immediateFuture(nextResult2); - } - }; + AsyncPageImpl.NextPageFetcher fetcher2 = new TestPageFetcher(nextResult2); final AsyncPageImpl nextResult1 = new AsyncPageImpl<>(fetcher2, "c2", VALUES2); - AsyncPageImpl.NextPageFetcher fetcher1 = new AsyncPageImpl.NextPageFetcher() { - private static final long serialVersionUID = -9203621430631884026L; - - @Override - public Future> nextPage() { - return Futures.>immediateFuture(nextResult1); - } - }; + AsyncPageImpl.NextPageFetcher fetcher1 = new TestPageFetcher(nextResult1); AsyncPageImpl result = new AsyncPageImpl<>(fetcher1, "c1", VALUES1); - assertEquals(nextResult1, result.nextPageAsync().get()); - assertEquals("c1", result.nextPageCursor()); - assertEquals(VALUES1, result.values()); - assertEquals(SOME_VALUES, ImmutableList.copyOf(result.nextPageAsync().get().iterateAll())); + assertEquals(nextResult1, result.getNextPageAsync().get()); + assertEquals("c1", result.getNextPageCursor()); + assertEquals(VALUES1, result.getValues()); + assertEquals(SOME_VALUES, ImmutableList.copyOf(result.getNextPageAsync().get().iterateAll())); } } diff --git a/google-cloud-core/src/test/java/com/google/cloud/AuthCredentialsTest.java b/google-cloud-core/src/test/java/com/google/cloud/AuthCredentialsTest.java index 9074c2d103a6..3ae34e6ca934 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/AuthCredentialsTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/AuthCredentialsTest.java @@ -88,12 +88,30 @@ public static void beforeClass() throws NoSuchAlgorithmException, InvalidKeySpec @Test public void testNoAuthCredentials() { + assertSame(NO_AUTH_CREDENTIALS, AuthCredentials.noAuth()); + assertNull(NO_AUTH_CREDENTIALS.getCredentials()); + } + + @Test + public void testNoAuthCredentialsDeprecated() { assertSame(NO_AUTH_CREDENTIALS, AuthCredentials.noAuth()); assertNull(NO_AUTH_CREDENTIALS.credentials()); } @Test public void testOAuth2AuthCredentials() { + AccessToken accessToken = OAUTH2_AUTH_CREDENTIALS.getCredentials().getAccessToken(); + assertEquals(ACCESS_TOKEN, accessToken.getTokenValue()); + assertEquals(EXPIRATION_DATE, accessToken.getExpirationTime()); + OAuth2AuthCredentials oAuth2AuthCredentials = + AuthCredentials.createFor(ACCESS_TOKEN); + accessToken = oAuth2AuthCredentials.getCredentials().getAccessToken(); + assertEquals(ACCESS_TOKEN, accessToken.getTokenValue()); + assertNull(accessToken.getExpirationTime()); + } + + @Test + public void testOAuth2AuthCredentialsDeprecated() { AccessToken accessToken = OAUTH2_AUTH_CREDENTIALS.credentials().getAccessToken(); assertEquals(ACCESS_TOKEN, accessToken.getTokenValue()); assertEquals(EXPIRATION_DATE, accessToken.getExpirationTime()); @@ -106,6 +124,17 @@ public void testOAuth2AuthCredentials() { @Test public void testServiceAccountFromJson() throws IOException, SignatureException { + ServiceAccountAuthCredentials serviceAccountAuthCredentials = + AuthCredentials.createForJson(new ByteArrayInputStream(JSON_KEY.getBytes())); + ServiceAccountCredentials credentials = serviceAccountAuthCredentials.getCredentials(); + assertEquals(SERVICE_ACCOUNT, serviceAccountAuthCredentials.getAccount()); + assertEquals(SERVICE_ACCOUNT, credentials.getClientEmail()); + assertEquals(privateKey, credentials.getPrivateKey()); + assertArrayEquals(signedBytes, serviceAccountAuthCredentials.sign(BYTES_TO_SIGN)); + } + + @Test + public void testServiceAccountFromJsonDeprecated() throws IOException, SignatureException { ServiceAccountAuthCredentials serviceAccountAuthCredentials = AuthCredentials.createForJson(new ByteArrayInputStream(JSON_KEY.getBytes())); ServiceAccountCredentials credentials = serviceAccountAuthCredentials.credentials(); @@ -117,6 +146,17 @@ public void testServiceAccountFromJson() throws IOException, SignatureException @Test public void testServiceAccountFromKey() throws IOException, SignatureException { + ServiceAccountAuthCredentials serviceAccountAuthCredentials = + AuthCredentials.createFor(SERVICE_ACCOUNT, privateKey); + ServiceAccountCredentials credentials = serviceAccountAuthCredentials.getCredentials(); + assertEquals(SERVICE_ACCOUNT, serviceAccountAuthCredentials.getAccount()); + assertEquals(SERVICE_ACCOUNT, credentials.getClientEmail()); + assertEquals(privateKey, credentials.getPrivateKey()); + assertArrayEquals(signedBytes, serviceAccountAuthCredentials.sign(BYTES_TO_SIGN)); + } + + @Test + public void testServiceAccountFromKeyDeprecated() throws IOException, SignatureException { ServiceAccountAuthCredentials serviceAccountAuthCredentials = AuthCredentials.createFor(SERVICE_ACCOUNT, privateKey); ServiceAccountCredentials credentials = serviceAccountAuthCredentials.credentials(); diff --git a/google-cloud-core/src/test/java/com/google/cloud/BaseServiceExceptionTest.java b/google-cloud-core/src/test/java/com/google/cloud/BaseServiceExceptionTest.java index 4517afff44ae..8980643b32c9 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/BaseServiceExceptionTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/BaseServiceExceptionTest.java @@ -56,7 +56,7 @@ public CustomServiceException(int code, String message, String reason, boolean i } @Override - protected Set retryableErrors() { + protected Set getRetryableErrors() { return ImmutableSet.of(new Error(CODE, REASON), new Error(null, REASON), new Error(CODE_NO_REASON, null)); } @@ -64,6 +64,94 @@ protected Set retryableErrors() { @Test public void testBaseServiceException() { + BaseServiceException serviceException = new BaseServiceException(CODE, MESSAGE, REASON, + IDEMPOTENT); + assertEquals(CODE, serviceException.getCode()); + assertEquals(MESSAGE, serviceException.getMessage()); + assertEquals(REASON, serviceException.getReason()); + assertFalse(serviceException.isRetryable()); + assertEquals(IDEMPOTENT, serviceException.isIdempotent()); + assertNull(serviceException.getCause()); + + serviceException = new BaseServiceException(CODE, MESSAGE, REASON, IDEMPOTENT); + assertEquals(CODE, serviceException.getCode()); + assertEquals(MESSAGE, serviceException.getMessage()); + assertEquals(REASON, serviceException.getReason()); + assertFalse(serviceException.isRetryable()); + assertEquals(IDEMPOTENT, serviceException.isIdempotent()); + assertNull(serviceException.getCause()); + + Exception cause = new RuntimeException(); + serviceException = new BaseServiceException(CODE, MESSAGE, REASON, IDEMPOTENT, cause); + assertEquals(CODE, serviceException.getCode()); + assertEquals(MESSAGE, serviceException.getMessage()); + assertEquals(REASON, serviceException.getReason()); + assertFalse(serviceException.isRetryable()); + assertEquals(IDEMPOTENT, serviceException.isIdempotent()); + assertEquals(cause, serviceException.getCause()); + + serviceException = new BaseServiceException(CODE, MESSAGE, REASON, false, cause); + assertEquals(CODE, serviceException.getCode()); + assertEquals(MESSAGE, serviceException.getMessage()); + assertEquals(REASON, serviceException.getReason()); + assertFalse(serviceException.isRetryable()); + assertFalse(serviceException.isIdempotent()); + assertEquals(cause, serviceException.getCause()); + + IOException exception = new SocketTimeoutException(); + serviceException = new BaseServiceException(exception, true); + assertTrue(serviceException.isRetryable()); + assertTrue(serviceException.isIdempotent()); + assertNull(serviceException.getMessage()); + assertEquals(exception, serviceException.getCause()); + + exception = new SocketException(); + serviceException = new BaseServiceException(exception, true); + assertTrue(serviceException.isRetryable()); + assertTrue(serviceException.isIdempotent()); + assertNull(serviceException.getMessage()); + assertEquals(exception, serviceException.getCause()); + + exception = new IOException("insufficient data written"); + serviceException = new BaseServiceException(exception, true); + assertTrue(serviceException.isRetryable()); + assertTrue(serviceException.isIdempotent()); + assertEquals("insufficient data written", serviceException.getMessage()); + assertEquals(exception, serviceException.getCause()); + + GoogleJsonError error = new GoogleJsonError(); + error.setCode(CODE); + error.setMessage(MESSAGE); + serviceException = new BaseServiceException(error, true); + assertEquals(CODE, serviceException.getCode()); + assertEquals(MESSAGE, serviceException.getMessage()); + assertFalse(serviceException.isRetryable()); + assertTrue(serviceException.isIdempotent()); + + serviceException = new CustomServiceException(CODE, MESSAGE, REASON, IDEMPOTENT); + assertEquals(CODE, serviceException.getCode()); + assertEquals(MESSAGE, serviceException.getMessage()); + assertEquals(REASON, serviceException.getReason()); + assertEquals(RETRYABLE, serviceException.isRetryable()); + assertEquals(IDEMPOTENT, serviceException.isIdempotent()); + + serviceException = new CustomServiceException(CODE_NO_REASON, MESSAGE, null, IDEMPOTENT); + assertEquals(CODE_NO_REASON, serviceException.getCode()); + assertEquals(MESSAGE, serviceException.getMessage()); + assertNull(serviceException.getReason()); + assertEquals(RETRYABLE, serviceException.isRetryable()); + assertEquals(IDEMPOTENT, serviceException.isIdempotent()); + + serviceException = new CustomServiceException(UNKNOWN_CODE, MESSAGE, REASON, IDEMPOTENT); + assertEquals(UNKNOWN_CODE, serviceException.getCode()); + assertEquals(MESSAGE, serviceException.getMessage()); + assertEquals(REASON, serviceException.getReason()); + assertEquals(RETRYABLE, serviceException.isRetryable()); + assertEquals(IDEMPOTENT, serviceException.isIdempotent()); + } + + @Test + public void testBaseServiceExceptionDeprecated() { BaseServiceException serviceException = new BaseServiceException(CODE, MESSAGE, REASON, IDEMPOTENT); assertEquals(CODE, serviceException.code()); @@ -160,10 +248,10 @@ public void testTranslateAndThrow() throws Exception { try { BaseServiceException.translateAndPropagateIfPossible(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(CODE, ex.code()); + assertEquals(CODE, ex.getCode()); assertEquals(MESSAGE, ex.getMessage()); - assertFalse(ex.retryable()); - assertEquals(IDEMPOTENT, ex.idempotent()); + assertFalse(ex.isRetryable()); + assertEquals(IDEMPOTENT, ex.isIdempotent()); } finally { verify(exceptionMock); } diff --git a/google-cloud-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java b/google-cloud-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java index fc476b11ae6e..9fb58a1633d9 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/BaseWriteChannelTest.java @@ -83,6 +83,18 @@ protected BaseState.Builder stateBuilder() { @Test public void testConstructor() { + assertEquals(null, channel.getOptions()); + assertEquals(ENTITY, channel.getEntity()); + assertEquals(0, channel.getPosition()); + assertEquals(UPLOAD_ID, channel.getUploadId()); + assertEquals(0, channel.getLimit()); + assertTrue(channel.isOpen()); + assertArrayEquals(new byte[0], channel.getBuffer()); + assertEquals(DEFAULT_CHUNK_SIZE, channel.getChunkSize()); + } + + @Test + public void testConstructorDeprecated() { assertEquals(null, channel.options()); assertEquals(ENTITY, channel.entity()); assertEquals(0, channel.position()); @@ -97,7 +109,7 @@ public void testConstructor() { public void testClose() throws IOException { channel.close(); assertFalse(channel.isOpen()); - assertNull(channel.buffer()); + assertNull(channel.getBuffer()); } @Test @@ -109,31 +121,31 @@ public void testValidateOpen() throws IOException { @Test public void testChunkSize() { - channel.chunkSize(42); - assertEquals(MIN_CHUNK_SIZE, channel.chunkSize()); - channel.chunkSize(2 * MIN_CHUNK_SIZE); - assertEquals(2 * MIN_CHUNK_SIZE, channel.chunkSize()); - channel.chunkSize(512 * 1025); - assertEquals(2 * MIN_CHUNK_SIZE, channel.chunkSize()); + channel.setChunkSize(42); + assertEquals(MIN_CHUNK_SIZE, channel.getChunkSize()); + channel.setChunkSize(2 * MIN_CHUNK_SIZE); + assertEquals(2 * MIN_CHUNK_SIZE, channel.getChunkSize()); + channel.setChunkSize(512 * 1025); + assertEquals(2 * MIN_CHUNK_SIZE, channel.getChunkSize()); } @Test public void testWrite() throws IOException { channel.write(ByteBuffer.wrap(CONTENT)); - assertEquals(CONTENT.length, channel.limit()); - assertEquals(DEFAULT_CHUNK_SIZE, channel.buffer().length); - assertArrayEquals(Arrays.copyOf(CONTENT, DEFAULT_CHUNK_SIZE), channel.buffer()); + assertEquals(CONTENT.length, channel.getLimit()); + assertEquals(DEFAULT_CHUNK_SIZE, channel.getBuffer().length); + assertArrayEquals(Arrays.copyOf(CONTENT, DEFAULT_CHUNK_SIZE), channel.getBuffer()); } @Test public void testWriteAndFlush() throws IOException { ByteBuffer content = randomBuffer(DEFAULT_CHUNK_SIZE + 1); channel.write(content); - assertEquals(DEFAULT_CHUNK_SIZE, channel.position()); - assertEquals(1, channel.limit()); + assertEquals(DEFAULT_CHUNK_SIZE, channel.getPosition()); + assertEquals(1, channel.getLimit()); byte[] newContent = new byte[DEFAULT_CHUNK_SIZE]; newContent[0] = content.get(DEFAULT_CHUNK_SIZE); - assertArrayEquals(newContent, channel.buffer()); + assertArrayEquals(newContent, channel.getBuffer()); } private static ByteBuffer randomBuffer(int size) { diff --git a/google-cloud-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java b/google-cloud-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java index ddbd2ced841c..f489207019ac 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/ExceptionHandlerTest.java @@ -82,7 +82,7 @@ public Object call() throws Error { } // using default exception handler (retry upon any non-runtime exceptions) - ExceptionHandler handler = ExceptionHandler.defaultInstance(); + ExceptionHandler handler = ExceptionHandler.getDefaultInstance(); assertValidCallable(new A(), handler); assertValidCallable(new B(), handler); assertValidCallable(new C(), handler); @@ -90,7 +90,7 @@ public Object call() throws Error { assertValidCallable(new E(), handler); assertInvalidCallable(new F(), handler); - handler = ExceptionHandler.builder() + handler = ExceptionHandler.newBuilder() .retryOn(FileNotFoundException.class, NullPointerException.class) .build(); assertInvalidCallable(new A(), handler); @@ -116,12 +116,12 @@ private static void assertInvalidCallable(Callable callable, ExceptionHan @Test public void testShouldTry() { - ExceptionHandler handler = ExceptionHandler.builder().retryOn(IOException.class).build(); + ExceptionHandler handler = ExceptionHandler.newBuilder().retryOn(IOException.class).build(); assertTrue(handler.shouldRetry(new IOException())); assertTrue(handler.shouldRetry(new ClosedByInterruptException())); assertFalse(handler.shouldRetry(new RuntimeException())); - ExceptionHandler.Builder builder = ExceptionHandler.builder() + ExceptionHandler.Builder builder = ExceptionHandler.newBuilder() .retryOn(IOException.class, NullPointerException.class) .abortOn(RuntimeException.class, ClosedByInterruptException.class, InterruptedException.class); @@ -148,7 +148,7 @@ public RetryResult beforeEval(Exception exception) { } }; - builder.interceptor(interceptor); + builder.addInterceptors(interceptor); handler = builder.build(); assertFalse(handler.shouldRetry(new IOException())); assertFalse(handler.shouldRetry(new ClosedByInterruptException())); @@ -188,7 +188,7 @@ public RetryResult afterEval(Exception exception, RetryResult retryResult) { }; - ExceptionHandler handler = ExceptionHandler.builder().interceptor(interceptor).build(); + ExceptionHandler handler = ExceptionHandler.newBuilder().addInterceptors(interceptor).build(); thrown.expect(NullPointerException.class); handler.shouldRetry(new Exception()); } @@ -210,7 +210,7 @@ public RetryResult afterEval(Exception exception, RetryResult retryResult) { }; - ExceptionHandler handler = ExceptionHandler.builder().interceptor(interceptor).build(); + ExceptionHandler handler = ExceptionHandler.newBuilder().addInterceptors(interceptor).build(); thrown.expect(NullPointerException.class); handler.shouldRetry(new Exception()); } diff --git a/google-cloud-core/src/test/java/com/google/cloud/FieldSelectorHelperTest.java b/google-cloud-core/src/test/java/com/google/cloud/FieldSelectorHelperTest.java index 02d5847946e0..408dc731324a 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/FieldSelectorHelperTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/FieldSelectorHelperTest.java @@ -31,18 +31,33 @@ public class FieldSelectorHelperTest { private static final FieldSelector FIELD1 = new FieldSelector() { @Override public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return "field1"; } }; private static final FieldSelector FIELD2 = new FieldSelector() { @Override public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return "field2"; } }; private static final FieldSelector FIELD3 = new FieldSelector() { @Override public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return "field3"; } }; diff --git a/google-cloud-core/src/test/java/com/google/cloud/GrpcServiceOptionsTest.java b/google-cloud-core/src/test/java/com/google/cloud/GrpcServiceOptionsTest.java index 457f05cd0ba9..f0906fae03b2 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/GrpcServiceOptionsTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/GrpcServiceOptionsTest.java @@ -36,15 +36,25 @@ public class GrpcServiceOptionsTest { private static final ExecutorFactory MOCK_EXECUTOR_FACTORY = EasyMock.createMock(ExecutorFactory.class); - private static final TestGrpcServiceOptions OPTIONS = TestGrpcServiceOptions.builder() - .projectId("project-id") - .initialTimeout(1234) - .timeoutMultiplier(1.6) - .maxTimeout(5678) - .executorFactory(MOCK_EXECUTOR_FACTORY) + private static final TestGrpcServiceOptions OPTIONS = TestGrpcServiceOptions.newBuilder() + .setProjectId("project-id") + .setInitialTimeout(1234) + .setTimeoutMultiplier(1.6) + .setMaxTimeout(5678) + .setExecutorFactory(MOCK_EXECUTOR_FACTORY) .build(); + private static final TestGrpcServiceOptions DEPRECATED_OPTIONS = + TestGrpcServiceOptions.newBuilder() + .projectId("project-id") + .initialTimeout(1234) + .timeoutMultiplier(1.6) + .maxTimeout(5678) + .executorFactory(MOCK_EXECUTOR_FACTORY) + .build(); private static final TestGrpcServiceOptions DEFAULT_OPTIONS = - TestGrpcServiceOptions.builder().projectId("project-id").build(); + TestGrpcServiceOptions.newBuilder().setProjectId("project-id").build(); + private static final TestGrpcServiceOptions DEPRECATED_DEFAULT_OPTIONS = + TestGrpcServiceOptions.newBuilder().projectId("project-id").build(); private static final TestGrpcServiceOptions OPTIONS_COPY = OPTIONS.toBuilder().build(); private interface TestService extends Service {} @@ -108,17 +118,17 @@ private TestGrpcServiceOptions(Builder builder) { } @Override - protected TestServiceFactory defaultServiceFactory() { + protected TestServiceFactory getDefaultServiceFactory() { return DefaultTestServiceFactory.INSTANCE; } @Override - protected TestServiceRpcFactory defaultRpcFactory() { + protected TestServiceRpcFactory getDefaultRpcFactory() { return DefaultTestServiceRpcFactory.INSTANCE; } @Override - protected Set scopes() { + protected Set getScopes() { return null; } @@ -127,7 +137,7 @@ public Builder toBuilder() { return new Builder(this); } - private static Builder builder() { + private static Builder newBuilder() { return new Builder(); } @@ -144,32 +154,44 @@ public int hashCode() { @Test public void testBuilder() { - assertEquals(1234, OPTIONS.initialTimeout()); - assertEquals(1.6, OPTIONS.timeoutMultiplier(), 0.0); - assertEquals(5678, OPTIONS.maxTimeout()); - assertSame(MOCK_EXECUTOR_FACTORY, OPTIONS.executorFactory()); - assertEquals(20000, DEFAULT_OPTIONS.initialTimeout()); - assertEquals(1.5, DEFAULT_OPTIONS.timeoutMultiplier(), 0.0); - assertEquals(100000, DEFAULT_OPTIONS.maxTimeout()); - assertTrue(DEFAULT_OPTIONS.executorFactory() instanceof DefaultExecutorFactory); + assertEquals(1234, OPTIONS.getInitialTimeout()); + assertEquals(1.6, OPTIONS.getTimeoutMultiplier(), 0.0); + assertEquals(5678, OPTIONS.getMaxTimeout()); + assertSame(MOCK_EXECUTOR_FACTORY, OPTIONS.getExecutorFactory()); + assertEquals(20000, DEFAULT_OPTIONS.getInitialTimeout()); + assertEquals(1.5, DEFAULT_OPTIONS.getTimeoutMultiplier(), 0.0); + assertEquals(100000, DEFAULT_OPTIONS.getMaxTimeout()); + assertTrue(DEFAULT_OPTIONS.getExecutorFactory() instanceof DefaultExecutorFactory); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(1234, DEPRECATED_OPTIONS.initialTimeout()); + assertEquals(1.6, DEPRECATED_OPTIONS.timeoutMultiplier(), 0.0); + assertEquals(5678, DEPRECATED_OPTIONS.maxTimeout()); + assertSame(MOCK_EXECUTOR_FACTORY, DEPRECATED_OPTIONS.executorFactory()); + assertEquals(20000, DEPRECATED_DEFAULT_OPTIONS.initialTimeout()); + assertEquals(1.5, DEPRECATED_DEFAULT_OPTIONS.timeoutMultiplier(), 0.0); + assertEquals(100000, DEPRECATED_DEFAULT_OPTIONS.maxTimeout()); + assertTrue(DEPRECATED_DEFAULT_OPTIONS.executorFactory() instanceof DefaultExecutorFactory); } @Test public void testBuilderError() { try { - TestGrpcServiceOptions.builder().initialTimeout(0); + TestGrpcServiceOptions.newBuilder().setInitialTimeout(0); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { assertEquals("Initial timeout must be > 0", ex.getMessage()); } try { - TestGrpcServiceOptions.builder().initialTimeout(-1); + TestGrpcServiceOptions.newBuilder().setInitialTimeout(-1); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { assertEquals("Initial timeout must be > 0", ex.getMessage()); } try { - TestGrpcServiceOptions.builder().timeoutMultiplier(0.9); + TestGrpcServiceOptions.newBuilder().setTimeoutMultiplier(0.9); fail("IllegalArgumentException expected"); } catch (IllegalArgumentException ex) { assertEquals("Timeout multiplier must be >= 1", ex.getMessage()); @@ -178,15 +200,15 @@ public void testBuilderError() { @Test public void testBuilderInvalidMaxTimeout() { - TestGrpcServiceOptions options = TestGrpcServiceOptions.builder() - .projectId("project-id") - .initialTimeout(1234) - .timeoutMultiplier(1.6) - .maxTimeout(123) + TestGrpcServiceOptions options = TestGrpcServiceOptions.newBuilder() + .setProjectId("project-id") + .setInitialTimeout(1234) + .setTimeoutMultiplier(1.6) + .setMaxTimeout(123) .build(); - assertEquals(1234, options.initialTimeout()); - assertEquals(1.6, options.timeoutMultiplier(), 0.0); - assertEquals(1234, options.maxTimeout()); + assertEquals(1234, options.getInitialTimeout()); + assertEquals(1.6, options.getTimeoutMultiplier(), 0.0); + assertEquals(1234, options.getMaxTimeout()); } @Test @@ -194,7 +216,7 @@ public void testBaseEquals() { assertEquals(OPTIONS, OPTIONS_COPY); assertNotEquals(DEFAULT_OPTIONS, OPTIONS); TestGrpcServiceOptions options = OPTIONS.toBuilder() - .executorFactory(new DefaultExecutorFactory()) + .setExecutorFactory(new DefaultExecutorFactory()) .build(); assertNotEquals(OPTIONS, options); } @@ -204,7 +226,7 @@ public void testBaseHashCode() { assertEquals(OPTIONS.hashCode(), OPTIONS_COPY.hashCode()); assertNotEquals(DEFAULT_OPTIONS.hashCode(), OPTIONS.hashCode()); TestGrpcServiceOptions options = OPTIONS.toBuilder() - .executorFactory(new DefaultExecutorFactory()) + .setExecutorFactory(new DefaultExecutorFactory()) .build(); assertNotEquals(OPTIONS.hashCode(), options.hashCode()); } diff --git a/google-cloud-core/src/test/java/com/google/cloud/HttpServiceOptionsTest.java b/google-cloud-core/src/test/java/com/google/cloud/HttpServiceOptionsTest.java index de8dc8592eeb..a372498c2173 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/HttpServiceOptionsTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/HttpServiceOptionsTest.java @@ -34,14 +34,23 @@ public class HttpServiceOptionsTest { private static final HttpTransportFactory MOCK_HTTP_TRANSPORT_FACTORY = EasyMock.createMock(HttpTransportFactory.class); - private static final TestHttpServiceOptions OPTIONS = TestHttpServiceOptions.builder() - .projectId("project-id") - .connectTimeout(1234) - .httpTransportFactory(MOCK_HTTP_TRANSPORT_FACTORY) - .readTimeout(5678) + private static final TestHttpServiceOptions OPTIONS = TestHttpServiceOptions.newBuilder() + .setProjectId("project-id") + .setConnectTimeout(1234) + .setHttpTransportFactory(MOCK_HTTP_TRANSPORT_FACTORY) + .setReadTimeout(5678) .build(); + private static final TestHttpServiceOptions DEPRECATED_OPTIONS = + TestHttpServiceOptions.newBuilder() + .projectId("project-id") + .connectTimeout(1234) + .httpTransportFactory(MOCK_HTTP_TRANSPORT_FACTORY) + .readTimeout(5678) + .build(); private static final TestHttpServiceOptions DEFAULT_OPTIONS = - TestHttpServiceOptions.builder().projectId("project-id").build(); + TestHttpServiceOptions.newBuilder().setProjectId("project-id").build(); + private static final TestHttpServiceOptions DEPRECATED_DEFAULT_OPTIONS = + TestHttpServiceOptions.newBuilder().projectId("project-id").build(); private static final TestHttpServiceOptions OPTIONS_COPY = OPTIONS.toBuilder().build(); private interface TestService extends Service {} @@ -105,17 +114,17 @@ private TestHttpServiceOptions(Builder builder) { } @Override - protected TestServiceFactory defaultServiceFactory() { + protected TestServiceFactory getDefaultServiceFactory() { return DefaultTestServiceFactory.INSTANCE; } @Override - protected TestServiceRpcFactory defaultRpcFactory() { + protected TestServiceRpcFactory getDefaultRpcFactory() { return DefaultTestServiceRpcFactory.INSTANCE; } @Override - protected Set scopes() { + protected Set getScopes() { return null; } @@ -124,7 +133,7 @@ public Builder toBuilder() { return new Builder(this); } - private static Builder builder() { + private static Builder newBuilder() { return new Builder(); } @@ -141,12 +150,23 @@ public int hashCode() { @Test public void testBuilder() { - assertEquals(1234, OPTIONS.connectTimeout()); - assertSame(MOCK_HTTP_TRANSPORT_FACTORY, OPTIONS.httpTransportFactory()); - assertEquals(5678, OPTIONS.readTimeout()); - assertEquals(-1, DEFAULT_OPTIONS.connectTimeout()); - assertTrue(DEFAULT_OPTIONS.httpTransportFactory() instanceof DefaultHttpTransportFactory); - assertEquals(-1, DEFAULT_OPTIONS.readTimeout()); + assertEquals(1234, OPTIONS.getConnectTimeout()); + assertSame(MOCK_HTTP_TRANSPORT_FACTORY, OPTIONS.getHttpTransportFactory()); + assertEquals(5678, OPTIONS.getReadTimeout()); + assertEquals(-1, DEFAULT_OPTIONS.getConnectTimeout()); + assertTrue(DEFAULT_OPTIONS.getHttpTransportFactory() instanceof DefaultHttpTransportFactory); + assertEquals(-1, DEFAULT_OPTIONS.getReadTimeout()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(1234, DEPRECATED_OPTIONS.connectTimeout()); + assertSame(MOCK_HTTP_TRANSPORT_FACTORY, DEPRECATED_OPTIONS.httpTransportFactory()); + assertEquals(5678, DEPRECATED_OPTIONS.readTimeout()); + assertEquals(-1, DEPRECATED_DEFAULT_OPTIONS.connectTimeout()); + assertTrue( + DEPRECATED_DEFAULT_OPTIONS.httpTransportFactory() instanceof DefaultHttpTransportFactory); + assertEquals(-1, DEPRECATED_DEFAULT_OPTIONS.readTimeout()); } @Test diff --git a/google-cloud-core/src/test/java/com/google/cloud/IdentityTest.java b/google-cloud-core/src/test/java/com/google/cloud/IdentityTest.java index e720503c547d..5a80daa50da4 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/IdentityTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/IdentityTest.java @@ -33,18 +33,36 @@ public class IdentityTest { @Test public void testAllUsers() { + assertEquals(Identity.Type.ALL_USERS, ALL_USERS.getType()); + assertNull(ALL_USERS.getValue()); + } + + @Test + public void testAllUsersDeprecated() { assertEquals(Identity.Type.ALL_USERS, ALL_USERS.type()); assertNull(ALL_USERS.value()); } @Test public void testAllAuthenticatedUsers() { + assertEquals(Identity.Type.ALL_AUTHENTICATED_USERS, ALL_AUTH_USERS.getType()); + assertNull(ALL_AUTH_USERS.getValue()); + } + + @Test + public void testAllAuthenticatedUsersDeprecated() { assertEquals(Identity.Type.ALL_AUTHENTICATED_USERS, ALL_AUTH_USERS.type()); assertNull(ALL_AUTH_USERS.value()); } @Test public void testUser() { + assertEquals(Identity.Type.USER, USER.getType()); + assertEquals("abc@gmail.com", USER.getValue()); + } + + @Test + public void testUserDeprecated() { assertEquals(Identity.Type.USER, USER.type()); assertEquals("abc@gmail.com", USER.value()); } @@ -56,6 +74,12 @@ public void testUserNullEmail() { @Test public void testServiceAccount() { + assertEquals(Identity.Type.SERVICE_ACCOUNT, SERVICE_ACCOUNT.getType()); + assertEquals("service-account@gmail.com", SERVICE_ACCOUNT.getValue()); + } + + @Test + public void testServiceAccountDeprecated() { assertEquals(Identity.Type.SERVICE_ACCOUNT, SERVICE_ACCOUNT.type()); assertEquals("service-account@gmail.com", SERVICE_ACCOUNT.value()); } @@ -67,6 +91,12 @@ public void testServiceAccountNullEmail() { @Test public void testGroup() { + assertEquals(Identity.Type.GROUP, GROUP.getType()); + assertEquals("group@gmail.com", GROUP.getValue()); + } + + @Test + public void testGroupDeprecated() { assertEquals(Identity.Type.GROUP, GROUP.type()); assertEquals("group@gmail.com", GROUP.value()); } @@ -78,6 +108,12 @@ public void testGroupNullEmail() { @Test public void testDomain() { + assertEquals(Identity.Type.DOMAIN, DOMAIN.getType()); + assertEquals("google.com", DOMAIN.getValue()); + } + + @Test + public void testDomainDeprecated() { assertEquals(Identity.Type.DOMAIN, DOMAIN.type()); assertEquals("google.com", DOMAIN.value()); } @@ -99,7 +135,7 @@ public void testIdentityToAndFromPb() { private void compareIdentities(Identity expected, Identity actual) { assertEquals(expected, actual); - assertEquals(expected.type(), actual.type()); - assertEquals(expected.value(), actual.value()); + assertEquals(expected.getType(), actual.getType()); + assertEquals(expected.getValue(), actual.getValue()); } } diff --git a/google-cloud-core/src/test/java/com/google/cloud/PageImplTest.java b/google-cloud-core/src/test/java/com/google/cloud/PageImplTest.java index 40db43b61da2..2a70b07ac949 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/PageImplTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/PageImplTest.java @@ -31,17 +31,40 @@ public class PageImplTest { .addAll(NEXT_VALUES) .build(); + private static class TestPageFetcher implements PageImpl.NextPageFetcher { + private static final long serialVersionUID = -8316752901403429976L; + + private final PageImpl nextResult; + + TestPageFetcher(PageImpl nextResult) { + this.nextResult = nextResult; + } + + @Override + public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { + return nextResult; + } + } + @Test public void testPage() { final PageImpl nextResult = new PageImpl<>(null, "c", NEXT_VALUES); - PageImpl.NextPageFetcher fetcher = new PageImpl.NextPageFetcher() { - private static final long serialVersionUID = -1714571149183431798L; - - @Override - public PageImpl nextPage() { - return nextResult; - } - }; + PageImpl.NextPageFetcher fetcher = new TestPageFetcher(nextResult); + PageImpl result = new PageImpl<>(fetcher, "c", VALUES); + assertEquals(nextResult, result.getNextPage()); + assertEquals("c", result.getNextPageCursor()); + assertEquals(VALUES, result.getValues()); + } + + @Test + public void testPageDeprecated() { + final PageImpl nextResult = new PageImpl<>(null, "c", NEXT_VALUES); + PageImpl.NextPageFetcher fetcher = new TestPageFetcher(nextResult); PageImpl result = new PageImpl<>(fetcher, "c", VALUES); assertEquals(nextResult, result.nextPage()); assertEquals("c", result.nextPageCursor()); @@ -51,12 +74,7 @@ public PageImpl nextPage() { @Test public void testIterateAll() { final PageImpl nextResult = new PageImpl<>(null, "c", NEXT_VALUES); - PageImpl.NextPageFetcher fetcher = new PageImpl.NextPageFetcher() { - @Override - public PageImpl nextPage() { - return nextResult; - } - }; + PageImpl.NextPageFetcher fetcher = new TestPageFetcher(nextResult); PageImpl result = new PageImpl<>(fetcher, "c", VALUES); assertEquals(ALL_VALUES, ImmutableList.copyOf(result.iterateAll())); } diff --git a/google-cloud-core/src/test/java/com/google/cloud/PolicyTest.java b/google-cloud-core/src/test/java/com/google/cloud/PolicyTest.java index 946c5584d5db..29583e64827a 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/PolicyTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/PolicyTest.java @@ -51,31 +51,78 @@ public class PolicyTest { ImmutableSet.of(USER, SERVICE_ACCOUNT, ALL_USERS), EDITOR, ImmutableSet.of(ALL_AUTH_USERS, GROUP, DOMAIN)); - private static final Policy SIMPLE_POLICY = Policy.builder() + private static final Policy SIMPLE_POLICY = Policy.newBuilder() .addIdentity(VIEWER, USER, SERVICE_ACCOUNT, ALL_USERS) .addIdentity(EDITOR, ALL_AUTH_USERS, GROUP, DOMAIN) .build(); - private static final Policy FULL_POLICY = Policy.builder() - .bindings(SIMPLE_POLICY.bindings()) + private static final Policy DEPRECATED_SIMPLE_POLICY = Policy.builder() + .addIdentity(VIEWER, USER, SERVICE_ACCOUNT, ALL_USERS) + .addIdentity(EDITOR, ALL_AUTH_USERS, GROUP, DOMAIN) + .build(); + private static final Policy FULL_POLICY = Policy.newBuilder() + .setBindings(SIMPLE_POLICY.getBindings()) + .setEtag("etag") + .setVersion(1) + .build(); + private static final Policy DEPRECATED_FULL_POLICY = Policy.builder() + .bindings(SIMPLE_POLICY.getBindings()) .etag("etag") .version(1) .build(); @Test public void testBuilder() { - assertEquals(BINDINGS, SIMPLE_POLICY.bindings()); - assertEquals(null, SIMPLE_POLICY.etag()); - assertEquals(0, SIMPLE_POLICY.version()); - assertEquals(BINDINGS, FULL_POLICY.bindings()); - assertEquals("etag", FULL_POLICY.etag()); - assertEquals(1, FULL_POLICY.version()); + assertEquals(BINDINGS, SIMPLE_POLICY.getBindings()); + assertEquals(null, SIMPLE_POLICY.getEtag()); + assertEquals(0, SIMPLE_POLICY.getVersion()); + assertEquals(BINDINGS, FULL_POLICY.getBindings()); + assertEquals("etag", FULL_POLICY.getEtag()); + assertEquals(1, FULL_POLICY.getVersion()); Map> editorBinding = ImmutableMap.>builder().put(EDITOR, BINDINGS.get(EDITOR)).build(); - Policy policy = FULL_POLICY.toBuilder().bindings(editorBinding).build(); + Policy policy = FULL_POLICY.toBuilder().setBindings(editorBinding).build(); + assertEquals(editorBinding, policy.getBindings()); + assertEquals("etag", policy.getEtag()); + assertEquals(1, policy.getVersion()); + policy = SIMPLE_POLICY.toBuilder().removeRole(EDITOR).build(); + assertEquals(ImmutableMap.of(VIEWER, BINDINGS.get(VIEWER)), policy.getBindings()); + assertNull(policy.getEtag()); + assertEquals(0, policy.getVersion()); + policy = policy.toBuilder() + .removeIdentity(VIEWER, USER, ALL_USERS) + .addIdentity(VIEWER, DOMAIN, GROUP) + .build(); + assertEquals(ImmutableMap.of(VIEWER, ImmutableSet.of(SERVICE_ACCOUNT, DOMAIN, GROUP)), + policy.getBindings()); + assertNull(policy.getEtag()); + assertEquals(0, policy.getVersion()); + policy = Policy.newBuilder() + .removeIdentity(VIEWER, USER) + .addIdentity(OWNER, USER, SERVICE_ACCOUNT) + .addIdentity(EDITOR, GROUP) + .removeIdentity(EDITOR, GROUP) + .build(); + assertEquals(ImmutableMap.of(OWNER, ImmutableSet.of(USER, SERVICE_ACCOUNT)), + policy.getBindings()); + assertNull(policy.getEtag()); + assertEquals(0, policy.getVersion()); + } + + @Test + public void testBuilderDeprecated() { + assertEquals(BINDINGS, DEPRECATED_SIMPLE_POLICY.bindings()); + assertEquals(null, DEPRECATED_SIMPLE_POLICY.etag()); + assertEquals(0, DEPRECATED_SIMPLE_POLICY.version()); + assertEquals(BINDINGS, DEPRECATED_FULL_POLICY.bindings()); + assertEquals("etag", DEPRECATED_FULL_POLICY.etag()); + assertEquals(1, DEPRECATED_FULL_POLICY.version()); + Map> editorBinding = + ImmutableMap.>builder().put(EDITOR, BINDINGS.get(EDITOR)).build(); + Policy policy = DEPRECATED_FULL_POLICY.toBuilder().bindings(editorBinding).build(); assertEquals(editorBinding, policy.bindings()); assertEquals("etag", policy.etag()); assertEquals(1, policy.version()); - policy = SIMPLE_POLICY.toBuilder().removeRole(EDITOR).build(); + policy = DEPRECATED_SIMPLE_POLICY.toBuilder().removeRole(EDITOR).build(); assertEquals(ImmutableMap.of(VIEWER, BINDINGS.get(VIEWER)), policy.bindings()); assertNull(policy.etag()); assertEquals(0, policy.version()); @@ -101,25 +148,25 @@ public void testBuilder() { @Test public void testIllegalPolicies() { try { - Policy.builder().addIdentity(null, USER); + Policy.newBuilder().addIdentity(null, USER); fail("Null role should cause exception."); } catch (NullPointerException ex) { assertEquals("The role cannot be null.", ex.getMessage()); } try { - Policy.builder().addIdentity(VIEWER, null, USER); + Policy.newBuilder().addIdentity(VIEWER, null, USER); fail("Null identity should cause exception."); } catch (NullPointerException ex) { assertEquals("Null identities are not permitted.", ex.getMessage()); } try { - Policy.builder().addIdentity(VIEWER, USER, (Identity[]) null); + Policy.newBuilder().addIdentity(VIEWER, USER, (Identity[]) null); fail("Null identity should cause exception."); } catch (NullPointerException ex) { assertEquals("Null identities are not permitted.", ex.getMessage()); } try { - Policy.builder().bindings(null); + Policy.newBuilder().setBindings(null); fail("Null bindings map should cause exception."); } catch (NullPointerException ex) { assertEquals("The provided map of bindings cannot be null.", ex.getMessage()); @@ -127,7 +174,7 @@ public void testIllegalPolicies() { try { Map> bindings = new HashMap<>(); bindings.put(VIEWER, null); - Policy.builder().bindings(bindings); + Policy.newBuilder().setBindings(bindings); fail("Null set of identities should cause exception."); } catch (NullPointerException ex) { assertEquals("A role cannot be assigned to a null set of identities.", ex.getMessage()); @@ -137,7 +184,7 @@ public void testIllegalPolicies() { Set identities = new HashSet<>(); identities.add(null); bindings.put(VIEWER, identities); - Policy.builder().bindings(bindings); + Policy.newBuilder().setBindings(bindings); fail("Null identity should cause exception."); } catch (IllegalArgumentException ex) { assertEquals("Null identities are not permitted.", ex.getMessage()); @@ -147,8 +194,8 @@ public void testIllegalPolicies() { @Test public void testEqualsHashCode() { assertNotNull(FULL_POLICY); - Policy emptyPolicy = Policy.builder().build(); - Policy anotherPolicy = Policy.builder().build(); + Policy emptyPolicy = Policy.newBuilder().build(); + Policy anotherPolicy = Policy.newBuilder().build(); assertEquals(emptyPolicy, anotherPolicy); assertEquals(emptyPolicy.hashCode(), anotherPolicy.hashCode()); assertNotEquals(FULL_POLICY, SIMPLE_POLICY); @@ -160,33 +207,33 @@ public void testEqualsHashCode() { @Test public void testBindings() { - assertTrue(Policy.builder().build().bindings().isEmpty()); - assertEquals(BINDINGS, SIMPLE_POLICY.bindings()); + assertTrue(Policy.newBuilder().build().getBindings().isEmpty()); + assertEquals(BINDINGS, SIMPLE_POLICY.getBindings()); } @Test public void testEtag() { - assertNull(SIMPLE_POLICY.etag()); - assertEquals("etag", FULL_POLICY.etag()); + assertNull(SIMPLE_POLICY.getEtag()); + assertEquals("etag", FULL_POLICY.getEtag()); } @Test public void testVersion() { - assertEquals(0, SIMPLE_POLICY.version()); - assertEquals(1, FULL_POLICY.version()); + assertEquals(0, SIMPLE_POLICY.getVersion()); + assertEquals(1, FULL_POLICY.getVersion()); } @Test public void testDefaultMarshaller() { DefaultMarshaller marshaller = new DefaultMarshaller(); - Policy emptyPolicy = Policy.builder().build(); + Policy emptyPolicy = Policy.newBuilder().build(); assertEquals(emptyPolicy, marshaller.fromPb(marshaller.toPb(emptyPolicy))); assertEquals(SIMPLE_POLICY, marshaller.fromPb(marshaller.toPb(SIMPLE_POLICY))); assertEquals(FULL_POLICY, marshaller.fromPb(marshaller.toPb(FULL_POLICY))); com.google.iam.v1.Policy policyPb = com.google.iam.v1.Policy.getDefaultInstance(); Policy policy = marshaller.fromPb(policyPb); - assertTrue(policy.bindings().isEmpty()); - assertNull(policy.etag()); - assertEquals(0, policy.version()); + assertTrue(policy.getBindings().isEmpty()); + assertNull(policy.getEtag()); + assertEquals(0, policy.getVersion()); } } diff --git a/google-cloud-core/src/test/java/com/google/cloud/RetryHelperTest.java b/google-cloud-core/src/test/java/com/google/cloud/RetryHelperTest.java index fcb404a4624f..987cf1daa144 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/RetryHelperTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/RetryHelperTest.java @@ -58,6 +58,51 @@ static class E4Exception extends E2Exception { @Test public void testTriesWithExceptionHandling() { + assertNull(RetryHelper.getContext()); + RetryParams params = + RetryParams.newBuilder().setInitialRetryDelayMillis(0).setRetryMaxAttempts(3).build(); + ExceptionHandler handler = ExceptionHandler.newBuilder() + .retryOn(IOException.class).abortOn(RuntimeException.class).build(); + final AtomicInteger count = new AtomicInteger(3); + try { + RetryHelper.runWithRetries(new Callable() { + @Override public Void call() throws IOException, NullPointerException { + if (count.decrementAndGet() == 2) { + assertEquals(1, RetryHelper.getContext().getAttemptNumber()); + throw new IOException("should be retried"); + } + assertEquals(2, RetryHelper.getContext().getAttemptNumber()); + throw new NullPointerException("Boo!"); + } + }, params, handler); + fail("Exception should have been thrown"); + } catch (NonRetriableException ex) { + assertEquals("Boo!", ex.getCause().getMessage()); + assertEquals(1, count.intValue()); + } + assertNull(RetryHelper.getContext()); + + params = RetryParams.newBuilder().setInitialRetryDelayMillis(0).setRetryMaxAttempts(5).build(); + handler = ExceptionHandler.newBuilder() + .retryOn(E1Exception.class, E4Exception.class) + .abortOn(E3Exception.class).build(); + final Iterator exceptions = Arrays.asList( + new E1Exception(), new E2Exception(), new E4Exception(), new E3Exception()).iterator(); + try { + RetryHelper.runWithRetries(new Callable() { + @Override public Void call() throws E1Exception { + throw exceptions.next(); + } + }, params, handler); + fail("Exception should have been thrown"); + } catch (NonRetriableException ex) { + assertTrue(ex.getCause() instanceof E3Exception); + } + assertNull(RetryHelper.getContext()); + } + + @Test + public void testTriesWithExceptionHandlingDeprecated() { assertNull(RetryHelper.getContext()); RetryParams params = RetryParams.builder().initialRetryDelayMillis(0).retryMaxAttempts(3).build(); @@ -103,6 +148,32 @@ public void testTriesWithExceptionHandling() { @Test public void testTriesAtLeastMinTimes() { + // Total retry period set to 60 seconds so as to not factor into test + RetryParams params = RetryParams.newBuilder().setInitialRetryDelayMillis(0) + .setTotalRetryPeriodMillis(60000) + .setRetryMinAttempts(5) + .setRetryMaxAttempts(10) + .build(); + final int timesToFail = 7; + assertNull(RetryHelper.getContext()); + int attempted = RetryHelper.runWithRetries(new Callable() { + int timesCalled; + @Override public Integer call() throws IOException { + timesCalled++; + assertEquals(timesCalled, RetryHelper.getContext().getAttemptNumber()); + assertEquals(10, RetryHelper.getContext().getRetryParams().getRetryMaxAttempts()); + if (timesCalled <= timesToFail) { + throw new IOException(); + } + return timesCalled; + } + }, params, ExceptionHandler.getDefaultInstance()); + assertEquals(timesToFail + 1, attempted); + assertNull(RetryHelper.getContext()); + } + + @Test + public void testTriesAtLeastMinTimesDeprecated() { // Total retry period set to 60 seconds so as to not factor into test RetryParams params = RetryParams.builder().initialRetryDelayMillis(0) .totalRetryPeriodMillis(60000) @@ -129,6 +200,34 @@ public void testTriesAtLeastMinTimes() { @Test public void testTriesNoMoreThanMaxTimes() { + // Total retry period set to 60 seconds so as to not factor into test + final int maxAttempts = 10; + RetryParams params = RetryParams.newBuilder().setInitialRetryDelayMillis(0) + .setTotalRetryPeriodMillis(60000) + .setRetryMinAttempts(0) + .setRetryMaxAttempts(maxAttempts) + .build(); + final AtomicInteger timesCalled = new AtomicInteger(0); + try { + RetryHelper.runWithRetries(callable(new Runnable() { + @Override public void run() { + // Throw an exception up to maxAttempts times, should never be called beyond that + if (timesCalled.incrementAndGet() <= maxAttempts) { + throw new RuntimeException(); + } + fail("Body was executed too many times: " + timesCalled.get()); + } + }), params, ExceptionHandler.newBuilder().retryOn(RuntimeException.class).build()); + // Unnecessary as this line should not be possible reach even if RetryHandler is broken + fail("Should not have succeeded, expected all attempts to fail and give up."); + } catch (RetriesExhaustedException expected) { + // Expect the body to run exactly maxAttempts times + assertEquals(maxAttempts, timesCalled.get()); + } + } + + @Test + public void testTriesNoMoreThanMaxTimesDeprecated() { // Total retry period set to 60 seconds so as to not factor into test final int maxAttempts = 10; RetryParams params = RetryParams.builder().initialRetryDelayMillis(0) @@ -175,12 +274,12 @@ public void testTriesNoMoreLongerThanTotalRetryPeriod() { final FakeClock fakeClock = new FakeClock(); // The 8th attempt (after min and before max) will trigger a 1 second (virtual) delay exceeding // total retry period which is set just under 1 second. Test occurs faster than realtime. - RetryParams params = RetryParams.builder().initialRetryDelayMillis(0) - .totalRetryPeriodMillis(999) - .retryMinAttempts(5) - .retryMaxAttempts(10) + RetryParams params = RetryParams.newBuilder().setInitialRetryDelayMillis(0) + .setTotalRetryPeriodMillis(999) + .setRetryMinAttempts(5) + .setRetryMaxAttempts(10) .build(); - ExceptionHandler handler = ExceptionHandler.builder().retryOn(RuntimeException.class).build(); + ExceptionHandler handler = ExceptionHandler.newBuilder().retryOn(RuntimeException.class).build(); final int sleepOnAttempt = 8; final AtomicInteger timesCalled = new AtomicInteger(0); try { @@ -203,13 +302,13 @@ public void testTriesNoMoreLongerThanTotalRetryPeriod() { @Test public void testBackoffIsExponential() { // Total retry period set to 60 seconds so as to not factor into test - RetryParams params = RetryParams.builder() - .initialRetryDelayMillis(10) - .maxRetryDelayMillis(10_000_000) - .retryDelayBackoffFactor(2) - .totalRetryPeriodMillis(60_000) - .retryMinAttempts(0) - .retryMaxAttempts(100) + RetryParams params = RetryParams.newBuilder() + .setInitialRetryDelayMillis(10) + .setMaxRetryDelayMillis(10_000_000) + .setRetryDelayBackoffFactor(2) + .setTotalRetryPeriodMillis(60_000) + .setRetryMinAttempts(0) + .setRetryMaxAttempts(100) .build(); long sleepDuration = RetryHelper.getSleepDuration(params, 1); assertTrue(String.valueOf(sleepDuration), sleepDuration < 13 && sleepDuration >= 7); diff --git a/google-cloud-core/src/test/java/com/google/cloud/RetryParamsTest.java b/google-cloud-core/src/test/java/com/google/cloud/RetryParamsTest.java index c3041053110b..c96358042932 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/RetryParamsTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/RetryParamsTest.java @@ -41,6 +41,20 @@ public class RetryParamsTest { @Test public void testDefaults() { + RetryParams params1 = RetryParams.getDefaultInstance(); + RetryParams params2 = RetryParams.newBuilder().build(); + for (RetryParams params : Arrays.asList(params1, params2)) { + assertEquals(DEFAULT_INITIAL_RETRY_DELAY_MILLIS, params.getInitialRetryDelayMillis()); + assertEquals(DEFAULT_MAX_RETRY_DELAY_MILLIS, params.getMaxRetryDelayMillis()); + assertEquals(DEFAULT_RETRY_DELAY_BACKOFF_FACTOR, params.getRetryDelayBackoffFactor(), 0); + assertEquals(DEFAULT_RETRY_MAX_ATTEMPTS, params.getRetryMaxAttempts()); + assertEquals(DEFAULT_RETRY_MIN_ATTEMPTS, params.getRetryMinAttempts()); + assertEquals(DEFAULT_TOTAL_RETRY_PERIOD_MILLIS, params.getTotalRetryPeriodMillis()); + } + } + + @Test + public void testDefaultsDeprecated() { RetryParams params1 = RetryParams.defaultInstance(); RetryParams params2 = RetryParams.builder().build(); for (RetryParams params : Arrays.asList(params1, params2)) { @@ -55,6 +69,27 @@ public void testDefaults() { @Test public void testSetAndCopy() { + RetryParams.Builder builder = RetryParams.newBuilder(); + builder.setInitialRetryDelayMillis(101); + builder.setMaxRetryDelayMillis(102); + builder.setRetryDelayBackoffFactor(103); + builder.setRetryMinAttempts(107); + builder.setRetryMaxAttempts(108); + builder.setTotalRetryPeriodMillis(109); + RetryParams params1 = builder.build(); + RetryParams params2 = new RetryParams.Builder(params1).build(); + for (RetryParams params : Arrays.asList(params1, params2)) { + assertEquals(101, params.getInitialRetryDelayMillis()); + assertEquals(102, params.getMaxRetryDelayMillis()); + assertEquals(103, params.getRetryDelayBackoffFactor(), 0); + assertEquals(107, params.getRetryMinAttempts()); + assertEquals(108, params.getRetryMaxAttempts()); + assertEquals(109, params.getTotalRetryPeriodMillis()); + } + } + + @Test + public void testSetAndCopyDeprecated() { RetryParams.Builder builder = RetryParams.builder(); builder.initialRetryDelayMillis(101); builder.maxRetryDelayMillis(102); @@ -76,22 +111,23 @@ public void testSetAndCopy() { @Test public void testBadSettings() { - RetryParams.Builder builder = RetryParams.builder(); - builder.initialRetryDelayMillis(-1); + RetryParams.Builder builder = RetryParams.newBuilder(); + builder.setInitialRetryDelayMillis(-1); builder = assertFailure(builder); - builder.maxRetryDelayMillis(RetryParams.defaultInstance().initialRetryDelayMillis() - 1); + builder.setMaxRetryDelayMillis( + RetryParams.getDefaultInstance().getInitialRetryDelayMillis() - 1); builder = assertFailure(builder); - builder.retryDelayBackoffFactor(-1); + builder.setRetryDelayBackoffFactor(-1); builder = assertFailure(builder); - builder.retryMinAttempts(-1); + builder.setRetryMinAttempts(-1); builder = assertFailure(builder); - builder.retryMaxAttempts(RetryParams.defaultInstance().retryMinAttempts() - 1); + builder.setRetryMaxAttempts(RetryParams.getDefaultInstance().getRetryMinAttempts() - 1); builder = assertFailure(builder); - builder.totalRetryPeriodMillis(-1); + builder.setTotalRetryPeriodMillis(-1); builder = assertFailure(builder); // verify that it is OK for min and max to be equal - builder.retryMaxAttempts(RetryParams.defaultInstance().retryMinAttempts()); - builder.maxRetryDelayMillis(RetryParams.defaultInstance().initialRetryDelayMillis()); + builder.setRetryMaxAttempts(RetryParams.getDefaultInstance().getRetryMinAttempts()); + builder.setMaxRetryDelayMillis(RetryParams.getDefaultInstance().getInitialRetryDelayMillis()); builder.build(); } @@ -102,6 +138,6 @@ private static Builder assertFailure(Builder builder) { } catch (IllegalArgumentException ex) { // expected } - return RetryParams.builder(); + return RetryParams.newBuilder(); } } diff --git a/google-cloud-core/src/test/java/com/google/cloud/RoleTest.java b/google-cloud-core/src/test/java/com/google/cloud/RoleTest.java index c66c28a9523a..7cce4ee4fbc2 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/RoleTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/RoleTest.java @@ -28,6 +28,16 @@ public class RoleTest { @Test public void testOf() { + assertEquals("roles/viewer", VIEWER.getValue()); + assertEquals("roles/editor", EDITOR.getValue()); + assertEquals("roles/owner", OWNER.getValue()); + compareRoles(VIEWER, Role.of("roles/viewer")); + compareRoles(EDITOR, Role.of("roles/editor")); + compareRoles(OWNER, Role.of("roles/owner")); + } + + @Test + public void testOfDeprecated() { assertEquals("roles/viewer", VIEWER.value()); assertEquals("roles/editor", EDITOR.value()); assertEquals("roles/owner", OWNER.value()); @@ -38,17 +48,17 @@ public void testOf() { @Test public void testViewer() { - assertEquals("roles/viewer", Role.viewer().value()); + assertEquals("roles/viewer", Role.viewer().getValue()); } @Test public void testEditor() { - assertEquals("roles/editor", Role.editor().value()); + assertEquals("roles/editor", Role.editor().getValue()); } @Test public void testOwner() { - assertEquals("roles/owner", Role.owner().value()); + assertEquals("roles/owner", Role.owner().getValue()); } @Test(expected = NullPointerException.class) @@ -58,7 +68,7 @@ public void testOfNullValue() { private void compareRoles(Role expected, Role actual) { assertEquals(expected, actual); - assertEquals(expected.value(), actual.value()); + assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.hashCode(), actual.hashCode()); assertEquals(expected.toString(), actual.toString()); } diff --git a/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java b/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java index ba3194c20371..746f2b406b13 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/SerializationTest.java @@ -32,15 +32,15 @@ public class SerializationTest extends BaseSerializationTest { private static final BaseServiceException BASE_SERVICE_EXCEPTION = new BaseServiceException(42, "message", "reason", true); - private static final ExceptionHandler EXCEPTION_HANDLER = ExceptionHandler.defaultInstance(); + private static final ExceptionHandler EXCEPTION_HANDLER = ExceptionHandler.getDefaultInstance(); private static final Identity IDENTITY = Identity.allAuthenticatedUsers(); private static final PageImpl PAGE = new PageImpl<>(null, "cursor", ImmutableList.of("string1", "string2")); private static final SigningException SIGNING_EXCEPTION = new SigningException("message", BASE_SERVICE_EXCEPTION); - private static final RetryParams RETRY_PARAMS = RetryParams.defaultInstance(); + private static final RetryParams RETRY_PARAMS = RetryParams.getDefaultInstance(); private static final Role SOME_ROLE = Role.viewer(); - private static final Policy SOME_IAM_POLICY = Policy.builder().build(); + private static final Policy SOME_IAM_POLICY = Policy.newBuilder().build(); private static final WaitForOption CHECKING_PERIOD = WaitForOption.checkEvery(42, TimeUnit.SECONDS); private static final LabelDescriptor LABEL_DESCRIPTOR = diff --git a/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java b/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java index 7792c63e821b..e7e74459d18c 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/ServiceOptionsTest.java @@ -71,7 +71,15 @@ public class ServiceOptionsTest { } private static final Clock TEST_CLOCK = new TestClock(); private static final TestServiceOptions OPTIONS = - TestServiceOptions.builder() + TestServiceOptions.newBuilder() + .setAuthCredentials(authCredentials) + .setClock(TEST_CLOCK) + .setHost("host") + .setProjectId("project-id") + .setRetryParams(RetryParams.noRetries()) + .build(); + private static final TestServiceOptions DEPRECATED_OPTIONS = + TestServiceOptions.newBuilder() .authCredentials(authCredentials) .clock(TEST_CLOCK) .host("host") @@ -79,7 +87,9 @@ public class ServiceOptionsTest { .retryParams(RetryParams.noRetries()) .build(); private static final TestServiceOptions DEFAULT_OPTIONS = - TestServiceOptions.builder().projectId("project-id").build(); + TestServiceOptions.newBuilder().setProjectId("project-id").build(); + private static final TestServiceOptions DEPRECATED_DEFAULT_OPTIONS = + TestServiceOptions.newBuilder().projectId("project-id").build(); private static final TestServiceOptions OPTIONS_COPY = OPTIONS.toBuilder().build(); private static final String LIBRARY_NAME = "gcloud-java"; private static final Pattern APPLICATION_NAME_PATTERN = @@ -151,17 +161,17 @@ private TestServiceOptions(Builder builder) { } @Override - protected TestServiceFactory defaultServiceFactory() { + protected TestServiceFactory getDefaultServiceFactory() { return DefaultTestServiceFactory.INSTANCE; } @Override - protected TestServiceRpcFactory defaultRpcFactory() { + protected TestServiceRpcFactory getDefaultRpcFactory() { return DefaultTestServiceRpcFactory.INSTANCE; } @Override - protected Set scopes() { + protected Set getScopes() { return null; } @@ -170,7 +180,7 @@ public Builder toBuilder() { return new Builder(this); } - private static Builder builder() { + private static Builder newBuilder() { return new Builder(); } @@ -187,14 +197,26 @@ public int hashCode() { @Test public void testBuilder() { - assertSame(authCredentials, OPTIONS.authCredentials()); - assertSame(TEST_CLOCK, OPTIONS.clock()); - assertEquals("host", OPTIONS.host()); - assertEquals("project-id", OPTIONS.projectId()); - assertSame(RetryParams.noRetries(), OPTIONS.retryParams()); - assertSame(Clock.defaultClock(), DEFAULT_OPTIONS.clock()); - assertEquals("https://www.googleapis.com", DEFAULT_OPTIONS.host()); - assertSame(RetryParams.defaultInstance(), DEFAULT_OPTIONS.retryParams()); + assertSame(authCredentials, OPTIONS.getAuthCredentials()); + assertSame(TEST_CLOCK, OPTIONS.getClock()); + assertEquals("host", OPTIONS.getHost()); + assertEquals("project-id", OPTIONS.getProjectId()); + assertSame(RetryParams.noRetries(), OPTIONS.getRetryParams()); + assertSame(Clock.defaultClock(), DEFAULT_OPTIONS.getClock()); + assertEquals("https://www.googleapis.com", DEFAULT_OPTIONS.getHost()); + assertSame(RetryParams.getDefaultInstance(), DEFAULT_OPTIONS.getRetryParams()); + } + + @Test + public void testBuilderDeprecated() { + assertSame(authCredentials, DEPRECATED_OPTIONS.authCredentials()); + assertSame(TEST_CLOCK, DEPRECATED_OPTIONS.clock()); + assertEquals("host", DEPRECATED_OPTIONS.host()); + assertEquals("project-id", DEPRECATED_OPTIONS.projectId()); + assertSame(RetryParams.noRetries(), DEPRECATED_OPTIONS.retryParams()); + assertSame(Clock.defaultClock(), DEPRECATED_DEFAULT_OPTIONS.clock()); + assertEquals("https://www.googleapis.com", DEPRECATED_DEFAULT_OPTIONS.host()); + assertSame(RetryParams.getDefaultInstance(), DEPRECATED_DEFAULT_OPTIONS.retryParams()); } @Test @@ -204,12 +226,12 @@ public void testGetProjectIdRequired() { @Test public void testService() { - assertTrue(OPTIONS.service() instanceof TestServiceImpl); + assertTrue(OPTIONS.getService() instanceof TestServiceImpl); } @Test public void testRpc() { - assertTrue(OPTIONS.rpc() instanceof DefaultTestServiceRpc); + assertTrue(OPTIONS.getRpc() instanceof DefaultTestServiceRpc); } @Test @@ -220,12 +242,12 @@ public void testBaseEquals() { @Test public void testLibraryName() { - assertEquals(LIBRARY_NAME, OPTIONS.libraryName()); + assertEquals(LIBRARY_NAME, OPTIONS.getLibraryName()); } @Test public void testApplicationName() { - assertTrue(APPLICATION_NAME_PATTERN.matcher(OPTIONS.applicationName()).matches()); + assertTrue(APPLICATION_NAME_PATTERN.matcher(OPTIONS.getApplicationName()).matches()); } @Test diff --git a/google-cloud-core/src/test/java/com/google/cloud/WaitForOptionTest.java b/google-cloud-core/src/test/java/com/google/cloud/WaitForOptionTest.java index 82996e1ca3f8..959b086aed20 100644 --- a/google-cloud-core/src/test/java/com/google/cloud/WaitForOptionTest.java +++ b/google-cloud-core/src/test/java/com/google/cloud/WaitForOptionTest.java @@ -40,7 +40,14 @@ public class WaitForOptionTest { @Test public void testCheckEvery() { - assertEquals(OptionType.CHECKING_PERIOD, CHECKING_PERIOD_OPTION.optionType()); + assertEquals(OptionType.CHECKING_PERIOD, CHECKING_PERIOD_OPTION.getOptionType()); + assertEquals(42, CHECKING_PERIOD_OPTION.getPeriod()); + assertEquals(TimeUnit.MILLISECONDS, CHECKING_PERIOD_OPTION.getUnit()); + } + + @Test + public void testCheckEveryDeprecated() { + assertEquals(OptionType.CHECKING_PERIOD, CHECKING_PERIOD_OPTION.getOptionType()); assertEquals(42, CHECKING_PERIOD_OPTION.period()); assertEquals(TimeUnit.MILLISECONDS, CHECKING_PERIOD_OPTION.unit()); } @@ -53,8 +60,8 @@ public void testCheckEvery_InvalidPeriod() { } @Test - public void testTimeout() { - assertEquals(OptionType.TIMEOUT, TIMEOUT_OPTION.optionType()); + public void testTimeoutDeprecated() { + assertEquals(OptionType.TIMEOUT, TIMEOUT_OPTION.getOptionType()); assertEquals(43, TIMEOUT_OPTION.timeoutMillis()); Timeout timeoutOption = WaitForOption.timeout(43, TimeUnit.SECONDS); assertEquals(43_000, timeoutOption.timeoutMillis()); @@ -102,10 +109,10 @@ public void testGetOrDefault() { assertEquals(TIMEOUT_OPTION, Timeout.getOrDefault(CHECKING_PERIOD_OPTION, TIMEOUT_OPTION)); CheckingPeriod checkingPeriod = CheckingPeriod.getOrDefault(TIMEOUT_OPTION); - assertEquals(500, checkingPeriod.period()); - assertEquals(TimeUnit.MILLISECONDS, checkingPeriod.unit()); + assertEquals(500, checkingPeriod.getPeriod()); + assertEquals(TimeUnit.MILLISECONDS, checkingPeriod.getUnit()); Timeout timeout = Timeout.getOrDefault(CHECKING_PERIOD_OPTION); - assertEquals(-1, timeout.timeoutMillis()); + assertEquals(-1, timeout.getTimeoutMillis()); } @Test diff --git a/google-cloud-datastore/README.md b/google-cloud-datastore/README.md index f4bd23333540..4c979c88a10d 100644 --- a/google-cloud-datastore/README.md +++ b/google-cloud-datastore/README.md @@ -73,7 +73,7 @@ To make authenticated requests to Google Cloud Datastore, you must create a serv import com.google.cloud.datastore.Datastore; import com.google.cloud.datastore.DatastoreOptions; -Datastore datastore = DatastoreOptions.defaultInstance().service(); +Datastore datastore = DatastoreOptions.getDefaultInstance().getService(); ``` For other authentication options, see the [Authentication](https://github.com/GoogleCloudPlatform/google-cloud-java#authentication) page. diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreException.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreException.java index 7ed4e5d3d197..45975730fc04 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreException.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreException.java @@ -57,7 +57,7 @@ public DatastoreException(IOException exception) { } @Override - protected Set retryableErrors() { + protected Set getRetryableErrors() { return RETRYABLE_ERRORS; } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreHelper.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreHelper.java index 957839cf4301..412ff14f2dfb 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreHelper.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreHelper.java @@ -56,7 +56,7 @@ static Entity put(DatastoreWriter writer, FullEntity entity) { } static KeyFactory newKeyFactory(DatastoreOptions options) { - return new KeyFactory(options.projectId(), options.namespace()); + return new KeyFactory(options.getProjectId(), options.getNamespace()); } /** diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreImpl.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreImpl.java index 892d397935df..542b8aa7b853 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreImpl.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreImpl.java @@ -49,8 +49,8 @@ final class DatastoreImpl extends BaseService implements Datas DatastoreImpl(DatastoreOptions options) { super(options); - this.datastoreRpc = options.rpc(); - retryParams = MoreObjects.firstNonNull(options.retryParams(), RetryParams.noRetries()); + this.datastoreRpc = options.getRpc(); + retryParams = MoreObjects.firstNonNull(options.getRetryParams(), RetryParams.noRetries()); } @Override @@ -92,7 +92,7 @@ public com.google.datastore.v1.RunQueryResponse call() throws DatastoreException { return datastoreRpc.runQuery(requestPb); } - }, retryParams, EXCEPTION_HANDLER, options().clock()); + }, retryParams, EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException e) { throw DatastoreException.translateAndThrow(e); } @@ -131,7 +131,7 @@ public com.google.datastore.v1.AllocateIdsResponse call() throws DatastoreException { return datastoreRpc.allocateIds(requestPb); } - }, retryParams, EXCEPTION_HANDLER, options().clock()); + }, retryParams, EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException e) { throw DatastoreException.translateAndThrow(e); } @@ -288,7 +288,7 @@ public com.google.datastore.v1.LookupResponse call() throws DatastoreException { return datastoreRpc.lookup(requestPb); } - }, retryParams, EXCEPTION_HANDLER, options().clock()); + }, retryParams, EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException e) { throw DatastoreException.translateAndThrow(e); } @@ -368,7 +368,7 @@ public void delete(Key... keys) { @Override public KeyFactory newKeyFactory() { - return DatastoreHelper.newKeyFactory(options()); + return DatastoreHelper.newKeyFactory(getOptions()); } private com.google.datastore.v1.CommitResponse commitMutation( @@ -391,7 +391,7 @@ public com.google.datastore.v1.CommitResponse call() throws DatastoreException { } }, retryParams, - EXCEPTION_HANDLER, options().clock()); + EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException e) { throw DatastoreException.translateAndThrow(e); } @@ -414,7 +414,7 @@ public com.google.datastore.v1.BeginTransactionResponse call() } }, retryParams, - EXCEPTION_HANDLER, options().clock()); + EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException e) { throw DatastoreException.translateAndThrow(e); } @@ -434,7 +434,7 @@ void rollback(final com.google.datastore.v1.RollbackRequest requestPb) { datastoreRpc.rollback(requestPb); return null; } - }, retryParams, EXCEPTION_HANDLER, options().clock()); + }, retryParams, EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException e) { throw DatastoreException.translateAndThrow(e); } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreOptions.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreOptions.java index f63892affdaa..214a12d59ce0 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreOptions.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/DatastoreOptions.java @@ -94,19 +94,19 @@ private DatastoreOptions(Builder builder) { } @Override - public HttpRequestInitializer httpRequestInitializer() { - final HttpRequestInitializer delegate = super.httpRequestInitializer(); + public HttpRequestInitializer getHttpRequestInitializer() { + final HttpRequestInitializer delegate = super.getHttpRequestInitializer(); return new HttpRequestInitializer() { @Override public void initialize(HttpRequest httpRequest) throws IOException { delegate.initialize(httpRequest); - httpRequest.getHeaders().setUserAgent(applicationName()); + httpRequest.getHeaders().setUserAgent(getApplicationName()); } }; } @Override - protected String defaultHost() { + protected String getDefaultHost() { String host = System.getProperty( com.google.datastore.v1.client.DatastoreHelper.LOCAL_HOST_ENV_VAR, System.getenv(com.google.datastore.v1.client.DatastoreHelper.LOCAL_HOST_ENV_VAR)); @@ -114,35 +114,51 @@ protected String defaultHost() { } @Override - protected String defaultProject() { + protected String getDefaultProject() { String projectId = System.getProperty( com.google.datastore.v1.client.DatastoreHelper.PROJECT_ID_ENV_VAR, System.getenv(com.google.datastore.v1.client.DatastoreHelper.PROJECT_ID_ENV_VAR)); - return projectId != null ? projectId : super.defaultProject(); + return projectId != null ? projectId : super.getDefaultProject(); } @Override - protected DatastoreFactory defaultServiceFactory() { + protected DatastoreFactory getDefaultServiceFactory() { return DefaultDatastoreFactory.INSTANCE; } @Override - protected DatastoreRpcFactory defaultRpcFactory() { + protected DatastoreRpcFactory getDefaultRpcFactory() { return DefaultDatastoreRpcFactory.INSTANCE; } /** * Returns the default namespace to be used by the datastore service. */ + @Deprecated public String namespace() { + return getNamespace(); + } + + /** + * Returns the default namespace to be used by the datastore service. + */ + public String getNamespace() { return namespace; } /** * Returns a default {@code DatastoreOptions} instance. */ + @Deprecated public static DatastoreOptions defaultInstance() { - return builder().build(); + return getDefaultInstance(); + } + + /** + * Returns a default {@code DatastoreOptions} instance. + */ + public static DatastoreOptions getDefaultInstance() { + return newBuilder().build(); } private static String defaultNamespace() { @@ -158,7 +174,7 @@ private static String defaultNamespace() { } @Override - protected Set scopes() { + protected Set getScopes() { return SCOPES; } @@ -182,7 +198,12 @@ public boolean equals(Object obj) { return baseEquals(other) && Objects.equals(namespace, other.namespace); } + @Deprecated public static Builder builder() { + return newBuilder(); + } + + public static Builder newBuilder() { return new Builder(); } } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/GqlQuery.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/GqlQuery.java index 0dd482e086b4..a736fdb10432 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/GqlQuery.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/GqlQuery.java @@ -412,7 +412,8 @@ public String toString() { @Override public int hashCode() { - return Objects.hash(namespace(), queryString, allowLiteral, namedBindings, positionalBindings); + return Objects.hash(getNamespace(), queryString, allowLiteral, namedBindings, + positionalBindings); } @Override @@ -424,7 +425,7 @@ public boolean equals(Object obj) { return false; } GqlQuery other = (GqlQuery) obj; - return Objects.equals(namespace(), other.namespace()) + return Objects.equals(getNamespace(), other.getNamespace()) && Objects.equals(queryString, other.queryString) && allowLiteral == other.allowLiteral && Objects.equals(namedBindings, other.namedBindings) @@ -452,7 +453,7 @@ void populatePb(com.google.datastore.v1.RunQueryRequest.Builder requestPb) { @Override Query nextQuery(com.google.datastore.v1.RunQueryResponse responsePb) { - return StructuredQuery.fromPb(type(), namespace(), responsePb.getQuery()) + return StructuredQuery.fromPb(getType(), getNamespace(), responsePb.getQuery()) .nextQuery(responsePb); } } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Query.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Query.java index 0e140b18f672..0b8a8d266daf 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Query.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/Query.java @@ -163,11 +163,16 @@ static ResultType fromPb(com.google.datastore.v1.EntityResult.ResultType type this.namespace = namespace; } - ResultType type() { + ResultType getType() { return resultType; } + @Deprecated public String namespace() { + return getNamespace(); + } + + public String getNamespace() { return namespace; } diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/QueryResultsImpl.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/QueryResultsImpl.java index 14124094f04f..f6b001e52bbc 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/QueryResultsImpl.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/QueryResultsImpl.java @@ -44,14 +44,14 @@ class QueryResultsImpl extends AbstractIterator implements QueryResults this.datastore = datastore; this.readOptionsPb = readOptionsPb; this.query = query; - queryResultType = query.type(); + queryResultType = query.getType(); com.google.datastore.v1.PartitionId.Builder pbBuilder = com.google.datastore.v1.PartitionId.newBuilder(); - pbBuilder.setProjectId(datastore.options().projectId()); - if (query.namespace() != null) { - pbBuilder.setNamespaceId(query.namespace()); - } else if (datastore.options().namespace() != null) { - pbBuilder.setNamespaceId(datastore.options().namespace()); + pbBuilder.setProjectId(datastore.getOptions().getProjectId()); + if (query.getNamespace() != null) { + pbBuilder.setNamespaceId(query.getNamespace()); + } else if (datastore.getOptions().getNamespace() != null) { + pbBuilder.setNamespaceId(datastore.getOptions().getNamespace()); } partitionIdPb = pbBuilder.build(); sendRequest(); diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/StructuredQuery.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/StructuredQuery.java index 988a0326d4e2..d21b42f78e25 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/StructuredQuery.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/StructuredQuery.java @@ -680,8 +680,8 @@ abstract static class BuilderImpl> implements Bui } BuilderImpl(StructuredQuery query) { - this(query.type()); - namespace = query.namespace(); + this(query.getType()); + namespace = query.getNamespace(); kind = query.kind; projection.addAll(query.projection); filter = query.filter; @@ -917,8 +917,8 @@ public String toString() { @Override public int hashCode() { - return Objects.hash(namespace(), kind, startCursor, endCursor, offset, limit, filter, orderBy, - projection, distinctOn); + return Objects.hash(getNamespace(), kind, startCursor, endCursor, offset, limit, filter, + orderBy, projection, distinctOn); } @Override @@ -930,7 +930,7 @@ public boolean equals(Object obj) { return false; } StructuredQuery other = (StructuredQuery) obj; - return Objects.equals(namespace(), other.namespace()) + return Objects.equals(getNamespace(), other.getNamespace()) && Objects.equals(kind, other.kind) && Objects.equals(startCursor, other.startCursor) && Objects.equals(endCursor, other.endCursor) diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/package-info.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/package-info.java index 5dcea4433d4e..0a17f9261d4f 100644 --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/package-info.java +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/package-info.java @@ -22,7 +22,7 @@ * * CreateEntity.java. *

     {@code
    - * Datastore datastore = DatastoreOptions.defaultInstance().service();
    + * Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
      * KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind");
      * Key key = keyFactory.newKey("keyName");
      * Entity entity = Entity.newBuilder(key)
    @@ -38,7 +38,7 @@
      * 
      * UpdateEntity.java.
      * 
     {@code
    - * Datastore datastore = DatastoreOptions.defaultInstance().service();
    + * Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
      * KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind");
      * Key key = keyFactory.newKey("keyName");
      * Entity entity = datastore.get(key);
    diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/spi/DefaultDatastoreRpc.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/spi/DefaultDatastoreRpc.java
    index e3647554859e..d31d52370c3a 100644
    --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/spi/DefaultDatastoreRpc.java
    +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/spi/DefaultDatastoreRpc.java
    @@ -41,13 +41,13 @@ public class DefaultDatastoreRpc implements DatastoreRpc {
       private final com.google.datastore.v1.client.Datastore client;
     
       public DefaultDatastoreRpc(DatastoreOptions options) {
    -    HttpTransport transport = options.httpTransportFactory().create();
    +    HttpTransport transport = options.getHttpTransportFactory().create();
         com.google.datastore.v1.client.DatastoreOptions.Builder clientBuilder =
             new com.google.datastore.v1.client.DatastoreOptions.Builder()
    -            .projectId(options.projectId())
    -            .initializer(options.httpRequestInitializer())
    +            .projectId(options.getProjectId())
    +            .initializer(options.getHttpRequestInitializer())
                 .transport(transport);
    -    String normalizedHost = options.host() != null ? options.host().toLowerCase() : "";
    +    String normalizedHost = options.getHost() != null ? options.getHost().toLowerCase() : "";
         if (isLocalHost(normalizedHost)) {
           clientBuilder = clientBuilder.localHost(removeScheme(normalizedHost));
         } else if (!removeScheme(com.google.datastore.v1.client.DatastoreFactory.DEFAULT_HOST)
    @@ -60,7 +60,7 @@ public DefaultDatastoreRpc(DatastoreOptions options) {
           fullUrl = fullUrl
               + com.google.datastore.v1.client.DatastoreFactory.VERSION
               + "/projects/"
    -          + options.projectId();
    +          + options.getProjectId();
           clientBuilder = clientBuilder.projectId(null).projectEndpoint(fullUrl);
         }
         client = com.google.datastore.v1.client.DatastoreFactory.get()
    diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java
    index cf7f47b8c853..d733b4758be7 100644
    --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java
    +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/LocalDatastoreHelper.java
    @@ -637,11 +637,11 @@ private static int findAvailablePort() {
       }
     
       private DatastoreOptions.Builder optionsBuilder() {
    -    return DatastoreOptions.builder()
    -        .projectId(projectId)
    -        .host("localhost:" + Integer.toString(port))
    -        .authCredentials(AuthCredentials.noAuth())
    -        .retryParams(RetryParams.noRetries());
    +    return DatastoreOptions.newBuilder()
    +        .setProjectId(projectId)
    +        .setHost("localhost:" + Integer.toString(port))
    +        .setAuthCredentials(AuthCredentials.noAuth())
    +        .setRetryParams(RetryParams.noRetries());
       }
     
       /**
    diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/RemoteDatastoreHelper.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/RemoteDatastoreHelper.java
    index 8e4febcf4580..723c0005459d 100644
    --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/RemoteDatastoreHelper.java
    +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/RemoteDatastoreHelper.java
    @@ -29,15 +29,16 @@
     /**
      * Utility to create a remote datastore configuration for testing. Datastore options can be obtained
      * via the {@link #getOptions()} method. Returned options use a randomly generated namespace
    - * ({@link DatastoreOptions#namespace()}) that can be used to run the tests. Once the tests are run,
    - * all entities in the namespace can be deleted using {@link #deleteNamespace()}. Returned options
    - * also have custom {@link DatastoreOptions#retryParams()}: {@link RetryParams#retryMaxAttempts()}
    - * is {@code 10}, {@link RetryParams#retryMinAttempts()} is {@code 6},
    - * {@link RetryParams#maxRetryDelayMillis()} is {@code 30000},
    - * {@link RetryParams#totalRetryPeriodMillis()} is {@code 120000} and
    - * {@link RetryParams#initialRetryDelayMillis()} is {@code 250}.
    - * {@link DatastoreOptions#connectTimeout()} and {@link DatastoreOptions#readTimeout()} are both set
    - * to {@code 60000}.
    + * ({@link DatastoreOptions#getNamespace()}) that can be used to run the tests. Once the tests are
    + * run, all entities in the namespace can be deleted using {@link #deleteNamespace()}. Returned
    + * options also have custom {@link DatastoreOptions#getRetryParams()}:
    + * {@link RetryParams#getRetryMaxAttempts()} is {@code 10},
    + * {@link RetryParams#getRetryMinAttempts()} is {@code 6},
    + * {@link RetryParams#getMaxRetryDelayMillis()} is {@code 30000},
    + * {@link RetryParams#getTotalRetryPeriodMillis()} is {@code 120000} and
    + * {@link RetryParams#getInitialRetryDelayMillis()} is {@code 250}.
    + * {@link DatastoreOptions#getConnectTimeout()} and {@link DatastoreOptions#getReadTimeout()} are
    + * both set to {@code 60000}.
      */
     public class RemoteDatastoreHelper {
     
    @@ -47,8 +48,8 @@ public class RemoteDatastoreHelper {
     
       private RemoteDatastoreHelper(DatastoreOptions options) {
         this.options = options;
    -    this.datastore = options.service();
    -    this.namespace = options.namespace();
    +    this.datastore = options.getService();
    +    this.namespace = options.getNamespace();
       }
     
       /**
    @@ -83,22 +84,22 @@ public void deleteNamespace() {
        * Creates a {@code RemoteStorageHelper} object.
        */
       public static RemoteDatastoreHelper create() {
    -    DatastoreOptions datastoreOption = DatastoreOptions.builder()
    +    DatastoreOptions datastoreOption = DatastoreOptions.newBuilder()
             .namespace(UUID.randomUUID().toString())
    -        .retryParams(retryParams())
    -        .connectTimeout(60000)
    -        .readTimeout(60000)
    +        .setRetryParams(retryParams())
    +        .setConnectTimeout(60000)
    +        .setReadTimeout(60000)
             .build();
         return new RemoteDatastoreHelper(datastoreOption);
       }
     
       private static RetryParams retryParams() {
    -    return RetryParams.builder()
    -        .retryMaxAttempts(10)
    -        .retryMinAttempts(6)
    -        .maxRetryDelayMillis(30000)
    -        .totalRetryPeriodMillis(120000)
    -        .initialRetryDelayMillis(250)
    +    return RetryParams.newBuilder()
    +        .setRetryMaxAttempts(10)
    +        .setRetryMinAttempts(6)
    +        .setMaxRetryDelayMillis(30000)
    +        .setTotalRetryPeriodMillis(120000)
    +        .setInitialRetryDelayMillis(250)
             .build();
       }
     }
    diff --git a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/package-info.java b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/package-info.java
    index 3000b96f3f4e..a964aaa466cc 100644
    --- a/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/package-info.java
    +++ b/google-cloud-datastore/src/main/java/com/google/cloud/datastore/testing/package-info.java
    @@ -22,7 +22,7 @@
      * 
     {@code
      * LocalDatastoreHelper helper = LocalDatastoreHelper.create();
      * helper.start();
    - * Datastore localDatastore = helper.getOptions().service();
    + * Datastore localDatastore = helper.getOptions().getService();
      * } 
    * *

    After the test: diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreExceptionTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreExceptionTest.java index 0da45f083210..63691d9d3e71 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreExceptionTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreExceptionTest.java @@ -40,49 +40,49 @@ public class DatastoreExceptionTest { @Test public void testDatastoreException() throws Exception { DatastoreException exception = new DatastoreException(10, "message", "ABORTED"); - assertEquals(10, exception.code()); - assertEquals("ABORTED", exception.reason()); + assertEquals(10, exception.getCode()); + assertEquals("ABORTED", exception.getReason()); assertEquals("message", exception.getMessage()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new DatastoreException(4, "message", "DEADLINE_EXCEEDED"); - assertEquals(4, exception.code()); - assertEquals("DEADLINE_EXCEEDED", exception.reason()); + assertEquals(4, exception.getCode()); + assertEquals("DEADLINE_EXCEEDED", exception.getReason()); assertEquals("message", exception.getMessage()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new DatastoreException(14, "message", "UNAVAILABLE"); - assertEquals(14, exception.code()); - assertEquals("UNAVAILABLE", exception.reason()); + assertEquals(14, exception.getCode()); + assertEquals("UNAVAILABLE", exception.getReason()); assertEquals("message", exception.getMessage()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new DatastoreException(2, "message", "INTERNAL"); - assertEquals(2, exception.code()); - assertEquals("INTERNAL", exception.reason()); + assertEquals(2, exception.getCode()); + assertEquals("INTERNAL", exception.getReason()); assertEquals("message", exception.getMessage()); - assertFalse(exception.retryable()); - assertTrue(exception.idempotent()); + assertFalse(exception.isRetryable()); + assertTrue(exception.isIdempotent()); IOException cause = new SocketTimeoutException("socketTimeoutMessage"); exception = new DatastoreException(cause); - assertEquals(DatastoreException.UNKNOWN_CODE, exception.code()); - assertNull(exception.reason()); + assertEquals(DatastoreException.UNKNOWN_CODE, exception.getCode()); + assertNull(exception.getReason()); assertEquals("socketTimeoutMessage", exception.getMessage()); assertEquals(cause, exception.getCause()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); exception = new DatastoreException(2, "message", "INTERNAL", cause); - assertEquals(2, exception.code()); - assertEquals("INTERNAL", exception.reason()); + assertEquals(2, exception.getCode()); + assertEquals("INTERNAL", exception.getReason()); assertEquals("message", exception.getMessage()); - assertFalse(exception.retryable()); - assertTrue(exception.idempotent()); + assertFalse(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); } @@ -96,10 +96,10 @@ public void testTranslateAndThrow() throws Exception { try { DatastoreException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(14, ex.code()); + assertEquals(14, ex.getCode()); assertEquals("message", ex.getMessage()); - assertTrue(ex.retryable()); - assertTrue(ex.idempotent()); + assertTrue(ex.isRetryable()); + assertTrue(ex.isIdempotent()); } finally { verify(exceptionMock); } @@ -111,10 +111,10 @@ public void testTranslateAndThrow() throws Exception { try { DatastoreException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(DatastoreException.UNKNOWN_CODE, ex.code()); + assertEquals(DatastoreException.UNKNOWN_CODE, ex.getCode()); assertEquals("message", ex.getMessage()); - assertFalse(ex.retryable()); - assertTrue(ex.idempotent()); + assertFalse(ex.isRetryable()); + assertTrue(ex.isIdempotent()); assertSame(cause, ex.getCause()); } finally { verify(exceptionMock); @@ -127,7 +127,7 @@ public void testThrowInvalidRequest() throws Exception { DatastoreException.throwInvalidRequest("message %s %d", "a", 1); fail("Exception expected"); } catch (DatastoreException ex) { - assertEquals("FAILED_PRECONDITION", ex.reason()); + assertEquals("FAILED_PRECONDITION", ex.getReason()); assertEquals("message a 1", ex.getMessage()); } } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreHelperTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreHelperTest.java index 95a61d47484f..44d998137043 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreHelperTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreHelperTest.java @@ -42,8 +42,8 @@ public class DatastoreHelperTest { @Test public void testNewKeyFactory() { DatastoreOptions options = createMock(DatastoreOptions.class); - expect(options.projectId()).andReturn("ds1").once(); - expect(options.namespace()).andReturn("ns1").once(); + expect(options.getProjectId()).andReturn("ds1").once(); + expect(options.getNamespace()).andReturn("ns1").once(); replay(options); KeyFactory keyFactory = DatastoreHelper.newKeyFactory(options); Key key = keyFactory.setKind("k").newKey("bla"); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreOptionsTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreOptionsTest.java index 786f3ea79623..cbc257ce71a4 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreOptionsTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreOptionsTest.java @@ -39,10 +39,10 @@ public class DatastoreOptionsTest { public void setUp() { datastoreRpcFactory = EasyMock.createMock(DatastoreRpcFactory.class); datastoreRpc = EasyMock.createMock(DatastoreRpc.class); - options = DatastoreOptions.builder() - .serviceRpcFactory(datastoreRpcFactory) - .projectId(PROJECT_ID) - .host("http://localhost:" + PORT); + options = DatastoreOptions.newBuilder() + .setServiceRpcFactory(datastoreRpcFactory) + .setProjectId(PROJECT_ID) + .setHost("http://localhost:" + PORT); EasyMock.expect(datastoreRpcFactory.create(EasyMock.anyObject(DatastoreOptions.class))) .andReturn(datastoreRpc) .anyTimes(); @@ -51,33 +51,33 @@ public void setUp() { @Test public void testProjectId() throws Exception { - assertEquals(PROJECT_ID, options.build().projectId()); + assertEquals(PROJECT_ID, options.build().getProjectId()); } @Test public void testHost() throws Exception { - assertEquals("http://localhost:" + PORT, options.build().host()); + assertEquals("http://localhost:" + PORT, options.build().getHost()); } @Test public void testNamespace() throws Exception { - assertTrue(options.build().namespace().isEmpty()); - assertEquals("ns1", options.namespace("ns1").build().namespace()); + assertTrue(options.build().getNamespace().isEmpty()); + assertEquals("ns1", options.namespace("ns1").build().getNamespace()); } @Test public void testDatastore() throws Exception { - assertSame(datastoreRpc, options.build().rpc()); + assertSame(datastoreRpc, options.build().getRpc()); } @Test public void testToBuilder() throws Exception { DatastoreOptions original = options.namespace("ns1").build(); DatastoreOptions copy = original.toBuilder().build(); - assertEquals(original.projectId(), copy.projectId()); - assertEquals(original.namespace(), copy.namespace()); - assertEquals(original.host(), copy.host()); - assertEquals(original.retryParams(), copy.retryParams()); - assertEquals(original.authCredentials(), copy.authCredentials()); + assertEquals(original.getProjectId(), copy.getProjectId()); + assertEquals(original.getNamespace(), copy.getNamespace()); + assertEquals(original.getHost(), copy.getHost()); + assertEquals(original.getRetryParams(), copy.getRetryParams()); + assertEquals(original.getAuthCredentials(), copy.getAuthCredentials()); } } diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreTest.java index 7b99f36abc4c..092ae42cb336 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/DatastoreTest.java @@ -69,8 +69,8 @@ public class DatastoreTest { private static LocalDatastoreHelper helper = LocalDatastoreHelper.create(1.0); private static final DatastoreOptions options = helper.getOptions(); - private static final Datastore datastore = options.service(); - private static final String PROJECT_ID = options.projectId(); + private static final Datastore datastore = options.getService(); + private static final String PROJECT_ID = options.getProjectId(); private static final String KIND1 = "kind1"; private static final String KIND2 = "kind2"; private static final String KIND3 = "kind3"; @@ -139,8 +139,8 @@ public void setUp() { rpcMock = EasyMock.createStrictMock(DatastoreRpc.class); rpcMockOptions = options .toBuilder() - .retryParams(RetryParams.defaultInstance()) - .serviceRpcFactory(rpcFactoryMock) + .setRetryParams(RetryParams.getDefaultInstance()) + .setServiceRpcFactory(rpcFactoryMock) .build(); EasyMock.expect(rpcFactoryMock.create(rpcMockOptions)).andReturn(rpcMock); StructuredQuery query = Query.newKeyQueryBuilder().build(); @@ -156,7 +156,7 @@ public static void afterClass() throws IOException, InterruptedException { @Test public void testGetOptions() { - assertSame(options, datastore.options()); + assertSame(options, datastore.getOptions()); } @Test @@ -211,7 +211,7 @@ public void testTransactionWithRead() { transaction.commit(); fail("Expecting a failure"); } catch (DatastoreException expected) { - assertEquals("ABORTED", expected.reason()); + assertEquals("ABORTED", expected.getReason()); } } @@ -239,7 +239,7 @@ public void testTransactionWithQuery() { transaction.commit(); fail("Expecting a failure"); } catch (DatastoreException expected) { - assertEquals("ABORTED", expected.reason()); + assertEquals("ABORTED", expected.getReason()); } } @@ -440,7 +440,7 @@ public void testGqlQueryPagination() throws DatastoreException { .andReturn(responses.get(i)); } EasyMock.replay(rpcFactoryMock, rpcMock); - Datastore mockDatastore = rpcMockOptions.service(); + Datastore mockDatastore = rpcMockOptions.getService(); QueryResults results = mockDatastore.run(Query.newGqlQueryBuilder(ResultType.KEY, "select __key__ from *").build()); int count = 0; @@ -503,7 +503,7 @@ public void testStructuredQueryPagination() throws DatastoreException { .andReturn(responses.get(i)); } EasyMock.replay(rpcFactoryMock, rpcMock); - Datastore datastore = rpcMockOptions.service(); + Datastore datastore = rpcMockOptions.getService(); QueryResults results = datastore.run(Query.newKeyQueryBuilder().build()); int count = 0; while (results.hasNext()) { @@ -564,7 +564,7 @@ public void testQueryPaginationWithLimit() throws DatastoreException { } } EasyMock.replay(rpcFactoryMock, rpcMock); - Datastore datastore = rpcMockOptions.service(); + Datastore datastore = rpcMockOptions.getService(); int limit = 2; int totalCount = 0; Iterator cursorIter = endCursors.iterator(); @@ -593,7 +593,7 @@ private List buildResponsesForQueryPaginationWithLimit() { Entity entity4 = Entity.newBuilder(KEY4).set("value", StringValue.of("value")).build(); Entity entity5 = Entity.newBuilder(KEY5).set("value", "value").build(); datastore.add(ENTITY3, entity4, entity5); - DatastoreRpc datastoreRpc = datastore.options().rpc(); + DatastoreRpc datastoreRpc = datastore.getOptions().getRpc(); List responses = new ArrayList<>(); Query query = Query.newEntityQueryBuilder().build(); RunQueryRequest.Builder requestPb = RunQueryRequest.newBuilder(); @@ -652,7 +652,7 @@ public void testEventualConsistencyQuery() { EasyMock.expect(rpcMock.runQuery(expectedRequest.build())) .andReturn(RunQueryResponse.newBuilder().build()); EasyMock.replay(rpcFactoryMock, rpcMock); - Datastore datastore = rpcMockOptions.service(); + Datastore datastore = rpcMockOptions.getService(); datastore.run( Query.newGqlQueryBuilder("FROM * SELECT *").build(), ReadOption.eventualConsistency()); EasyMock.verify(rpcFactoryMock, rpcMock); @@ -750,7 +750,7 @@ public void testLookupEventualConsistency() { .andReturn(LookupResponse.newBuilder().build()) .times(3); EasyMock.replay(rpcFactoryMock, rpcMock); - Datastore datastore = rpcMockOptions.service(); + Datastore datastore = rpcMockOptions.getService(); datastore.get(KEY1, ReadOption.eventualConsistency()); datastore.get(ImmutableList.of(KEY1), ReadOption.eventualConsistency()); datastore.fetch(ImmutableList.of(KEY1), ReadOption.eventualConsistency()); @@ -857,7 +857,7 @@ private Datastore createDatastoreForDeferredLookup() throws DatastoreException { EasyMock.expect(rpcMock.lookup(lookupRequests.get(i))).andReturn(lookupResponses.get(i)); } EasyMock.replay(rpcFactoryMock, rpcMock); - return rpcMockOptions.service(); + return rpcMockOptions.getService(); } @Test @@ -963,7 +963,7 @@ public void testRetryableException() throws Exception { .andThrow(new DatastoreException(14, "UNAVAILABLE", "UNAVAILABLE", null)) .andReturn(responsePb); EasyMock.replay(rpcFactoryMock, rpcMock); - Datastore datastore = rpcMockOptions.service(); + Datastore datastore = rpcMockOptions.getService(); Entity entity = datastore.get(KEY1); assertEquals(ENTITY1, entity); EasyMock.verify(rpcFactoryMock, rpcMock); @@ -977,7 +977,7 @@ public void testNonRetryableException() throws Exception { new DatastoreException(DatastoreException.UNKNOWN_CODE, "denied", "PERMISSION_DENIED")) .times(1); EasyMock.replay(rpcFactoryMock, rpcMock); - Datastore datastore = rpcMockOptions.service(); + Datastore datastore = rpcMockOptions.getService(); thrown.expect(DatastoreException.class); thrown.expectMessage("denied"); datastore.get(KEY1); @@ -990,7 +990,7 @@ public void testRuntimeException() throws Exception { String exceptionMessage = "Artificial runtime exception"; EasyMock.expect(rpcMock.lookup(requestPb)).andThrow(new RuntimeException(exceptionMessage)); EasyMock.replay(rpcFactoryMock, rpcMock); - Datastore datastore = rpcMockOptions.service(); + Datastore datastore = rpcMockOptions.getService(); thrown.expect(DatastoreException.class); thrown.expectMessage(exceptionMessage); datastore.get(KEY1); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java index 505043a4ffbb..275ca0534e76 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/SerializationTest.java @@ -110,13 +110,13 @@ public class SerializationTest extends BaseSerializationTest { @Override protected java.io.Serializable[] serializableObjects() { - DatastoreOptions options = DatastoreOptions.builder() - .authCredentials(AuthCredentials.createForAppEngine()) - .projectId("ds1") + DatastoreOptions options = DatastoreOptions.newBuilder() + .setAuthCredentials(AuthCredentials.createForAppEngine()) + .setProjectId("ds1") .build(); DatastoreOptions otherOptions = options.toBuilder() .namespace("ns1") - .authCredentials(null) + .setAuthCredentials(null) .build(); return new java.io.Serializable[]{KEY1, KEY2, INCOMPLETE_KEY1, INCOMPLETE_KEY2, ENTITY1, ENTITY2, ENTITY3, EMBEDDED_ENTITY, PROJECTION_ENTITY, DATE_TIME1, BLOB1, CURSOR1, GQL1, diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/StructuredQueryTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/StructuredQueryTest.java index a19423b0709b..61c851c728a1 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/StructuredQueryTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/StructuredQueryTest.java @@ -161,7 +161,7 @@ public void testProjectionEntityQueryBuilderDeprecated() { } private void compareBaseBuilderFields(StructuredQuery query) { - assertEquals(NAMESPACE, query.namespace()); + assertEquals(NAMESPACE, query.getNamespace()); assertEquals(KIND, query.getKind()); assertEquals(START_CURSOR, query.getStartCursor()); assertEquals(END_CURSOR, query.getEndCursor()); @@ -172,7 +172,7 @@ private void compareBaseBuilderFields(StructuredQuery query) { } private void compareBaseBuilderFieldsDeprecated(StructuredQuery query) { - assertEquals(NAMESPACE, query.namespace()); + assertEquals(NAMESPACE, query.getNamespace()); assertEquals(KIND, query.kind()); assertEquals(START_CURSOR, query.startCursor()); assertEquals(END_CURSOR, query.endCursor()); @@ -208,13 +208,16 @@ private void compareMergedQuery(StructuredQuery expected, StructuredQuery public void testToAndFromPb() { assertEquals( ENTITY_QUERY, - StructuredQuery.fromPb(ResultType.ENTITY, ENTITY_QUERY.namespace(), ENTITY_QUERY.toPb())); + StructuredQuery.fromPb(ResultType.ENTITY, ENTITY_QUERY.getNamespace(), + ENTITY_QUERY.toPb())); assertEquals( - KEY_QUERY, StructuredQuery.fromPb(ResultType.KEY, KEY_QUERY.namespace(), KEY_QUERY.toPb())); + KEY_QUERY, StructuredQuery.fromPb(ResultType.KEY, KEY_QUERY.getNamespace(), + KEY_QUERY.toPb())); assertEquals( PROJECTION_QUERY, StructuredQuery.fromPb( - ResultType.PROJECTION_ENTITY, PROJECTION_QUERY.namespace(), PROJECTION_QUERY.toPb())); + ResultType.PROJECTION_ENTITY, PROJECTION_QUERY.getNamespace(), + PROJECTION_QUERY.toPb())); } @Test diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/it/ITDatastoreTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/it/ITDatastoreTest.java index c0a3901a9acd..a68175ccd6fc 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/it/ITDatastoreTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/it/ITDatastoreTest.java @@ -74,9 +74,9 @@ public class ITDatastoreTest { private static final RemoteDatastoreHelper HELPER = RemoteDatastoreHelper.create(); private static final DatastoreOptions OPTIONS = HELPER.getOptions(); - private static final Datastore DATASTORE = OPTIONS.service(); - private static final String PROJECT_ID = OPTIONS.projectId(); - private static final String NAMESPACE = OPTIONS.namespace(); + private static final Datastore DATASTORE = OPTIONS.getService(); + private static final String PROJECT_ID = OPTIONS.getProjectId(); + private static final String NAMESPACE = OPTIONS.getNamespace(); private static final String KIND1 = "kind1"; private static final String KIND2 = "kind2"; private static final String KIND3 = "kind3"; @@ -178,14 +178,14 @@ public void testNewTransactionCommit() { transaction.commit(); fail("Expecting a failure"); } catch (DatastoreException expected) { - assertEquals("FAILED_PRECONDITION", expected.reason()); + assertEquals("FAILED_PRECONDITION", expected.getReason()); } try { transaction.rollback(); fail("Expecting a failure"); } catch (DatastoreException expected) { - assertEquals("FAILED_PRECONDITION", expected.reason()); + assertEquals("FAILED_PRECONDITION", expected.getReason()); } } @@ -206,7 +206,7 @@ public void testTransactionWithRead() { transaction.commit(); fail("Expecting a failure"); } catch (DatastoreException expected) { - assertEquals("ABORTED", expected.reason()); + assertEquals("ABORTED", expected.getReason()); } } @@ -248,7 +248,7 @@ public void testTransactionWithQuery() throws InterruptedException { transaction.commit(); fail("Expecting a failure"); } catch (DatastoreException expected) { - assertEquals("ABORTED", expected.reason()); + assertEquals("ABORTED", expected.getReason()); } } @@ -267,7 +267,7 @@ public void testNewTransactionRollback() { transaction.commit(); fail("Expecting a failure"); } catch (DatastoreException expected) { - assertEquals("FAILED_PRECONDITION", expected.reason()); + assertEquals("FAILED_PRECONDITION", expected.getReason()); } List list = DATASTORE.fetch(KEY1, KEY2, KEY3); @@ -318,14 +318,15 @@ public void testNewBatch() { batch.submit(); fail("Expecting a failure"); } catch (DatastoreException expected) { - assertEquals("FAILED_PRECONDITION", expected.reason()); + assertEquals("FAILED_PRECONDITION", expected.getReason()); } batch = DATASTORE.newBatch(); batch.delete(entity4.getKey(), entity5.getKey(), entity6.getKey()); batch.update(ENTITY1, ENTITY2, ENTITY3); batch.submit(); - entities = DATASTORE.fetch(KEY1, KEY2, KEY3, entity4.getKey(), entity5.getKey(), entity6.getKey()); + entities = + DATASTORE.fetch(KEY1, KEY2, KEY3, entity4.getKey(), entity5.getKey(), entity6.getKey()); assertEquals(ENTITY1, entities.get(0)); assertEquals(ENTITY2, entities.get(1)); assertEquals(ENTITY3, entities.get(2)); @@ -373,9 +374,10 @@ public void testRunGqlQueryNoCasting() throws InterruptedException { results1 = DATASTORE.run(query1); assertFalse(results1.hasNext()); - Query keyOnlyQuery = Query.newGqlQueryBuilder(ResultType.KEY, "select __key__ from " + KIND1) - .setNamespace(NAMESPACE) - .build(); + Query keyOnlyQuery = + Query.newGqlQueryBuilder(ResultType.KEY, "select __key__ from " + KIND1) + .setNamespace(NAMESPACE) + .build(); QueryResults keyOnlyResults = DATASTORE.run(keyOnlyQuery); while (Iterators.size(keyOnlyResults) < 1) { Thread.sleep(500); diff --git a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java index 4aa0a7261f62..ee649c878ca0 100644 --- a/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java +++ b/google-cloud-datastore/src/test/java/com/google/cloud/datastore/testing/LocalDatastoreHelperTest.java @@ -71,21 +71,21 @@ public void testCreateDeprecated() { public void testOptions() { LocalDatastoreHelper helper = LocalDatastoreHelper.create(); DatastoreOptions options = helper.getOptions(); - assertTrue(options.projectId().startsWith(PROJECT_ID_PREFIX)); - assertTrue(options.host().startsWith("localhost:")); - assertSame(AuthCredentials.noAuth(), options.authCredentials()); + assertTrue(options.getProjectId().startsWith(PROJECT_ID_PREFIX)); + assertTrue(options.getHost().startsWith("localhost:")); + assertSame(AuthCredentials.noAuth(), options.getAuthCredentials()); options = helper.getOptions(NAMESPACE); - assertTrue(options.projectId().startsWith(PROJECT_ID_PREFIX)); - assertTrue(options.host().startsWith("localhost:")); - assertSame(AuthCredentials.noAuth(), options.authCredentials()); - assertEquals(NAMESPACE, options.namespace()); + assertTrue(options.getProjectId().startsWith(PROJECT_ID_PREFIX)); + assertTrue(options.getHost().startsWith("localhost:")); + assertSame(AuthCredentials.noAuth(), options.getAuthCredentials()); + assertEquals(NAMESPACE, options.getNamespace()); } @Test public void testStartStopReset() throws IOException, InterruptedException { LocalDatastoreHelper helper = LocalDatastoreHelper.create(); helper.start(); - Datastore datastore = helper.getOptions().service(); + Datastore datastore = helper.getOptions().getService(); Key key = datastore.newKeyFactory().setKind("kind").newKey("name"); datastore.put(Entity.newBuilder(key).build()); assertNotNull(datastore.get(key)); diff --git a/google-cloud-dns/README.md b/google-cloud-dns/README.md index ebd986d74b31..422bcaa447cc 100644 --- a/google-cloud-dns/README.md +++ b/google-cloud-dns/README.md @@ -86,7 +86,7 @@ code to create your service object: import com.google.cloud.dns.Dns; import com.google.cloud.dns.DnsOptions; -Dns dns = DnsOptions.defaultInstance().service(); +Dns dns = DnsOptions.getDefaultInstance().getService(); ``` For other authentication options, see the [Authentication](https://github.com/GoogleCloudPlatform/google-cloud-java#authentication) page. diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequest.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequest.java index d7ed6ef02dd2..2c9a89732d6d 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequest.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/ChangeRequest.java @@ -142,12 +142,13 @@ public ChangeRequest build() { super(infoBuilder); this.zone = checkNotNull(zone); this.dns = checkNotNull(dns); - this.options = dns.options(); + this.options = dns.getOptions(); } /** * Returns the name of the {@link Zone} associated with this change request. */ + @Deprecated public String zone() { return getZone(); } @@ -162,6 +163,7 @@ public String getZone() { /** * Returns the change request's {@code Dns} object used to issue requests. */ + @Deprecated public Dns dns() { return getDns(); } @@ -238,7 +240,7 @@ public final int hashCode() { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); - this.dns = options.service(); + this.dns = options.getService(); } static ChangeRequest fromPb(Dns dns, String zoneName, Change pb) { diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/Dns.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/Dns.java index 38faad7854e7..cbeb308b3a73 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/Dns.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/Dns.java @@ -53,7 +53,13 @@ enum ProjectField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -83,7 +89,13 @@ enum ZoneField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -110,7 +122,13 @@ enum RecordSetField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -138,7 +156,13 @@ enum ChangeRequestField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsBatch.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsBatch.java index b1fa7165aeaa..c2ecd5ec1a7c 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsBatch.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsBatch.java @@ -48,7 +48,7 @@ public class DnsBatch { DnsBatch(DnsOptions options) { this.options = options; - this.dnsRpc = options.rpc(); + this.dnsRpc = options.getRpc(); this.batch = dnsRpc.createBatch(); } @@ -247,7 +247,7 @@ public void onSuccess(Void response) { @Override public void onFailure(GoogleJsonError googleJsonError) { DnsException serviceException = new DnsException(googleJsonError, false); - if (serviceException.code() == HTTP_NOT_FOUND) { + if (serviceException.getCode() == HTTP_NOT_FOUND) { result.success(false); } else { result.error(serviceException); @@ -264,13 +264,14 @@ private RpcBatch.Callback createZoneCallback(final DnsOptions servi return new RpcBatch.Callback() { @Override public void onSuccess(ManagedZone response) { - result.success(response == null ? null : Zone.fromPb(serviceOptions.service(), response)); + result.success(response == null + ? null : Zone.fromPb(serviceOptions.getService(), response)); } @Override public void onFailure(GoogleJsonError googleJsonError) { DnsException serviceException = new DnsException(googleJsonError, idempotent); - if (nullForNotFound && serviceException.code() == HTTP_NOT_FOUND) { + if (nullForNotFound && serviceException.getCode() == HTTP_NOT_FOUND) { result.success(null); } else { result.error(serviceException); @@ -327,7 +328,7 @@ public void onSuccess(ChangesListResponse response) { new DnsImpl.ChangeRequestPageFetcher(zoneName, options, response.getNextPageToken(), optionMap), response.getNextPageToken(), changes == null ? ImmutableList.of() - : Iterables.transform(changes, ChangeRequest.fromPbFunction(options.service(), + : Iterables.transform(changes, ChangeRequest.fromPbFunction(options.getService(), zoneName))); result.success(page); } @@ -348,15 +349,15 @@ private RpcBatch.Callback createChangeRequestCallback(final String zoneN return new RpcBatch.Callback() { @Override public void onSuccess(Change response) { - result.success(response == null ? null : ChangeRequest.fromPb(options.service(), zoneName, - response)); + result.success(response == null + ? null : ChangeRequest.fromPb(options.getService(), zoneName, response)); } @Override public void onFailure(GoogleJsonError googleJsonError) { DnsException serviceException = new DnsException(googleJsonError, idempotent); - if (serviceException.code() == HTTP_NOT_FOUND) { - if ("entity.parameters.changeId".equals(serviceException.location()) + if (serviceException.getCode() == HTTP_NOT_FOUND) { + if ("entity.parameters.changeId".equals(serviceException.getLocation()) || (serviceException.getMessage() != null && serviceException.getMessage().contains("parameters.changeId"))) { // the change id was not found, but the zone exists diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsException.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsException.java index 90c32aee1681..c30a841fb454 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsException.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsException.java @@ -53,7 +53,7 @@ public DnsException(int code, String message, Throwable cause) { } @Override - protected Set retryableErrors() { + protected Set getRetryableErrors() { return RETRYABLE_ERRORS; } diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsImpl.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsImpl.java index abcacf0521e6..c98ae4313ca6 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsImpl.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsImpl.java @@ -58,7 +58,13 @@ static class ZonePageFetcher implements PageImpl.NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listZones(serviceOptions, requestOptions); } } @@ -79,7 +85,13 @@ static class ChangeRequestPageFetcher implements PageImpl.NextPageFetcher nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listChangeRequests(zoneName, serviceOptions, requestOptions); } } @@ -100,42 +112,48 @@ static class RecordSetPageFetcher implements PageImpl.NextPageFetcher } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listRecordSets(zoneName, serviceOptions, requestOptions); } } DnsImpl(DnsOptions options) { super(options); - dnsRpc = options.rpc(); + dnsRpc = options.getRpc(); } static Function zoneFromPb(final DnsOptions options) { return new Function() { @Override public Zone apply(ManagedZone zonePb) { - return Zone.fromPb(options.service(), zonePb); + return Zone.fromPb(options.getService(), zonePb); } }; } @Override public Page listZones(ZoneListOption... options) { - return listZones(options(), optionMap(options)); + return listZones(getOptions(), optionMap(options)); } private static Page listZones(final DnsOptions serviceOptions, final Map optionsMap) { try { // get a list of managed zones - final DnsRpc rpc = serviceOptions.rpc(); + final DnsRpc rpc = serviceOptions.getRpc(); DnsRpc.ListResult result = runWithRetries(new Callable>() { @Override public DnsRpc.ListResult call() { return rpc.listZones(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.pageToken(); // transform that list into zone objects Iterable zones = result.results() == null ? ImmutableList.of() @@ -150,26 +168,26 @@ public DnsRpc.ListResult call() { @Override public Page listChangeRequests(String zoneName, ChangeRequestListOption... options) { - return listChangeRequests(zoneName, options(), optionMap(options)); + return listChangeRequests(zoneName, getOptions(), optionMap(options)); } private static Page listChangeRequests(final String zoneName, final DnsOptions serviceOptions, final Map optionsMap) { try { // get a list of changes - final DnsRpc rpc = serviceOptions.rpc(); + final DnsRpc rpc = serviceOptions.getRpc(); DnsRpc.ListResult result = runWithRetries(new Callable>() { @Override public DnsRpc.ListResult call() { return rpc.listChangeRequests(zoneName, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.pageToken(); // transform that list into change request objects Iterable changes = result.results() == null ? ImmutableList.of() : Iterables.transform(result.results(), - ChangeRequest.fromPbFunction(serviceOptions.service(), zoneName)); + ChangeRequest.fromPbFunction(serviceOptions.getService(), zoneName)); return new PageImpl<>(new ChangeRequestPageFetcher(zoneName, serviceOptions, cursor, optionsMap), cursor, changes); } catch (RetryHelper.RetryHelperException e) { @@ -179,21 +197,21 @@ public DnsRpc.ListResult call() { @Override public Page listRecordSets(String zoneName, RecordSetListOption... options) { - return listRecordSets(zoneName, options(), optionMap(options)); + return listRecordSets(zoneName, getOptions(), optionMap(options)); } private static Page listRecordSets(final String zoneName, final DnsOptions serviceOptions, final Map optionsMap) { try { // get a list of record sets - final DnsRpc rpc = serviceOptions.rpc(); + final DnsRpc rpc = serviceOptions.getRpc(); DnsRpc.ListResult result = runWithRetries( new Callable>() { @Override public DnsRpc.ListResult call() { return rpc.listRecordSets(zoneName, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.pageToken(); // transform that list into record sets Iterable recordSets = result.results() == null @@ -216,7 +234,7 @@ public Zone create(final ZoneInfo zoneInfo, Dns.ZoneOption... options) { public ManagedZone call() { return dnsRpc.create(zoneInfo.toPb(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Zone.fromPb(this, answer); } catch (RetryHelper.RetryHelperException ex) { throw DnsException.translateAndThrow(ex); @@ -233,7 +251,7 @@ public Zone getZone(final String zoneName, Dns.ZoneOption... options) { public ManagedZone call() { return dnsRpc.getZone(zoneName, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Zone.fromPb(this, answer); } catch (RetryHelper.RetryHelperException ex) { throw DnsException.translateAndThrow(ex); @@ -248,7 +266,7 @@ public boolean delete(final String zoneName) { public Boolean call() { return dnsRpc.deleteZone(zoneName); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelper.RetryHelperException ex) { throw DnsException.translateAndThrow(ex); } @@ -264,7 +282,7 @@ public ProjectInfo getProject(Dns.ProjectOption... fields) { public Project call() { return dnsRpc.getProject(optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : ProjectInfo.fromPb(answer); // should never be null } catch (RetryHelper.RetryHelperException ex) { throw DnsException.translateAndThrow(ex); @@ -282,7 +300,7 @@ public ChangeRequest applyChangeRequest(final String zoneName, public Change call() { return dnsRpc.applyChangeRequest(zoneName, changeRequest.toPb(), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : ChangeRequest.fromPb(this, zoneName, answer); // not null } catch (RetryHelper.RetryHelperException ex) { throw DnsException.translateAndThrow(ex); @@ -300,7 +318,7 @@ public ChangeRequest getChangeRequest(final String zoneName, final String change public Change call() { return dnsRpc.getChangeRequest(zoneName, changeRequestId, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : ChangeRequest.fromPb(this, zoneName, answer); } catch (RetryHelper.RetryHelperException ex) { throw DnsException.translateAndThrow(ex); @@ -309,7 +327,7 @@ public Change call() { @Override public DnsBatch batch() { - return new DnsBatch(this.options()); + return new DnsBatch(this.getOptions()); } static Map optionMap(Option... options) { diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsOptions.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsOptions.java index a3db4ef7ed63..d76d8e22525a 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsOptions.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/DnsOptions.java @@ -70,17 +70,17 @@ private DnsOptions(Builder builder) { } @Override - protected DnsFactory defaultServiceFactory() { + protected DnsFactory getDefaultServiceFactory() { return DefaultDnsFactory.INSTANCE; } @Override - protected DnsRpcFactory defaultRpcFactory() { + protected DnsRpcFactory getDefaultRpcFactory() { return DefaultDnsRpcFactory.INSTANCE; } @Override - protected Set scopes() { + protected Set getScopes() { return SCOPES; } @@ -90,7 +90,12 @@ public Builder toBuilder() { return new Builder(this); } + @Deprecated public static Builder builder() { + return newBuilder(); + } + + public static Builder newBuilder() { return new Builder(); } @@ -98,8 +103,17 @@ public static Builder builder() { * Creates a default instance of {@code DnsOptions} with the project ID and credentials inferred * from the environment. */ + @Deprecated public static DnsOptions defaultInstance() { - return builder().build(); + return getDefaultInstance(); + } + + /** + * Creates a default instance of {@code DnsOptions} with the project ID and credentials inferred + * from the environment. + */ + public static DnsOptions getDefaultInstance() { + return newBuilder().build(); } @Override diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/Zone.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/Zone.java index 5680af4c8646..80c4f7c5daae 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/Zone.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/Zone.java @@ -124,7 +124,7 @@ public Zone build() { Zone(Dns dns, ZoneInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.dns = dns; - this.options = dns.options(); + this.options = dns.getOptions(); } @Override @@ -241,7 +241,7 @@ public final int hashCode() { private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); - this.dns = options.service(); + this.dns = options.getService(); } static Zone fromPb(Dns dns, ManagedZone zone) { diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/package-info.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/package-info.java index a56db7757db7..44bd05a16e40 100644 --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/package-info.java +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/package-info.java @@ -27,7 +27,7 @@ * name that you own and the ownership of which you verified with Google. * *

     {@code
    - * Dns dns = DnsOptions.defaultInstance().service();
    + * Dns dns = DnsOptions.getDefaultInstance().getService();
      * String zoneName = "my-unique-zone";
      * String domainName = "someexampledomain.com.";
      * String description = "This is a google-cloud-dns sample zone.";
    @@ -42,7 +42,7 @@
      * CreateAndListDnsRecords.java.
      *
      * 
     {@code
    - * Dns dns = DnsOptions.defaultInstance().service();
    + * Dns dns = DnsOptions.getDefaultInstance().getService();
      * String zoneName = "my-unique-zone";
      * Zone zone = dns.getZone(zoneName);
      * String ip = "12.13.14.15";
    diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/spi/DefaultDnsRpc.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/spi/DefaultDnsRpc.java
    index 4ee117cc7ea1..82423647df1b 100644
    --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/spi/DefaultDnsRpc.java
    +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/spi/DefaultDnsRpc.java
    @@ -187,11 +187,11 @@ private static DnsException translate(IOException exception, boolean idempotent)
        * Constructs an instance of this rpc client with provided {@link DnsOptions}.
        */
       public DefaultDnsRpc(DnsOptions options) {
    -    HttpTransport transport = options.httpTransportFactory().create();
    -    HttpRequestInitializer initializer = options.httpRequestInitializer();
    +    HttpTransport transport = options.getHttpTransportFactory().create();
    +    HttpRequestInitializer initializer = options.getHttpRequestInitializer();
         this.dns = new Dns.Builder(transport, new JacksonFactory(), initializer)
    -        .setRootUrl(options.host())
    -        .setApplicationName(options.applicationName())
    +        .setRootUrl(options.getHost())
    +        .setApplicationName(options.getApplicationName())
             .build();
         this.options = options;
       }
    @@ -209,7 +209,7 @@ public ManagedZone create(ManagedZone zone, Map options) throws DnsEx
       private Dns.ManagedZones.Create createZoneCall(ManagedZone zone, Map options)
           throws IOException {
         return dns.managedZones()
    -        .create(this.options.projectId(), zone)
    +        .create(this.options.getProjectId(), zone)
             .setFields(FIELDS.getString(options));
       }
     
    @@ -220,7 +220,7 @@ public ManagedZone getZone(String zoneName, Map options) throws DnsEx
           return getZoneCall(zoneName, options).execute();
         } catch (IOException ex) {
           DnsException serviceException = translate(ex, true);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return null;
           }
           throw serviceException;
    @@ -230,7 +230,7 @@ public ManagedZone getZone(String zoneName, Map options) throws DnsEx
       private Dns.ManagedZones.Get getZoneCall(String zoneName, Map options)
           throws IOException {
         return dns.managedZones()
    -        .get(this.options.projectId(), zoneName)
    +        .get(this.options.getProjectId(), zoneName)
             .setFields(FIELDS.getString(options));
       }
     
    @@ -246,7 +246,7 @@ public ListResult listZones(Map options) throws DnsExcep
       }
     
       private Dns.ManagedZones.List listZonesCall(Map options) throws IOException {
    -    return dns.managedZones().list(this.options.projectId())
    +    return dns.managedZones().list(this.options.getProjectId())
             .setFields(FIELDS.getString(options))
             .setMaxResults(PAGE_SIZE.getInt(options))
             .setDnsName(DNS_NAME.getString(options))
    @@ -260,7 +260,7 @@ public boolean deleteZone(String zoneName) throws DnsException {
           return true;
         } catch (IOException ex) {
           DnsException serviceException = translate(ex, false);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return false;
           }
           throw serviceException;
    @@ -268,7 +268,7 @@ public boolean deleteZone(String zoneName) throws DnsException {
       }
     
       private Dns.ManagedZones.Delete deleteZoneCall(String zoneName) throws IOException {
    -    return dns.managedZones().delete(this.options.projectId(), zoneName);
    +    return dns.managedZones().delete(this.options.getProjectId(), zoneName);
       }
     
       @Override
    @@ -286,7 +286,7 @@ private Dns.ResourceRecordSets.List listRecordSetsCall(String zoneName, Map options) throws DnsException {
       }
     
       private Dns.Projects.Get getProjectCall(Map options) throws IOException {
    -    return dns.projects().get(this.options.projectId()).setFields(FIELDS.getString(options));
    +    return dns.projects().get(this.options.getProjectId()).setFields(FIELDS.getString(options));
       }
     
       @Override
    @@ -320,7 +320,7 @@ public Change applyChangeRequest(String zoneName, Change changeRequest, Map options) throws IOException {
         return dns.changes()
    -        .create(this.options.projectId(), zoneName, changeRequest)
    +        .create(this.options.getProjectId(), zoneName, changeRequest)
             .setFields(FIELDS.getString(options));
       }
     
    @@ -331,8 +331,8 @@ public Change getChangeRequest(String zoneName, String changeRequestId, Map options) throws IOException {
         return dns.changes()
    -        .get(this.options.projectId(), zoneName, changeRequestId)
    +        .get(this.options.getProjectId(), zoneName, changeRequestId)
             .setFields(FIELDS.getString(options));
       }
     
    @@ -365,7 +365,7 @@ public ListResult listChangeRequests(String zoneName, Map opt
       private Dns.Changes.List listChangeRequestsCall(String zoneName, Map options)
           throws IOException {
         // options are fields, page token, page size, sort order
    -    Dns.Changes.List request = dns.changes().list(this.options.projectId(), zoneName)
    +    Dns.Changes.List request = dns.changes().list(this.options.getProjectId(), zoneName)
             .setFields(FIELDS.getString(options))
             .setMaxResults(PAGE_SIZE.getInt(options))
             .setPageToken(PAGE_TOKEN.getString(options));
    diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java
    index 12e2599defcb..b9abf3aeb43b 100644
    --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java
    +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/LocalDnsHelper.java
    @@ -504,10 +504,10 @@ public DnsOptions options() {
        * Returns a {@link DnsOptions} instance that sets the host to use the mock server.
        */
       public DnsOptions getOptions() {
    -    return DnsOptions.builder()
    -        .projectId(PROJECT_ID)
    -        .host("http://localhost:" + port)
    -        .authCredentials(AuthCredentials.noAuth())
    +    return DnsOptions.newBuilder()
    +        .setProjectId(PROJECT_ID)
    +        .setHost("http://localhost:" + port)
    +        .setAuthCredentials(AuthCredentials.noAuth())
             .build();
       }
     
    diff --git a/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/package-info.java b/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/package-info.java
    index da431658c712..1f48ecf01607 100644
    --- a/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/package-info.java
    +++ b/google-cloud-dns/src/main/java/com/google/cloud/dns/testing/package-info.java
    @@ -25,7 +25,7 @@
      * long delay = 0;
      * LocalDnsHelper dnsHelper = LocalDnsHelper.create(delay);
      * dnsHelper.start();
    - * Dns dns = dnsHelper.options().service();
    + * Dns dns = dnsHelper.getOptions().getService();
      * }
    * *

    After the test: diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/ChangeRequestTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/ChangeRequestTest.java index f983ae47e686..5a3347890c00 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/ChangeRequestTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/ChangeRequestTest.java @@ -49,7 +49,7 @@ public class ChangeRequestTest { @Before public void setUp() throws Exception { dns = createStrictMock(Dns.class); - expect(dns.options()).andReturn(OPTIONS).times(3); + expect(dns.getOptions()).andReturn(OPTIONS).times(3); replay(dns); changeRequest = new ChangeRequest(dns, ZONE_NAME, new ChangeRequestInfo.BuilderImpl( CHANGE_REQUEST_INFO.toBuilder() @@ -75,7 +75,19 @@ public void tearDown() throws Exception { @Test public void testConstructor() { - expect(dns.options()).andReturn(OPTIONS); + expect(dns.getOptions()).andReturn(OPTIONS); + replay(dns); + assertEquals(new ChangeRequest(dns, ZONE_NAME, + new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_INFO)), changeRequestPartial); + assertNotNull(changeRequest.getDns()); + assertEquals(ZONE_NAME, changeRequest.getZone()); + assertSame(dns, changeRequestPartial.getDns()); + assertEquals(ZONE_NAME, changeRequestPartial.getZone()); + } + + @Test + public void testConstructorDeprecated() { + expect(dns.getOptions()).andReturn(OPTIONS); replay(dns); assertEquals(new ChangeRequest(dns, ZONE_NAME, new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_INFO)), changeRequestPartial); @@ -87,7 +99,7 @@ public void testConstructor() { @Test public void testFromPb() { - expect(dns.options()).andReturn(OPTIONS).times(2); + expect(dns.getOptions()).andReturn(OPTIONS).times(2); replay(dns); assertEquals(changeRequest, ChangeRequest.fromPb(dns, ZONE_NAME, changeRequest.toPb())); assertEquals(changeRequestPartial, @@ -96,7 +108,7 @@ public void testFromPb() { @Test public void testEqualsAndToBuilder() { - expect(dns.options()).andReturn(OPTIONS).times(2); + expect(dns.getOptions()).andReturn(OPTIONS).times(2); replay(dns); ChangeRequest compare = changeRequest.toBuilder().build(); assertEquals(changeRequest, compare); @@ -110,7 +122,7 @@ public void testEqualsAndToBuilder() { @Test public void testBuilder() { // one for each build() call because it invokes a constructor - expect(dns.options()).andReturn(OPTIONS).times(9); + expect(dns.getOptions()).andReturn(OPTIONS).times(9); replay(dns); String id = changeRequest.getGeneratedId() + "aaa"; assertEquals(id, changeRequest.toBuilder().setGeneratedId(id).build().getGeneratedId()); @@ -137,7 +149,7 @@ public void testBuilder() { @Test public void testBuilderDeprecated() { // one for each build() call because it invokes a constructor - expect(dns.options()).andReturn(OPTIONS).times(9); + expect(dns.getOptions()).andReturn(OPTIONS).times(9); replay(dns); String id = changeRequest.generatedId() + "aaa"; assertEquals(id, changeRequest.toBuilder().setGeneratedId(id).build().generatedId()); diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsBatchTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsBatchTest.java index d348e8e9858f..03c8e096f52d 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsBatchTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsBatchTest.java @@ -109,7 +109,7 @@ public void setUp() { optionsMock = EasyMock.createMock(DnsOptions.class); dnsRpcMock = EasyMock.createMock(DnsRpc.class); batchMock = EasyMock.createMock(RpcBatch.class); - EasyMock.expect(optionsMock.rpc()).andReturn(dnsRpcMock); + EasyMock.expect(optionsMock.getRpc()).andReturn(dnsRpcMock); EasyMock.expect(dnsRpcMock.createBatch()).andReturn(batchMock); EasyMock.replay(optionsMock, dnsRpcMock, batchMock, dns); dnsBatch = new DnsBatch(optionsMock); @@ -150,7 +150,7 @@ public void testListZones() { fail("Should throw a DnsException on error."); } catch (DnsException ex) { // expected - assertTrue(ex.idempotent()); + assertTrue(ex.isIdempotent()); } } @@ -168,8 +168,8 @@ public void testListZonesWithOptions() { String selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[1].getRpcOption()); assertEquals(PAGE_TOKEN, selector); selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[2].getRpcOption()); - assertTrue(selector.contains(Dns.ZoneField.DESCRIPTION.selector())); - assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); + assertTrue(selector.contains(Dns.ZoneField.DESCRIPTION.getSelector())); + assertTrue(selector.contains(Dns.ZoneField.NAME.getSelector())); selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[3].getRpcOption()); assertEquals(DNS_NAME, selector); // check the callback @@ -179,16 +179,16 @@ public void testListZonesWithOptions() { RpcBatch.Callback capturedCallback = callback.getValue(); EasyMock.verify(optionsMock); EasyMock.reset(optionsMock); - EasyMock.expect(optionsMock.service()).andReturn(dns).times(ZONE_LIST.size()); + EasyMock.expect(optionsMock.getService()).andReturn(dns).times(ZONE_LIST.size()); EasyMock.replay(optionsMock); capturedCallback.onSuccess(response); Page page = batchResult.get(); - assertEquals(PAGE_TOKEN, page.nextPageCursor()); - Iterator iterator = page.values().iterator(); + assertEquals(PAGE_TOKEN, page.getNextPageCursor()); + Iterator iterator = page.getValues().iterator(); int resultSize = 0; EasyMock.verify(dns); EasyMock.reset(dns); - EasyMock.expect(dns.options()).andReturn(optionsMock).times(ZONE_LIST.size() + 1); + EasyMock.expect(dns.getOptions()).andReturn(optionsMock).times(ZONE_LIST.size() + 1); EasyMock.replay(dns); Zone zoneInfoFunctional = new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)); while (iterator.hasNext()) { @@ -227,15 +227,15 @@ public void testCreateZone() { fail("Should throw a DnsException on error."); } catch (DnsException ex) { // expected - assertTrue(ex.idempotent()); + assertTrue(ex.isIdempotent()); } } @Test public void testCreateZoneWithOptions() { EasyMock.reset(dns, batchMock, optionsMock); - EasyMock.expect(dns.options()).andReturn(optionsMock); - EasyMock.expect(optionsMock.service()).andReturn(dns); + EasyMock.expect(dns.getOptions()).andReturn(optionsMock); + EasyMock.expect(optionsMock.getService()).andReturn(dns); Capture> callback = Capture.newInstance(); Capture> capturedOptions = Capture.newInstance(); Capture capturedZone = Capture.newInstance(); @@ -246,8 +246,8 @@ public void testCreateZoneWithOptions() { assertEquals(ZONE_INFO.toPb(), capturedZone.getValue()); assertNotNull(callback.getValue()); String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.getRpcOption()); - assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.selector())); - assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); + assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.getSelector())); + assertTrue(selector.contains(Dns.ZoneField.NAME.getSelector())); RpcBatch.Callback capturedCallback = callback.getValue(); capturedCallback.onSuccess(ZONE_INFO.toPb()); assertEquals(ZONE_INFO.toPb(), batchResult.get().toPb()); @@ -278,7 +278,7 @@ public void testGetZone() { fail("Should throw a DnsException on error."); } catch (DnsException ex) { // expected - assertTrue(ex.idempotent()); + assertTrue(ex.isIdempotent()); } } @@ -302,18 +302,18 @@ public void testGetZoneNotFound() { @Test public void testGetZoneWithOptions() { EasyMock.reset(dns, batchMock, optionsMock); - EasyMock.expect(dns.options()).andReturn(optionsMock); + EasyMock.expect(dns.getOptions()).andReturn(optionsMock); Capture> callback = Capture.newInstance(); Capture> capturedOptions = Capture.newInstance(); batchMock.addGetZone(EasyMock.eq(ZONE_NAME), EasyMock.capture(callback), EasyMock.capture(capturedOptions)); - EasyMock.expect(optionsMock.service()).andReturn(dns); + EasyMock.expect(optionsMock.getService()).andReturn(dns); EasyMock.replay(dns, batchMock, optionsMock); DnsBatchResult batchResult = dnsBatch.getZone(ZONE_NAME, ZONE_FIELDS); assertNotNull(callback.getValue()); String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.getRpcOption()); - assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.selector())); - assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); + assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.getSelector())); + assertTrue(selector.contains(Dns.ZoneField.NAME.getSelector())); RpcBatch.Callback capturedCallback = callback.getValue(); capturedCallback.onSuccess(ZONE_INFO.toPb()); assertEquals(ZONE_INFO.toPb(), batchResult.get().toPb()); @@ -341,7 +341,7 @@ public void testDeleteZone() { fail("Should throw a DnsException on error."); } catch (DnsException ex) { // expected - assertFalse(ex.idempotent()); + assertFalse(ex.isIdempotent()); } } @@ -383,7 +383,7 @@ public void testGetProject() { fail("Should throw a DnsException on error."); } catch (DnsException ex) { // expected - assertTrue(ex.idempotent()); + assertTrue(ex.isIdempotent()); } } @@ -397,8 +397,8 @@ public void testGetProjectWithOptions() { DnsBatchResult batchResult = dnsBatch.getProject(PROJECT_FIELDS); assertNotNull(callback.getValue()); String selector = (String) capturedOptions.getValue().get(PROJECT_FIELDS.getRpcOption()); - assertTrue(selector.contains(Dns.ProjectField.QUOTA.selector())); - assertTrue(selector.contains(Dns.ProjectField.PROJECT_ID.selector())); + assertTrue(selector.contains(Dns.ProjectField.QUOTA.getSelector())); + assertTrue(selector.contains(Dns.ProjectField.PROJECT_ID.getSelector())); RpcBatch.Callback capturedCallback = callback.getValue(); capturedCallback.onSuccess(PROJECT_INFO.toPb()); assertEquals(PROJECT_INFO, batchResult.get()); @@ -428,7 +428,7 @@ public void testListRecordSets() { fail("Should throw a DnsException on error."); } catch (DnsException ex) { // expected - assertTrue(ex.idempotent()); + assertTrue(ex.isIdempotent()); } } @@ -450,8 +450,8 @@ public void testListRecordSetsWithOptions() { .get(RECORD_SET_LIST_OPTIONS[1].getRpcOption()); assertEquals(PAGE_TOKEN, selector); selector = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[2].getRpcOption()); - assertTrue(selector.contains(Dns.RecordSetField.NAME.selector())); - assertTrue(selector.contains(Dns.RecordSetField.TTL.selector())); + assertTrue(selector.contains(Dns.RecordSetField.NAME.getSelector())); + assertTrue(selector.contains(Dns.RecordSetField.TTL.getSelector())); selector = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[3].getRpcOption()); assertEquals(RECORD_SET_LIST_OPTIONS[3].getValue(), selector); String type = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[4] @@ -463,8 +463,8 @@ public void testListRecordSetsWithOptions() { .setNextPageToken(PAGE_TOKEN); capturedCallback.onSuccess(response); Page page = batchResult.get(); - assertEquals(PAGE_TOKEN, page.nextPageCursor()); - Iterator iterator = page.values().iterator(); + assertEquals(PAGE_TOKEN, page.getNextPageCursor()); + Iterator iterator = page.getValues().iterator(); int resultSize = 0; while (iterator.hasNext()) { assertEquals(RECORD_SET, iterator.next()); @@ -497,7 +497,7 @@ public void testListChangeRequests() { fail("Should throw a DnsException on error."); } catch (DnsException ex) { // expected - assertTrue(ex.idempotent()); + assertTrue(ex.isIdempotent()); } } @@ -518,8 +518,8 @@ public void testListChangeRequestsWithOptions() { (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[1].getRpcOption()); assertEquals(PAGE_TOKEN, selector); selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[2].getRpcOption()); - assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); - assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); + assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.getSelector())); + assertTrue(selector.contains(Dns.ChangeRequestField.ID.getSelector())); selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[3].getRpcOption()); assertTrue(selector.contains(Dns.SortingOrder.ASCENDING.selector())); // check the callback @@ -529,16 +529,16 @@ public void testListChangeRequestsWithOptions() { RpcBatch.Callback capturedCallback = callback.getValue(); EasyMock.verify(optionsMock); EasyMock.reset(optionsMock); - EasyMock.expect(optionsMock.service()).andReturn(dns); + EasyMock.expect(optionsMock.getService()).andReturn(dns); EasyMock.replay(optionsMock); capturedCallback.onSuccess(response); Page page = batchResult.get(); - assertEquals(PAGE_TOKEN, page.nextPageCursor()); - Iterator iterator = page.values().iterator(); + assertEquals(PAGE_TOKEN, page.getNextPageCursor()); + Iterator iterator = page.getValues().iterator(); int resultSize = 0; EasyMock.verify(dns); EasyMock.reset(dns); - EasyMock.expect(dns.options()).andReturn(optionsMock).times(CHANGE_LIST.size()); + EasyMock.expect(dns.getOptions()).andReturn(optionsMock).times(CHANGE_LIST.size()); EasyMock.replay(dns); while (iterator.hasNext()) { assertEquals(CHANGE_REQUEST_COMPLETE.toPb(), iterator.next().toPb()); @@ -574,7 +574,7 @@ public void testGetChangeRequest() { fail("Should throw a DnsException on error."); } catch (DnsException ex) { // expected - assertTrue(ex.idempotent()); + assertTrue(ex.isIdempotent()); } } @@ -604,8 +604,8 @@ public void testGetChangeRequestNotFound() { @Test public void testGetChangeRequestWithOptions() { EasyMock.reset(dns, batchMock, optionsMock); - EasyMock.expect(dns.options()).andReturn(optionsMock); - EasyMock.expect(optionsMock.service()).andReturn(dns); + EasyMock.expect(dns.getOptions()).andReturn(optionsMock); + EasyMock.expect(optionsMock.getService()).andReturn(dns); Capture> callback = Capture.newInstance(); Capture> capturedOptions = Capture.newInstance(); batchMock.addGetChangeRequest(EasyMock.eq(ZONE_NAME), @@ -616,8 +616,8 @@ public void testGetChangeRequestWithOptions() { CHANGE_REQUEST_COMPLETE.getGeneratedId(), CHANGE_GET_FIELDS); assertNotNull(callback.getValue()); String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.getRpcOption()); - assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); - assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); + assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.getSelector())); + assertTrue(selector.contains(Dns.ChangeRequestField.ID.getSelector())); RpcBatch.Callback capturedCallback = callback.getValue(); capturedCallback.onSuccess(CHANGE_REQUEST_COMPLETE.toPb()); assertEquals(CHANGE_REQUEST_COMPLETE.toPb(), batchResult.get().toPb()); @@ -652,26 +652,26 @@ public void testApplyChangeRequest() { fail("Should throw a DnsException on error."); } catch (DnsException ex) { // expected - assertFalse(ex.idempotent()); + assertFalse(ex.isIdempotent()); } } @Test public void testApplyChangeRequestWithOptions() { EasyMock.reset(dns, batchMock, optionsMock); - EasyMock.expect(dns.options()).andReturn(optionsMock); + EasyMock.expect(dns.getOptions()).andReturn(optionsMock); Capture> callback = Capture.newInstance(); Capture> capturedOptions = Capture.newInstance(); batchMock.addApplyChangeRequest(EasyMock.eq(ZONE_NAME), EasyMock.eq(CHANGE_REQUEST_PARTIAL.toPb()), EasyMock.capture(callback), EasyMock.capture(capturedOptions)); - EasyMock.expect(optionsMock.service()).andReturn(dns); + EasyMock.expect(optionsMock.getService()).andReturn(dns); EasyMock.replay(dns, batchMock, optionsMock); DnsBatchResult batchResult = dnsBatch.applyChangeRequest(ZONE_INFO.getName(), CHANGE_REQUEST_PARTIAL, CHANGE_GET_FIELDS); String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.getRpcOption()); - assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); - assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); + assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.getSelector())); + assertTrue(selector.contains(Dns.ChangeRequestField.ID.getSelector())); RpcBatch.Callback capturedCallback = callback.getValue(); capturedCallback.onSuccess(CHANGE_REQUEST_COMPLETE.toPb()); assertEquals(CHANGE_REQUEST_COMPLETE.toPb(), batchResult.get().toPb()); diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsExceptionTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsExceptionTest.java index f97d9f697baa..7da8bac8d090 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsExceptionTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsExceptionTest.java @@ -41,62 +41,62 @@ public class DnsExceptionTest { public void testDnsException() throws Exception { IOException cause = new SocketTimeoutException("socketTimeoutMessage"); DnsException exception = new DnsException(500, "message", cause); - assertEquals(500, exception.code()); + assertEquals(500, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); exception = new DnsException(502, "message", cause); - assertEquals(502, exception.code()); + assertEquals(502, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); exception = new DnsException(503, "message", cause); - assertEquals(503, exception.code()); + assertEquals(503, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); exception = new DnsException(429, "message", cause); - assertEquals(429, exception.code()); + assertEquals(429, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); exception = new DnsException(404, "message", cause); - assertEquals(404, exception.code()); + assertEquals(404, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertFalse(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertFalse(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); exception = new DnsException(cause, true); - assertEquals(DnsException.UNKNOWN_CODE, exception.code()); - assertNull(exception.reason()); + assertEquals(DnsException.UNKNOWN_CODE, exception.getCode()); + assertNull(exception.getReason()); assertEquals("socketTimeoutMessage", exception.getMessage()); assertEquals(cause, exception.getCause()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); GoogleJsonError error = new GoogleJsonError(); error.setCode(503); error.setMessage("message"); exception = new DnsException(error, true); - assertEquals(503, exception.code()); + assertEquals(503, exception.getCode()); assertEquals("message", exception.getMessage()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); } @Test @@ -109,12 +109,12 @@ public void testTranslateAndThrow() throws Exception { try { DnsException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(DnsException.UNKNOWN_CODE, ex.code()); - assertNull(ex.reason()); + assertEquals(DnsException.UNKNOWN_CODE, ex.getCode()); + assertNull(ex.getReason()); assertEquals("message", ex.getMessage()); assertEquals(timeoutException, ex.getCause()); - assertTrue(ex.retryable()); - assertTrue(ex.idempotent()); + assertTrue(ex.isRetryable()); + assertTrue(ex.isIdempotent()); } finally { verify(exceptionMock); } @@ -126,10 +126,10 @@ public void testTranslateAndThrow() throws Exception { try { DnsException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(DnsException.UNKNOWN_CODE, ex.code()); + assertEquals(DnsException.UNKNOWN_CODE, ex.getCode()); assertEquals("message", ex.getMessage()); - assertFalse(ex.retryable()); - assertTrue(ex.idempotent()); + assertFalse(ex.isRetryable()); + assertTrue(ex.isIdempotent()); assertSame(cause, ex.getCause()); } finally { verify(exceptionMock); diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsImplTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsImplTest.java index 19c143abbeaf..534a939d7c1e 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsImplTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsImplTest.java @@ -119,11 +119,11 @@ public void setUp() { 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()) + options = DnsOptions.newBuilder() + .setProjectId("projectId") + .setClock(TIME_SOURCE) + .setServiceRpcFactory(rpcFactoryMock) + .setRetryParams(RetryParams.noRetries()) .build(); } @@ -137,7 +137,7 @@ 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 + dns = options.getService(); // creates DnsImpl Zone zone = dns.create(ZONE_INFO); assertEquals(new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)), zone); } @@ -148,12 +148,12 @@ public void testCreateZoneWithOptions() { EasyMock.expect(dnsRpcMock.create(EasyMock.eq(ZONE_INFO.toPb()), EasyMock.capture(capturedOptions))).andReturn(ZONE_INFO.toPb()); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl Zone zone = dns.create(ZONE_INFO, ZONE_FIELDS); String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.getRpcOption()); 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())); + assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.getSelector())); + assertTrue(selector.contains(Dns.ZoneField.NAME.getSelector())); } @Test @@ -161,7 +161,7 @@ public void testGetZone() { EasyMock.expect(dnsRpcMock.getZone(ZONE_INFO.getName(), EMPTY_RPC_OPTIONS)) .andReturn(ZONE_INFO.toPb()); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl Zone zone = dns.getZone(ZONE_INFO.getName()); assertEquals(new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)), zone); } @@ -172,12 +172,12 @@ public void testGetZoneWithOptions() { EasyMock.expect(dnsRpcMock.getZone(EasyMock.eq(ZONE_INFO.getName()), EasyMock.capture(capturedOptions))).andReturn(ZONE_INFO.toPb()); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl Zone zone = dns.getZone(ZONE_INFO.getName(), ZONE_FIELDS); String selector = (String) capturedOptions.getValue().get(ZONE_FIELDS.getRpcOption()); 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())); + assertTrue(selector.contains(Dns.ZoneField.CREATION_TIME.getSelector())); + assertTrue(selector.contains(Dns.ZoneField.NAME.getSelector())); } @Test @@ -185,7 +185,7 @@ public void testDeleteZone() { EasyMock.expect(dnsRpcMock.deleteZone(ZONE_INFO.getName())) .andReturn(true); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl assertTrue(dns.delete(ZONE_INFO.getName())); } @@ -194,7 +194,7 @@ public void testGetProject() { EasyMock.expect(dnsRpcMock.getProject(EMPTY_RPC_OPTIONS)) .andReturn(PROJECT_INFO.toPb()); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl ProjectInfo projectInfo = dns.getProject(); assertEquals(PROJECT_INFO, projectInfo); } @@ -205,12 +205,12 @@ public void testProjectGetWithOptions() { EasyMock.expect(dnsRpcMock.getProject(EasyMock.capture(capturedOptions))) .andReturn(PROJECT_INFO.toPb()); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl ProjectInfo projectInfo = dns.getProject(PROJECT_FIELDS); String selector = (String) capturedOptions.getValue().get(PROJECT_FIELDS.getRpcOption()); assertEquals(PROJECT_INFO, projectInfo); - assertTrue(selector.contains(Dns.ProjectField.QUOTA.selector())); - assertTrue(selector.contains(Dns.ProjectField.PROJECT_ID.selector())); + assertTrue(selector.contains(Dns.ProjectField.QUOTA.getSelector())); + assertTrue(selector.contains(Dns.ProjectField.PROJECT_ID.getSelector())); } @Test @@ -219,7 +219,7 @@ public void testGetChangeRequest() { CHANGE_REQUEST_COMPLETE.getGeneratedId(), EMPTY_RPC_OPTIONS)) .andReturn(CHANGE_REQUEST_COMPLETE.toPb()); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl ChangeRequest changeRequest = dns.getChangeRequest(ZONE_INFO.getName(), CHANGE_REQUEST_COMPLETE.getGeneratedId()); assertEquals(new ChangeRequest(dns, ZONE_INFO.getName(), @@ -233,14 +233,14 @@ public void testGetChangeRequestWithOptions() { EasyMock.eq(CHANGE_REQUEST_COMPLETE.getGeneratedId()), EasyMock.capture(capturedOptions))) .andReturn(CHANGE_REQUEST_COMPLETE.toPb()); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl ChangeRequest changeRequest = dns.getChangeRequest(ZONE_INFO.getName(), CHANGE_REQUEST_COMPLETE.getGeneratedId(), CHANGE_GET_FIELDS); String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.getRpcOption()); assertEquals(new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); - assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); - assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); + assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.getSelector())); + assertTrue(selector.contains(Dns.ChangeRequestField.ID.getSelector())); } @Test @@ -249,7 +249,7 @@ public void testApplyChangeRequest() { CHANGE_REQUEST_PARTIAL.toPb(), EMPTY_RPC_OPTIONS)) .andReturn(CHANGE_REQUEST_COMPLETE.toPb()); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl ChangeRequest changeRequest = dns.applyChangeRequest(ZONE_INFO.getName(), CHANGE_REQUEST_PARTIAL); assertEquals(new ChangeRequest(dns, ZONE_INFO.getName(), @@ -263,14 +263,14 @@ public void testApplyChangeRequestWithOptions() { EasyMock.eq(CHANGE_REQUEST_PARTIAL.toPb()), EasyMock.capture(capturedOptions))) .andReturn(CHANGE_REQUEST_COMPLETE.toPb()); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl ChangeRequest changeRequest = dns.applyChangeRequest(ZONE_INFO.getName(), CHANGE_REQUEST_PARTIAL, CHANGE_GET_FIELDS); String selector = (String) capturedOptions.getValue().get(CHANGE_GET_FIELDS.getRpcOption()); assertEquals(new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)), changeRequest); - assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); - assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); + assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.getSelector())); + assertTrue(selector.contains(Dns.ChangeRequestField.ID.getSelector())); } // lists @@ -279,15 +279,15 @@ public void testListChangeRequests() { EasyMock.expect(dnsRpcMock.listChangeRequests(ZONE_INFO.getName(), EMPTY_RPC_OPTIONS)) .andReturn(LIST_RESULT_OF_PB_CHANGES); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl Page changeRequestPage = dns.listChangeRequests(ZONE_INFO.getName()); - assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( + assertTrue(Lists.newArrayList(changeRequestPage.getValues()).contains( new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)))); - assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( + assertTrue(Lists.newArrayList(changeRequestPage.getValues()).contains( new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_PARTIAL)))); - assertEquals(2, Lists.newArrayList(changeRequestPage.values()).size()); + assertEquals(2, Lists.newArrayList(changeRequestPage.getValues()).size()); } @Test @@ -296,23 +296,23 @@ public void testListChangeRequestsWithOptions() { 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 + dns = options.getService(); // creates DnsImpl Page changeRequestPage = dns.listChangeRequests(ZONE_NAME, CHANGE_LIST_OPTIONS); - assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( + assertTrue(Lists.newArrayList(changeRequestPage.getValues()).contains( new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_COMPLETE)))); - assertTrue(Lists.newArrayList(changeRequestPage.values()).contains( + assertTrue(Lists.newArrayList(changeRequestPage.getValues()).contains( new ChangeRequest(dns, ZONE_INFO.getName(), new ChangeRequestInfo.BuilderImpl(CHANGE_REQUEST_PARTIAL)))); - assertEquals(2, Lists.newArrayList(changeRequestPage.values()).size()); + assertEquals(2, Lists.newArrayList(changeRequestPage.getValues()).size()); Integer size = (Integer) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[0].getRpcOption()); assertEquals(MAX_SIZE, size); String selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[1].getRpcOption()); assertEquals(PAGE_TOKEN, selector); selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[2].getRpcOption()); - assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.selector())); - assertTrue(selector.contains(Dns.ChangeRequestField.ID.selector())); + assertTrue(selector.contains(Dns.ChangeRequestField.STATUS.getSelector())); + assertTrue(selector.contains(Dns.ChangeRequestField.ID.getSelector())); selector = (String) capturedOptions.getValue().get(CHANGE_LIST_OPTIONS[3].getRpcOption()); assertTrue(selector.contains(Dns.SortingOrder.ASCENDING.selector())); } @@ -322,11 +322,11 @@ public void testListZones() { EasyMock.expect(dnsRpcMock.listZones(EMPTY_RPC_OPTIONS)) .andReturn(LIST_RESULT_OF_PB_ZONES); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl Page zonePage = dns.listZones(); - assertEquals(1, Lists.newArrayList(zonePage.values()).size()); + assertEquals(1, Lists.newArrayList(zonePage.getValues()).size()); assertEquals(new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)), - Lists.newArrayList(zonePage.values()).get(0)); + Lists.newArrayList(zonePage.getValues()).get(0)); } @Test @@ -335,18 +335,18 @@ public void testListZonesWithOptions() { EasyMock.expect(dnsRpcMock.listZones(EasyMock.capture(capturedOptions))) .andReturn(LIST_RESULT_OF_PB_ZONES); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl Page zonePage = dns.listZones(ZONE_LIST_OPTIONS); - assertEquals(1, Lists.newArrayList(zonePage.values()).size()); + assertEquals(1, Lists.newArrayList(zonePage.getValues()).size()); assertEquals(new Zone(dns, new ZoneInfo.BuilderImpl(ZONE_INFO)), - Lists.newArrayList(zonePage.values()).get(0)); + Lists.newArrayList(zonePage.getValues()).get(0)); Integer size = (Integer) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[0].getRpcOption()); assertEquals(MAX_SIZE, size); String selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[1].getRpcOption()); assertEquals(PAGE_TOKEN, selector); selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[2].getRpcOption()); - assertTrue(selector.contains(Dns.ZoneField.DESCRIPTION.selector())); - assertTrue(selector.contains(Dns.ZoneField.NAME.selector())); + assertTrue(selector.contains(Dns.ZoneField.DESCRIPTION.getSelector())); + assertTrue(selector.contains(Dns.ZoneField.NAME.getSelector())); selector = (String) capturedOptions.getValue().get(ZONE_LIST_OPTIONS[3].getRpcOption()); assertEquals(DNS_NAME, selector); } @@ -356,11 +356,11 @@ public void testListRecordSets() { EasyMock.expect(dnsRpcMock.listRecordSets(ZONE_INFO.getName(), EMPTY_RPC_OPTIONS)) .andReturn(LIST_OF_PB_DNS_RECORDS); EasyMock.replay(dnsRpcMock); - dns = options.service(); // creates DnsImpl + dns = options.getService(); // creates DnsImpl Page dnsPage = dns.listRecordSets(ZONE_INFO.getName()); - assertEquals(2, Lists.newArrayList(dnsPage.values()).size()); - assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD1)); - assertTrue(Lists.newArrayList(dnsPage.values()).contains(DNS_RECORD2)); + assertEquals(2, Lists.newArrayList(dnsPage.getValues()).size()); + assertTrue(Lists.newArrayList(dnsPage.getValues()).contains(DNS_RECORD1)); + assertTrue(Lists.newArrayList(dnsPage.getValues()).contains(DNS_RECORD2)); } @Test @@ -369,11 +369,11 @@ public void testListRecordSetsWithOptions() { 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 + dns = options.getService(); // creates DnsImpl Page dnsPage = dns.listRecordSets(ZONE_NAME, RECORD_SET_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)); + assertEquals(2, Lists.newArrayList(dnsPage.getValues()).size()); + assertTrue(Lists.newArrayList(dnsPage.getValues()).contains(DNS_RECORD1)); + assertTrue(Lists.newArrayList(dnsPage.getValues()).contains(DNS_RECORD2)); Integer size = (Integer) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[0].getRpcOption()); assertEquals(MAX_SIZE, size); @@ -381,8 +381,8 @@ public void testListRecordSetsWithOptions() { .get(RECORD_SET_LIST_OPTIONS[1].getRpcOption()); assertEquals(PAGE_TOKEN, selector); selector = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[2].getRpcOption()); - assertTrue(selector.contains(Dns.RecordSetField.NAME.selector())); - assertTrue(selector.contains(Dns.RecordSetField.TTL.selector())); + assertTrue(selector.contains(Dns.RecordSetField.NAME.getSelector())); + assertTrue(selector.contains(Dns.RecordSetField.TTL.getSelector())); selector = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[3].getRpcOption()); assertEquals(RECORD_SET_LIST_OPTIONS[3].getValue(), selector); String type = (String) capturedOptions.getValue().get(RECORD_SET_LIST_OPTIONS[4] diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsTest.java index b5561235da45..4da893a769e1 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/DnsTest.java @@ -55,11 +55,11 @@ public void testRecordSetListOption() { assertEquals(DnsRpc.Option.FIELDS, recordSetListOption.getRpcOption()); assertTrue(recordSetListOption.getValue() instanceof String); assertTrue(((String) recordSetListOption.getValue()).contains( - Dns.RecordSetField.NAME.selector())); + Dns.RecordSetField.NAME.getSelector())); assertTrue(((String) recordSetListOption.getValue()).contains( - Dns.RecordSetField.TTL.selector())); + Dns.RecordSetField.TTL.getSelector())); assertTrue(((String) recordSetListOption.getValue()).contains( - Dns.RecordSetField.NAME.selector())); + Dns.RecordSetField.NAME.getSelector())); } @Test @@ -68,8 +68,8 @@ public void testZoneOption() { Dns.ZoneField.DESCRIPTION); assertEquals(DnsRpc.Option.FIELDS, fields.getRpcOption()); assertTrue(fields.getValue() instanceof String); - assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.CREATION_TIME.selector())); - assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.DESCRIPTION.selector())); + assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.CREATION_TIME.getSelector())); + assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.DESCRIPTION.getSelector())); } @Test @@ -79,9 +79,9 @@ public void testZoneList() { Dns.ZoneField.DESCRIPTION); assertEquals(DnsRpc.Option.FIELDS, fields.getRpcOption()); assertTrue(fields.getValue() instanceof String); - assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.CREATION_TIME.selector())); - assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.DESCRIPTION.selector())); - assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.NAME.selector())); + assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.CREATION_TIME.getSelector())); + assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.DESCRIPTION.getSelector())); + assertTrue(((String) fields.getValue()).contains(Dns.ZoneField.NAME.getSelector())); // page token Dns.ZoneListOption option = Dns.ZoneListOption.pageToken(PAGE_TOKEN); assertEquals(PAGE_TOKEN, option.getValue()); @@ -102,8 +102,8 @@ public void testProjectGetOption() { Dns.ProjectOption fields = Dns.ProjectOption.fields(Dns.ProjectField.QUOTA); assertEquals(DnsRpc.Option.FIELDS, fields.getRpcOption()); assertTrue(fields.getValue() instanceof String); - assertTrue(((String) fields.getValue()).contains(Dns.ProjectField.QUOTA.selector())); - assertTrue(((String) fields.getValue()).contains(Dns.ProjectField.PROJECT_ID.selector())); + assertTrue(((String) fields.getValue()).contains(Dns.ProjectField.QUOTA.getSelector())); + assertTrue(((String) fields.getValue()).contains(Dns.ProjectField.PROJECT_ID.getSelector())); } @Test @@ -114,9 +114,9 @@ public void testChangeRequestOption() { assertEquals(DnsRpc.Option.FIELDS, fields.getRpcOption()); assertTrue(fields.getValue() instanceof String); assertTrue(((String) fields.getValue()).contains( - Dns.ChangeRequestField.START_TIME.selector())); - assertTrue(((String) fields.getValue()).contains(Dns.ChangeRequestField.STATUS.selector())); - assertTrue(((String) fields.getValue()).contains(Dns.ChangeRequestField.ID.selector())); + Dns.ChangeRequestField.START_TIME.getSelector())); + assertTrue(((String) fields.getValue()).contains(Dns.ChangeRequestField.STATUS.getSelector())); + assertTrue(((String) fields.getValue()).contains(Dns.ChangeRequestField.ID.getSelector())); } @Test @@ -127,9 +127,9 @@ public void testChangeRequestListOption() { assertEquals(DnsRpc.Option.FIELDS, fields.getRpcOption()); assertTrue(fields.getValue() instanceof String); assertTrue(((String) fields.getValue()).contains( - Dns.ChangeRequestField.START_TIME.selector())); - assertTrue(((String) fields.getValue()).contains(Dns.ChangeRequestField.STATUS.selector())); - assertTrue(((String) fields.getValue()).contains(Dns.ChangeRequestField.ID.selector())); + Dns.ChangeRequestField.START_TIME.getSelector())); + assertTrue(((String) fields.getValue()).contains(Dns.ChangeRequestField.STATUS.getSelector())); + assertTrue(((String) fields.getValue()).contains(Dns.ChangeRequestField.ID.getSelector())); // page token Dns.ChangeRequestListOption option = Dns.ChangeRequestListOption.pageToken(PAGE_TOKEN); assertEquals(PAGE_TOKEN, option.getValue()); diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java index 15af4d07c6a9..3434a5cf8280 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/SerializationTest.java @@ -56,11 +56,11 @@ public class SerializationTest extends BaseSerializationTest { 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()) + private static final DnsOptions OPTIONS = DnsOptions.newBuilder() + .setProjectId("some-unnecessary-project-ID") + .setRetryParams(RetryParams.getDefaultInstance()) .build(); - private static final Dns DNS = OPTIONS.service(); + private static final Dns DNS = OPTIONS.getService(); 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)); @@ -88,12 +88,12 @@ public class SerializationTest extends BaseSerializationTest { @Override protected Serializable[] serializableObjects() { - DnsOptions options = DnsOptions.builder() - .authCredentials(AuthCredentials.createForAppEngine()) - .projectId("id1") + DnsOptions options = DnsOptions.newBuilder() + .setAuthCredentials(AuthCredentials.createForAppEngine()) + .setProjectId("id1") .build(); DnsOptions otherOptions = options.toBuilder() - .authCredentials(null) + .setAuthCredentials(null) .build(); 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, diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/ZoneTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/ZoneTest.java index 05846d120fd6..f4f73a0ffbe8 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/ZoneTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/ZoneTest.java @@ -75,7 +75,7 @@ public class ZoneTest { @Before public void setUp() throws Exception { dns = createStrictMock(Dns.class); - expect(dns.options()).andReturn(OPTIONS).times(3); + expect(dns.getOptions()).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)); @@ -476,14 +476,14 @@ public void listChangeRequestsAndZoneNotFound() { @Test public void testFromPb() { - expect(dns.options()).andReturn(OPTIONS); + expect(dns.getOptions()).andReturn(OPTIONS); replay(dns); assertEquals(Zone.fromPb(dns, zone.toPb()), zone); } @Test public void testEqualsAndToBuilder() { - expect(dns.options()).andReturn(OPTIONS).times(2); + expect(dns.getOptions()).andReturn(OPTIONS).times(2); replay(dns); assertEquals(zone, zone.toBuilder().build()); assertEquals(zone.hashCode(), zone.toBuilder().build().hashCode()); @@ -492,7 +492,7 @@ public void testEqualsAndToBuilder() { @Test public void testBuilder() { // one for each build() call because it invokes a constructor - expect(dns.options()).andReturn(OPTIONS).times(8); + expect(dns.getOptions()).andReturn(OPTIONS).times(8); replay(dns); assertNotEquals(zone, zone.toBuilder() .setGeneratedId(new BigInteger(zone.getGeneratedId()).add(BigInteger.ONE).toString()) @@ -516,7 +516,7 @@ public void testBuilder() { @Test public void testBuilderDeprecated() { // one for each build() call because it invokes a constructor - expect(dns.options()).andReturn(OPTIONS).times(8); + expect(dns.getOptions()).andReturn(OPTIONS).times(8); replay(dns); assertNotEquals(zone, zone.toBuilder() .setGeneratedId(new BigInteger(zone.generatedId()).add(BigInteger.ONE).toString()) diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/it/ITDnsTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/it/ITDnsTest.java index f3dabf2fdfcb..1da588be5398 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/it/ITDnsTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/it/ITDnsTest.java @@ -57,7 +57,7 @@ public class ITDnsTest { private static final String PREFIX = "gcldjvit-"; - private static final Dns DNS = DnsOptions.defaultInstance().service(); + private static final Dns DNS = DnsOptions.getDefaultInstance().getService(); 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); @@ -209,14 +209,14 @@ public void testCreateZoneWithErrors() { fail("Zone name is too long. The service returns an error."); } catch (DnsException ex) { // expected - assertFalse(ex.retryable()); + assertFalse(ex.isRetryable()); } try { DNS.create(ZONE_DNS_NO_PERIOD); fail("Zone name is missing a period. The service returns an error."); } catch (DnsException ex) { // expected - assertFalse(ex.retryable()); + assertFalse(ex.isRetryable()); } } finally { DNS.delete(ZONE_NAME_ERROR.getName()); @@ -400,16 +400,16 @@ public void testListZones() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } try { DNS.listZones(Dns.ZoneListOption.pageSize(-1)); fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } // ok size zones = filter(DNS.listZones(Dns.ZoneListOption.pageSize(1000)).iterateAll()); @@ -420,8 +420,8 @@ public void testListZones() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } // ok name zones = filter(DNS.listZones(Dns.ZoneListOption.dnsName(ZONE1.getDnsName())).iterateAll()); @@ -611,8 +611,8 @@ public void testInvalidChangeRequest() { fail("Created a record set which already exists."); } catch (DnsException ex) { // expected - assertFalse(ex.retryable()); - assertEquals(409, ex.code()); + assertFalse(ex.isRetryable()); + assertEquals(409, ex.getCode()); } // delete with field mismatch RecordSet mismatch = validA.toBuilder().setTtl(20, TimeUnit.SECONDS).build(); @@ -622,8 +622,8 @@ public void testInvalidChangeRequest() { fail("Deleted a record set without a complete match."); } catch (DnsException ex) { // expected - assertEquals(412, ex.code()); - assertFalse(ex.retryable()); + assertEquals(412, ex.getCode()); + assertFalse(ex.isRetryable()); } // delete and add SOA Iterator recordSetIterator = zone.listRecordSets().iterateAll(); @@ -646,16 +646,16 @@ public void testInvalidChangeRequest() { fail("Deleted SOA."); } catch (DnsException ex) { // expected - assertFalse(ex.retryable()); - assertEquals(400, ex.code()); + assertFalse(ex.isRetryable()); + assertEquals(400, ex.getCode()); } try { zone.applyChangeRequest(addition); fail("Added second SOA."); } catch (DnsException ex) { // expected - assertFalse(ex.retryable()); - assertEquals(400, ex.code()); + assertFalse(ex.isRetryable()); + assertEquals(400, ex.getCode()); } } finally { if (recordAdded) { @@ -676,8 +676,8 @@ public void testListChanges() { fail(); } catch (DnsException ex) { // expected - assertEquals(404, ex.code()); - assertFalse(ex.retryable()); + assertEquals(404, ex.getCode()); + assertFalse(ex.isRetryable()); } // zone exists but has no changes DNS.create(ZONE1); @@ -701,16 +701,16 @@ public void testListChanges() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } try { DNS.listChangeRequests(ZONE1.getName(), Dns.ChangeRequestListOption.pageSize(-1)); fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } // sorting order ImmutableList ascending = ImmutableList.copyOf(DNS.listChangeRequests( @@ -909,7 +909,7 @@ public void testListDnsRecords() { Page recordSetPage = DNS.listRecordSets(zone.getName(), Dns.RecordSetListOption.fields(RecordSetField.TYPE), Dns.RecordSetListOption.pageSize(1)); - assertEquals(1, ImmutableList.copyOf(recordSetPage.values().iterator()).size()); + assertEquals(1, ImmutableList.copyOf(recordSetPage.getValues().iterator()).size()); // test name filter ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); @@ -944,24 +944,24 @@ public void testListDnsRecords() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } try { DNS.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(0)); fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } try { DNS.listRecordSets(ZONE1.getName(), Dns.RecordSetListOption.pageSize(-1)); fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); } finally { @@ -1028,27 +1028,27 @@ public void testListZonesBatch() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } try { negativeSizeError.get(); fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } // ok size - assertEquals(1, Iterables.size(okSize.get().values())); + assertEquals(1, Iterables.size(okSize.get().getValues())); // dns name problems try { nameError.get(); fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } // ok name zones = filter(okName.get().iterateAll()); @@ -1177,14 +1177,14 @@ public void testCreateZoneWithErrorsBatch() { fail("Zone name is too long. The service returns an error."); } catch (DnsException ex) { // expected - assertFalse(ex.retryable()); + assertFalse(ex.isRetryable()); } try { noPeriodResult.get(); fail("Zone name is missing a period. The service returns an error."); } catch (DnsException ex) { // expected - assertFalse(ex.retryable()); + assertFalse(ex.isRetryable()); } } finally { DNS.delete(ZONE_NAME_ERROR.getName()); @@ -1599,15 +1599,16 @@ public void testListChangesBatch() { fail("Zone does not exist yet"); } catch (DnsException ex) { // expected - assertEquals(404, ex.code()); - assertFalse(ex.retryable()); + assertEquals(404, ex.getCode()); + assertFalse(ex.isRetryable()); } // zone exists but has no changes DNS.create(ZONE1); batch = DNS.batch(); result = batch.listChangeRequests(ZONE1.getName()); batch.submit(); - assertEquals(1, Iterables.size(result.get().values())); // default change creating SOA and NS + // default change creating SOA and NS + assertEquals(1, Iterables.size(result.get().getValues())); // zone has changes ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); @@ -1644,23 +1645,23 @@ public void testListChangesBatch() { Dns.ChangeRequestListOption.sortOrder(Dns.SortingOrder.ASCENDING), Dns.ChangeRequestListOption.fields(ChangeRequestField.STATUS)); batch.submit(); - assertEquals(3, Iterables.size(result.get().values())); + assertEquals(3, Iterables.size(result.get().getValues())); // error in options try { errorPageSize.get(); fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } try { errorPageNegative.get(); fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } // sorting order ImmutableList ascending = @@ -1674,31 +1675,31 @@ public void testListChangesBatch() { assertEquals(descending.get(i), ascending.get(size - i - 1)); } // field options - change = Iterables.get(resultAdditions.get().values(), 1); + change = Iterables.get(resultAdditions.get().getValues(), 1); assertEquals(CHANGE_ADD_ZONE1.getAdditions(), change.getAdditions()); assertTrue(change.getDeletions().isEmpty()); assertNotNull(change.getGeneratedId()); assertNull(change.getStartTimeMillis()); assertNull(change.status()); - change = Iterables.get(resultDeletions.get().values(), 2); + change = Iterables.get(resultDeletions.get().getValues(), 2); assertTrue(change.getAdditions().isEmpty()); assertNotNull(change.getDeletions()); assertNotNull(change.getGeneratedId()); assertNull(change.getStartTimeMillis()); assertNull(change.status()); - change = Iterables.get(resultId.get().values(), 1); + change = Iterables.get(resultId.get().getValues(), 1); assertTrue(change.getAdditions().isEmpty()); assertTrue(change.getDeletions().isEmpty()); assertNotNull(change.getGeneratedId()); assertNull(change.getStartTimeMillis()); assertNull(change.status()); - change = Iterables.get(resultTime.get().values(), 1); + change = Iterables.get(resultTime.get().getValues(), 1); assertTrue(change.getAdditions().isEmpty()); assertTrue(change.getDeletions().isEmpty()); assertNotNull(change.getGeneratedId()); assertNotNull(change.getStartTimeMillis()); assertNull(change.status()); - change = Iterables.get(resultStatus.get().values(), 1); + change = Iterables.get(resultStatus.get().getValues(), 1); assertTrue(change.getAdditions().isEmpty()); assertTrue(change.getDeletions().isEmpty()); assertNotNull(change.getGeneratedId()); @@ -1781,7 +1782,7 @@ public void testListDnsRecordSetsBatch() { assertEquals(2, counter); // test page size Page recordSetPage = pageSizeResult.get(); - assertEquals(1, ImmutableList.copyOf(recordSetPage.values().iterator()).size()); + assertEquals(1, ImmutableList.copyOf(recordSetPage.getValues().iterator()).size()); // test name filter ChangeRequest change = DNS.applyChangeRequest(ZONE1.getName(), CHANGE_ADD_ZONE1); waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); @@ -1827,24 +1828,24 @@ public void testListDnsRecordSetsBatch() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } try { zeroSizeError.get(); fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } try { negativeSizeError.get(); fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); - assertFalse(ex.retryable()); + assertEquals(400, ex.getCode()); + assertFalse(ex.isRetryable()); } waitForChangeToComplete(ZONE1.getName(), change.getGeneratedId()); } finally { @@ -1878,7 +1879,7 @@ public void testBatchCombined() { assertNull(zoneResult.get().getNameServerSet()); // we did not set it assertNotNull(zoneResult.get().getGeneratedId()); assertNotNull(projectResult.get().getQuota()); - assertEquals(2, Iterables.size(pageResult.get().values())); + assertEquals(2, Iterables.size(pageResult.get().getValues())); assertNotNull(changeRequestResult.get()); } finally { DNS.delete(ZONE1.getName()); diff --git a/google-cloud-dns/src/test/java/com/google/cloud/dns/testing/LocalDnsHelperTest.java b/google-cloud-dns/src/test/java/com/google/cloud/dns/testing/LocalDnsHelperTest.java index fd9ee2126013..6f98874b5a48 100644 --- a/google-cloud-dns/src/test/java/com/google/cloud/dns/testing/LocalDnsHelperTest.java +++ b/google-cloud-dns/src/test/java/com/google/cloud/dns/testing/LocalDnsHelperTest.java @@ -75,7 +75,7 @@ public class LocalDnsHelperTest { private static final LocalDnsHelper LOCAL_DNS_HELPER = LocalDnsHelper.create(0L); private static final Map EMPTY_RPC_OPTIONS = ImmutableMap.of(); private static final DnsRpc RPC = new DefaultDnsRpc(LOCAL_DNS_HELPER.getOptions()); - private static final String REAL_PROJECT_ID = LOCAL_DNS_HELPER.getOptions().projectId(); + private static final String REAL_PROJECT_ID = LOCAL_DNS_HELPER.getOptions().getProjectId(); private Map optionsMap; private static abstract class FailExpectedCallback implements RpcBatch.Callback { @@ -162,7 +162,7 @@ public void testCreateZone() { fail("Zone cannot be null"); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("entity.managedZone")); } // create zone twice @@ -171,7 +171,7 @@ public void testCreateZone() { fail("Zone already exists."); } catch (DnsException ex) { // expected - assertEquals(409, ex.code()); + assertEquals(409, ex.getCode()); assertTrue(ex.getMessage().contains("already exists")); } // field options @@ -352,7 +352,7 @@ public void testDeleteZone() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("not empty")); } } @@ -366,7 +366,7 @@ public void testCreateAndApplyChange() { public void testCreateAndApplyChangeWithThreads() { LocalDnsHelper localDnsThreaded = LocalDnsHelper.create(50L); localDnsThreaded.start(); - DnsRpc rpc = new DefaultDnsRpc(localDnsThreaded.options()); + DnsRpc rpc = new DefaultDnsRpc(localDnsThreaded.getOptions()); executeCreateAndApplyChangeTest(rpc); localDnsThreaded.stop(); } @@ -399,7 +399,7 @@ private static void executeCreateAndApplyChangeTest(DnsRpc rpc) { rpc.applyChangeRequest(ZONE1.getName(), CHANGE1, EMPTY_RPC_OPTIONS); fail(); } catch (DnsException ex) { - assertEquals(409, ex.code()); + assertEquals(409, ex.getCode()); assertTrue(ex.getMessage().contains("already exists")); } assertNotNull(rpc.getChangeRequest(ZONE1.getName(), "1", EMPTY_RPC_OPTIONS)); @@ -465,7 +465,7 @@ public void testCreateChange() { RPC.applyChangeRequest(ZONE_NAME1, CHANGE1, EMPTY_RPC_OPTIONS); fail("Zone was not created yet."); } catch (DnsException ex) { - assertEquals(404, ex.code()); + assertEquals(404, ex.getCode()); } // existent zone RPC.create(ZONE1, EMPTY_RPC_OPTIONS); @@ -527,7 +527,7 @@ public void testGetChange() { fail(); } catch (DnsException ex) { // expected - assertEquals(404, ex.code()); + assertEquals(404, ex.getCode()); assertTrue(ex.getMessage().contains("managedZone")); } // field options @@ -595,7 +595,7 @@ public void testListZones() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("parameters.maxResults")); } options = new HashMap<>(); @@ -605,7 +605,7 @@ public void testListZones() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("parameters.maxResults")); } // ok size @@ -622,7 +622,7 @@ public void testListZones() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("parameters.dnsName")); } // ok name @@ -713,7 +713,7 @@ public void testListRecordSets() { fail(); } catch (DnsException ex) { // expected - assertEquals(404, ex.code()); + assertEquals(404, ex.getCode()); assertTrue(ex.getMessage().contains("managedZone")); } // zone exists but has no records @@ -735,7 +735,7 @@ public void testListRecordSets() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("parameters.maxResults")); } options.put(DnsRpc.Option.PAGE_SIZE, -1); @@ -744,7 +744,7 @@ public void testListRecordSets() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("parameters.maxResults")); } options.put(DnsRpc.Option.PAGE_SIZE, 15); @@ -759,7 +759,7 @@ public void testListRecordSets() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("parameters.name")); } options.put(DnsRpc.Option.NAME, "aaa."); @@ -773,7 +773,7 @@ public void testListRecordSets() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("parameters.name")); } options.put(DnsRpc.Option.NAME, "aaa."); @@ -783,7 +783,7 @@ public void testListRecordSets() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("parameters.type")); } options.put(DnsRpc.Option.NAME, DNS_NAME); @@ -860,7 +860,7 @@ public void testListChanges() { fail(); } catch (DnsException ex) { // expected - assertEquals(404, ex.code()); + assertEquals(404, ex.getCode()); assertTrue(ex.getMessage().contains("managedZone")); } // zone exists but has no changes @@ -883,7 +883,7 @@ public void testListChanges() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("parameters.maxResults")); } options.put(DnsRpc.Option.PAGE_SIZE, -1); @@ -892,7 +892,7 @@ public void testListChanges() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("parameters.maxResults")); } options.put(DnsRpc.Option.PAGE_SIZE, 15); @@ -916,7 +916,7 @@ public void testListChanges() { fail(); } catch (DnsException ex) { // expected - assertEquals(400, ex.code()); + assertEquals(400, ex.getCode()); assertTrue(ex.getMessage().contains("parameters.sortOrder")); } // field options diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/BigQueryExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/BigQueryExample.java index 7478fa7e20c9..eb59e1aa9ab1 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/BigQueryExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/BigQueryExample.java @@ -755,12 +755,12 @@ public static void main(String... args) throws Exception { printUsage(); return; } - BigQueryOptions.Builder optionsBuilder = BigQueryOptions.builder(); + BigQueryOptions.Builder optionsBuilder = BigQueryOptions.newBuilder(); BigQueryAction action; String actionName; if (args.length >= 2 && !ACTIONS.containsKey(args[0])) { actionName = args[1]; - optionsBuilder.projectId(args[0]); + optionsBuilder.setProjectId(args[0]); action = ACTIONS.get(args[1]); args = Arrays.copyOfRange(args, 2, args.length); } else { @@ -773,7 +773,7 @@ public static void main(String... args) throws Exception { printUsage(); return; } - BigQuery bigquery = optionsBuilder.build().service(); + BigQuery bigquery = optionsBuilder.build().getService(); Object arg; try { arg = action.parse(args); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/CreateTableAndLoadData.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/CreateTableAndLoadData.java index 02f3f70fd51a..ad29925cd6bd 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/CreateTableAndLoadData.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/CreateTableAndLoadData.java @@ -43,7 +43,7 @@ public class CreateTableAndLoadData { public static void main(String... args) throws InterruptedException, TimeoutException { - BigQuery bigquery = BigQueryOptions.defaultInstance().service(); + BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); TableId tableId = TableId.of("dataset", "table"); Table table = bigquery.getTable(tableId); if (table == null) { diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/InsertDataAndQueryTable.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/InsertDataAndQueryTable.java index a57e42fb7417..c1ed6e695f95 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/InsertDataAndQueryTable.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/bigquery/snippets/InsertDataAndQueryTable.java @@ -49,7 +49,7 @@ public class InsertDataAndQueryTable { public static void main(String... args) throws InterruptedException { // Create a service instance - BigQuery bigquery = BigQueryOptions.defaultInstance().service(); + BigQuery bigquery = BigQueryOptions.getDefaultInstance().getService(); // Create a dataset String datasetId = "my_dataset_id"; diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/ComputeExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/ComputeExample.java index bea18bedc3c0..d64673868cc2 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/ComputeExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/ComputeExample.java @@ -2500,12 +2500,12 @@ public static void main(String... args) throws Exception { printUsage(); return; } - ComputeOptions.Builder optionsBuilder = ComputeOptions.builder(); + ComputeOptions.Builder optionsBuilder = ComputeOptions.newBuilder(); ComputeAction action; String actionName; if (args.length >= 2 && !ACTIONS.containsKey(args[0])) { actionName = args[1]; - optionsBuilder.projectId(args[0]); + optionsBuilder.setProjectId(args[0]); action = ACTIONS.get(args[1]); args = Arrays.copyOfRange(args, 2, args.length); } else { @@ -2518,7 +2518,7 @@ public static void main(String... args) throws Exception { printUsage(); return; } - Compute compute = optionsBuilder.build().service(); + Compute compute = optionsBuilder.build().getService(); Object arg; try { arg = action.parse(args); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateAddressDiskAndInstance.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateAddressDiskAndInstance.java index 2e0834fa600b..d1176a67a4cc 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateAddressDiskAndInstance.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateAddressDiskAndInstance.java @@ -46,7 +46,7 @@ public class CreateAddressDiskAndInstance { public static void main(String... args) throws InterruptedException, TimeoutException { // Create a service object // Credentials are inferred from the environment. - Compute compute = ComputeOptions.defaultInstance().service(); + Compute compute = ComputeOptions.getDefaultInstance().getService(); // Create an external region address RegionAddressId addressId = RegionAddressId.of("us-central1", "test-address"); @@ -56,7 +56,7 @@ public static void main(String... args) throws InterruptedException, TimeoutExce if (operation.getErrors() == null) { System.out.println("Address " + addressId + " was successfully created"); } else { - // inspect operation.errors() + // inspect operation.getErrors() throw new RuntimeException("Address creation failed"); } @@ -71,7 +71,7 @@ public static void main(String... args) throws InterruptedException, TimeoutExce if (operation.getErrors() == null) { System.out.println("Disk " + diskId + " was successfully created"); } else { - // inspect operation.errors() + // inspect operation.getErrors() throw new RuntimeException("Disk creation failed"); } @@ -94,7 +94,7 @@ public static void main(String... args) throws InterruptedException, TimeoutExce if (operation.getErrors() == null) { System.out.println("Instance " + instanceId + " was successfully created"); } else { - // inspect operation.errors() + // inspect operation.getErrors() throw new RuntimeException("Instance creation failed"); } } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateInstance.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateInstance.java index 0d55dfa3e52f..1e70c0741268 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateInstance.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateInstance.java @@ -36,7 +36,7 @@ public class CreateInstance { public static void main(String... args) throws InterruptedException, TimeoutException { - Compute compute = ComputeOptions.defaultInstance().service(); + Compute compute = ComputeOptions.getDefaultInstance().getService(); ImageId imageId = ImageId.of("debian-cloud", "debian-8-jessie-v20160329"); NetworkId networkId = NetworkId.of("default"); AttachedDisk attachedDisk = AttachedDisk.of(AttachedDisk.CreateDiskConfiguration.of(imageId)); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateSnapshot.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateSnapshot.java index 8c221d6bb5f6..d54464c36c7f 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateSnapshot.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/compute/snippets/CreateSnapshot.java @@ -32,7 +32,7 @@ public class CreateSnapshot { public static void main(String... args) throws InterruptedException, TimeoutException { - Compute compute = ComputeOptions.defaultInstance().service(); + Compute compute = ComputeOptions.getDefaultInstance().getService(); DiskId diskId = DiskId.of("us-central1-a", "disk-name"); Disk disk = compute.getDisk(diskId, Compute.DiskOption.fields()); if (disk != null) { diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/DatastoreExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/DatastoreExample.java index 515d1ceac5d4..fb4385249117 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/DatastoreExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/DatastoreExample.java @@ -286,15 +286,16 @@ private static void printUsage() { public static void main(String... args) throws Exception { String projectId = args.length > 0 ? args[0] : null; // If you want to access a local Datastore running via the Google Cloud SDK, do - // DatastoreOptions options = DatastoreOptions.builder() - // .projectId(projectId) - // .namespace(NAMESPACE) - // .host("http://localhost:8080") // change 8080 to the port that the emulator listens to + // DatastoreOptions options = DatastoreOptions.newBuilder() + // .setProjectId(projectId) + // .setNamespace(NAMESPACE) + // // change 8080 to the port that the emulator listens to + // .setHost("http://localhost:8080") // .build(); DatastoreOptions options = - DatastoreOptions.builder().projectId(projectId).namespace(NAMESPACE).build(); + DatastoreOptions.newBuilder().setProjectId(projectId).namespace(NAMESPACE).build(); String name = args.length > 1 ? args[1] : System.getProperty("user.getName"); - Datastore datastore = options.service(); + Datastore datastore = options.getService(); KeyFactory keyFactory = datastore.newKeyFactory().setKind(USER_KIND); Key key = keyFactory.newKey(name); String actionName = args.length > 2 ? args[2].toLowerCase() : DEFAULT_ACTION; diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java index 122d93dbb637..917252640b88 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/AddEntitiesAndRunQuery.java @@ -40,7 +40,7 @@ public class AddEntitiesAndRunQuery { public static void main(String... args) { // Create datastore service object. // By default, credentials are inferred from the runtime environment. - Datastore datastore = DatastoreOptions.defaultInstance().service(); + Datastore datastore = DatastoreOptions.getDefaultInstance().getService(); // Add an entity to Datastore KeyFactory keyFactory = datastore.newKeyFactory().setKind("Person"); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/CreateEntity.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/CreateEntity.java index 9da67416f34b..731ae9c7c1fa 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/CreateEntity.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/CreateEntity.java @@ -35,7 +35,7 @@ public class CreateEntity { public static void main(String... args) { - Datastore datastore = DatastoreOptions.defaultInstance().service(); + Datastore datastore = DatastoreOptions.getDefaultInstance().getService(); KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind"); Key key = keyFactory.newKey("keyName"); Entity entity = Entity.newBuilder(key) diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/UpdateEntity.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/UpdateEntity.java index ce423b2535c4..43ec52a1648f 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/UpdateEntity.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/datastore/snippets/UpdateEntity.java @@ -35,7 +35,7 @@ public class UpdateEntity { public static void main(String... args) { - Datastore datastore = DatastoreOptions.defaultInstance().service(); + Datastore datastore = DatastoreOptions.getDefaultInstance().getService(); KeyFactory keyFactory = datastore.newKeyFactory().setKind("keyKind"); Key key = keyFactory.newKey("keyName"); Entity entity = datastore.get(key); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/DnsExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/DnsExample.java index 783cccb699d6..ec9492d5a2c3 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/DnsExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/DnsExample.java @@ -404,7 +404,7 @@ private static class GetProjectAction implements DnsAction { public void run(Dns dns, String... args) { ProjectInfo project = dns.getProject(); ProjectInfo.Quota quota = project.getQuota(); - System.out.printf("Project id: %s%nQuota:%n", dns.options().projectId()); + System.out.printf("Project id: %s%nQuota:%n", dns.getOptions().getProjectId()); System.out.printf("\tZones: %d%n", quota.getZones()); System.out.printf("\tRecord sets per zone: %d%n", quota.getRrsetsPerZone()); System.out.printf("\tRecord sets per DNS record: %d%n", @@ -510,11 +510,11 @@ public static void main(String... args) throws Exception { return; } if (valid) { - DnsOptions.Builder optionsBuilder = DnsOptions.builder(); + DnsOptions.Builder optionsBuilder = DnsOptions.newBuilder(); if (projectId != null) { - optionsBuilder.projectId(projectId); + optionsBuilder.setProjectId(projectId); } - Dns dns = optionsBuilder.build().service(); + Dns dns = optionsBuilder.build().getService(); action.run(dns, args); } else { System.out.printf("Invalid input for action '%s'%n", actionName); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateOrUpdateRecordSets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateOrUpdateRecordSets.java index 997e35e6a8e6..e1bfc163e849 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateOrUpdateRecordSets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateOrUpdateRecordSets.java @@ -39,7 +39,7 @@ public class CreateOrUpdateRecordSets { 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(); + Dns dns = DnsOptions.getDefaultInstance().getService(); // Change this to a zone name that exists within your project String zoneName = "my-unique-zone"; diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateZone.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateZone.java index 57939ca9e07a..979fde43e465 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateZone.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/CreateZone.java @@ -36,7 +36,7 @@ public class CreateZone { 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(); + Dns dns = DnsOptions.getDefaultInstance().getService(); // Create a zone metadata object String zoneName = "my-unique-zone"; // Change this zone name which is unique within your project diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/DeleteZone.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/DeleteZone.java index 1202c66b51ac..009c7910d2dc 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/DeleteZone.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/DeleteZone.java @@ -39,7 +39,7 @@ 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(); + Dns dns = DnsOptions.getDefaultInstance().getService(); // Change this to a zone name that exists within your project and that you want to delete. String zoneName = "my-unique-zone"; diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java index 1cfa768c220e..b0b43bedd939 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/dns/snippets/ManipulateZonesAndRecordSets.java @@ -41,7 +41,7 @@ public class ManipulateZonesAndRecordSets { public static void main(String... args) { - Dns dns = DnsOptions.defaultInstance().service(); + Dns dns = DnsOptions.getDefaultInstance().getService(); // Create a zone metadata object String zoneName = "my-unique-zone"; // Change this zone name which is unique within your project diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/LoggingExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/LoggingExample.java index 3cab8c4dd3de..20265cc2c6ac 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/LoggingExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/LoggingExample.java @@ -396,7 +396,7 @@ private static class WriteEntryAction extends LoggingAction { @Override public void run(Logging logging, LogEntry entry) { MonitoredResource resource = MonitoredResource.newBuilder("global") - .addLabel("project_id", logging.options().projectId()) + .addLabel("project_id", logging.getOptions().getProjectId()) .build(); LogEntry entryWithResource = entry.toBuilder().setResource(resource).build(); logging.write(Collections.singleton(entryWithResource)); @@ -540,12 +540,12 @@ public static void main(String... args) throws Exception { printUsage(); return; } - LoggingOptions.Builder optionsBuilder = LoggingOptions.builder(); + LoggingOptions.Builder optionsBuilder = LoggingOptions.newBuilder(); LoggingAction action; String actionName; if (args.length >= 2 && !ACTIONS.containsKey(args[0])) { actionName = args[1]; - optionsBuilder.projectId(args[0]); + optionsBuilder.setProjectId(args[0]); action = ACTIONS.get(args[1]); args = Arrays.copyOfRange(args, 2, args.length); } else { @@ -558,7 +558,7 @@ public static void main(String... args) throws Exception { printUsage(); return; } - try (Logging logging = optionsBuilder.build().service()) { + try (Logging logging = optionsBuilder.build().getService()) { Object arg; try { arg = action.parse(args); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListMetrics.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListMetrics.java index 151b5428910b..0707aea1ae2f 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListMetrics.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListMetrics.java @@ -36,7 +36,7 @@ public class CreateAndListMetrics { public static void main(String... args) throws Exception { // Create a service object // Credentials are inferred from the environment - try(Logging logging = LoggingOptions.defaultInstance().service()) { + try(Logging logging = LoggingOptions.getDefaultInstance().getService()) { // Create a metric MetricInfo metricInfo = MetricInfo.newBuilder("test-metric", "severity >= ERROR") diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListSinks.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListSinks.java index cb5b378bd7b5..7bd363280a0f 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListSinks.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/CreateAndListSinks.java @@ -36,7 +36,7 @@ public class CreateAndListSinks { public static void main(String... args) throws Exception { // Create a service object // Credentials are inferred from the environment - try(Logging logging = LoggingOptions.defaultInstance().service()) { + try(Logging logging = LoggingOptions.getDefaultInstance().getService()) { // Create a sink to back log entries to a BigQuery dataset SinkInfo sinkInfo = SinkInfo.newBuilder("test-sink", DatasetDestination.of("test-dataset")) diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/LoggingSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/LoggingSnippets.java index a4db3bb185fa..be7491d266d9 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/LoggingSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/LoggingSnippets.java @@ -58,7 +58,7 @@ public LoggingSnippets(Logging logging) { /** * Example of creating a sink to export logs to a BigQuery dataset (in the - * {@link LoggingOptions#projectId()} project). + * {@link LoggingOptions#getProjectId()} project). */ // [TARGET create(SinkInfo)] // [VARIABLE "my_sink_name"] @@ -73,7 +73,7 @@ public Sink createSink(String sinkName, String datasetName) { /** * Example of asynchronously creating a sink to export logs to a BigQuery dataset (in the - * {@link LoggingOptions#projectId()} project). + * {@link LoggingOptions#getProjectId()} project). */ // [TARGET createAsync(SinkInfo)] // [VARIABLE "my_sink_name"] diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/WriteAndListLogEntries.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/WriteAndListLogEntries.java index cc0b8fe175c8..825159e30bc2 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/WriteAndListLogEntries.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/logging/snippets/WriteAndListLogEntries.java @@ -38,21 +38,21 @@ public class WriteAndListLogEntries { public static void main(String... args) throws Exception { // Create a service object // Credentials are inferred from the environment - LoggingOptions options = LoggingOptions.defaultInstance(); - try(Logging logging = options.service()) { + LoggingOptions options = LoggingOptions.getDefaultInstance(); + try(Logging logging = options.getService()) { // Create a log entry LogEntry firstEntry = LogEntry.newBuilder(StringPayload.of("message")) .setLogName("test-log") .setResource(MonitoredResource.newBuilder("global") - .addLabel("project_id", options.projectId()) + .addLabel("project_id", options.getProjectId()) .build()) .build(); logging.write(Collections.singleton(firstEntry)); // List log entries Page entries = logging.listLogEntries( - EntryListOption.filter("logName=projects/" + options.projectId() + "/logs/test-log")); + EntryListOption.filter("logName=projects/" + options.getProjectId() + "/logs/test-log")); Iterator entryIterator = entries.iterateAll(); while (entryIterator.hasNext()) { System.out.println(entryIterator.next()); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/PubSubExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/PubSubExample.java index b1d448adaf9d..7bb34839c4a3 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/PubSubExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/PubSubExample.java @@ -861,12 +861,12 @@ public static void main(String... args) throws Exception { printUsage(); return; } - PubSubOptions.Builder optionsBuilder = PubSubOptions.builder(); + PubSubOptions.Builder optionsBuilder = PubSubOptions.newBuilder(); PubSubAction action; String actionName; if (args.length >= 2 && !ACTIONS.containsKey(args[0])) { actionName = args[1]; - optionsBuilder.projectId(args[0]); + optionsBuilder.setProjectId(args[0]); action = ACTIONS.get(args[1]); args = Arrays.copyOfRange(args, 2, args.length); } else { @@ -879,7 +879,7 @@ public static void main(String... args) throws Exception { printUsage(); return; } - try (PubSub pubsub = optionsBuilder.build().service()) { + try (PubSub pubsub = optionsBuilder.build().getService()) { Object arg; try { arg = action.parse(args); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/CreateSubscriptionAndPullMessages.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/CreateSubscriptionAndPullMessages.java index d3b6d432fde9..cab4dc44e218 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/CreateSubscriptionAndPullMessages.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/CreateSubscriptionAndPullMessages.java @@ -31,7 +31,7 @@ public class CreateSubscriptionAndPullMessages { public static void main(String... args) throws Exception { - try (PubSub pubsub = PubSubOptions.defaultInstance().service()) { + try (PubSub pubsub = PubSubOptions.getDefaultInstance().getService()) { Subscription subscription = pubsub.create(SubscriptionInfo.of("test-topic", "test-subscription")); MessageProcessor callback = new MessageProcessor() { diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/CreateTopicAndPublishMessages.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/CreateTopicAndPublishMessages.java index c6eded996be5..e57475a845e8 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/CreateTopicAndPublishMessages.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/CreateTopicAndPublishMessages.java @@ -29,7 +29,7 @@ public class CreateTopicAndPublishMessages { public static void main(String... args) throws Exception { - try (PubSub pubsub = PubSubOptions.defaultInstance().service()) { + try (PubSub pubsub = PubSubOptions.getDefaultInstance().getService()) { Topic topic = pubsub.create(TopicInfo.of("test-topic")); Message message1 = Message.of("First message"); Message message2 = Message.of("Second message"); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/ResourceManagerExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/ResourceManagerExample.java index 68589ce59582..916b2a274551 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/ResourceManagerExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/ResourceManagerExample.java @@ -134,7 +134,7 @@ private static class ListAction implements ResourceManagerAction { @Override public void run(ResourceManager resourceManager, String... args) { System.out.println("Projects you can view:"); - for (ProjectInfo project : resourceManager.list().values()) { + for (ProjectInfo project : resourceManager.list().getValues()) { System.out.println(projectDetails(project)); } } @@ -207,8 +207,8 @@ public static void main(String... args) { // If you want to access a local Resource Manager emulator (after creating and starting the // LocalResourceManagerHelper), use the following code instead: - // ResourceManager resourceManager = LocalResourceManagerHelper.options().service(); - ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service(); + // ResourceManager resourceManager = LocalResourceManagerHelper.getOptions().getService(); + ResourceManager resourceManager = ResourceManagerOptions.getDefaultInstance().getService(); args = args.length > 1 ? Arrays.copyOfRange(args, 1, args.length) : new String[] {}; if (args.length < action.getRequiredParams().length) { StringBuilder usage = new StringBuilder(); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/GetOrCreateProject.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/GetOrCreateProject.java index 79278c77affe..bdb2c1fa736a 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/GetOrCreateProject.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/GetOrCreateProject.java @@ -35,7 +35,7 @@ public class GetOrCreateProject { public static void main(String... args) { // Create Resource Manager service object. // By default, credentials are inferred from the runtime environment. - ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service(); + ResourceManager resourceManager = ResourceManagerOptions.getDefaultInstance().getService(); String projectId = "my-globally-unique-project-id"; // Change to a unique project ID. // Get a project from the server. diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/ModifyPolicy.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/ModifyPolicy.java index 00c881a1b7eb..cbf6ee73a83e 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/ModifyPolicy.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/ModifyPolicy.java @@ -37,7 +37,7 @@ public class ModifyPolicy { public static void main(String... args) { // Create Resource Manager service object // By default, credentials are inferred from the runtime environment. - ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service(); + ResourceManager resourceManager = ResourceManagerOptions.getDefaultInstance().getService(); // Get a project from the server String projectId = "some-project-id"; // Use an existing project's ID diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/UpdateAndListProjects.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/UpdateAndListProjects.java index 0a502787316e..eb60ae917ecb 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/UpdateAndListProjects.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/resourcemanager/snippets/UpdateAndListProjects.java @@ -37,7 +37,7 @@ public class UpdateAndListProjects { public static void main(String... args) { // Create Resource Manager service object // By default, credentials are inferred from the runtime environment. - ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service(); + ResourceManager resourceManager = ResourceManagerOptions.getDefaultInstance().getService(); // Get a project from the server Project project = resourceManager.get("some-project-id"); // Use an existing project's ID diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java index 8eb63d541df3..69ccbf51d880 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/StorageExample.java @@ -788,12 +788,12 @@ public static void main(String... args) throws Exception { printUsage(); return; } - StorageOptions.Builder optionsBuilder = StorageOptions.builder(); + StorageOptions.Builder optionsBuilder = StorageOptions.newBuilder(); StorageAction action; String actionName; if (args.length >= 2 && !ACTIONS.containsKey(args[0])) { actionName = args[1]; - optionsBuilder.projectId(args[0]); + optionsBuilder.setProjectId(args[0]); action = ACTIONS.get(args[1]); args = Arrays.copyOfRange(args, 2, args.length); } else { @@ -806,7 +806,7 @@ public static void main(String... args) throws Exception { printUsage(); return; } - Storage storage = optionsBuilder.build().service(); + Storage storage = optionsBuilder.build().getService(); Object arg; try { arg = action.parse(args); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateAndListBucketsAndBlobs.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateAndListBucketsAndBlobs.java index b34cf8b70895..79a4854d9a91 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateAndListBucketsAndBlobs.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateAndListBucketsAndBlobs.java @@ -41,7 +41,7 @@ public class CreateAndListBucketsAndBlobs { public static void main(String... args) { // Create a service object // Credentials are inferred from the environment. - Storage storage = StorageOptions.defaultInstance().service(); + Storage storage = StorageOptions.getDefaultInstance().getService(); // Create a bucket String bucketName = "my_unique_bucket"; // Change this to something unique diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateBlob.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateBlob.java index b63989ce97b3..7d81165ac43d 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateBlob.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/CreateBlob.java @@ -36,7 +36,7 @@ public class CreateBlob { public static void main(String... args) { - Storage storage = StorageOptions.defaultInstance().service(); + Storage storage = StorageOptions.getDefaultInstance().getService(); BlobId blobId = BlobId.of("bucket", "blob_name"); BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build(); Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8)); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/UpdateBlob.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/UpdateBlob.java index ed081928f911..08e200578b57 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/UpdateBlob.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/storage/snippets/UpdateBlob.java @@ -39,7 +39,7 @@ public class UpdateBlob { public static void main(String... args) throws IOException { - Storage storage = StorageOptions.defaultInstance().service(); + Storage storage = StorageOptions.getDefaultInstance().getService(); BlobId blobId = BlobId.of("bucket", "blob_name"); Blob blob = storage.get(blobId); if (blob != null) { diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/TranslateExample.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/TranslateExample.java index f095a0fa89fd..6cb8099fe0f6 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/TranslateExample.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/TranslateExample.java @@ -42,7 +42,7 @@ * translate +"}

    * *

    The first parameter is an optional {@code targetLanguage}. If the target language is not - * supplied, {@code en} is used (see {@link TranslateOptions.Builder#targetLanguage(String)}). + * supplied, {@code en} is used (see {@link TranslateOptions.Builder#setTargetLanguage(String)}). */ public class TranslateExample { @@ -180,16 +180,16 @@ public static void main(String... args) throws Exception { printUsage(); return; } - TranslateOptions.Builder optionsBuilder = TranslateOptions.builder(); + TranslateOptions.Builder optionsBuilder = TranslateOptions.newBuilder(); TranslateAction action; String actionName; if (args.length >= 3 && !ACTIONS.containsKey(args[1])) { - optionsBuilder.apiKey(args[0]); + optionsBuilder.setApiKey(args[0]); actionName = args[2]; - optionsBuilder.targetLanguage(args[1]); + optionsBuilder.setTargetLanguage(args[1]); args = Arrays.copyOfRange(args, 3, args.length); } else if (args.length >= 2 && !ACTIONS.containsKey(args[0])) { - optionsBuilder.apiKey(args[0]); + optionsBuilder.setApiKey(args[0]); actionName = args[1]; args = Arrays.copyOfRange(args, 2, args.length); } else { @@ -214,7 +214,7 @@ public static void main(String... args) throws Exception { ex.printStackTrace(); return; } - Translate translate = optionsBuilder.build().service(); + Translate translate = optionsBuilder.build().getService(); action.run(translate, arg); } } diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java index e66921e60ace..3da44edae015 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/DetectLanguageAndTranslate.java @@ -37,7 +37,7 @@ public class DetectLanguageAndTranslate { public static void main(String... args) { // Create a service object // API key is read from the GOOGLE_API_KEY environment variable - Translate translate = TranslateOptions.defaultInstance().service(); + Translate translate = TranslateOptions.getDefaultInstance().getService(); // Detect the language of some text Detection detection = translate.detect("Hola"); diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/TranslateSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/TranslateSnippets.java index 9305c57bf79a..e122d0610e65 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/TranslateSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/translate/snippets/TranslateSnippets.java @@ -46,7 +46,7 @@ public TranslateSnippets(Translate translate) { /** * Example of listing supported languages, localized according to - * {@link TranslateOptions#targetLanguage()}. + * {@link TranslateOptions#getTargetLanguage()}. */ // [TARGET listSupportedLanguages(LanguageListOption...)] public List listSupportedLanguages() { diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITBigQuerySnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITBigQuerySnippets.java index 124135eabb48..df7811963c6a 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITBigQuerySnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITBigQuerySnippets.java @@ -93,7 +93,7 @@ public DatasetId apply(Dataset dataset) { @BeforeClass public static void beforeClass() { - bigquery = RemoteBigQueryHelper.create().getOptions().service(); + bigquery = RemoteBigQueryHelper.create().getOptions().getService(); bigquerySnippets = new BigQuerySnippets(bigquery); bigquery.create(DatasetInfo.newBuilder(DATASET).build()); } @@ -110,7 +110,7 @@ public void testCreateGetAndDeleteTable() throws InterruptedException { String fieldName = "aField"; Table table = bigquerySnippets.createTable(DATASET, tableName, fieldName); assertNotNull(table); - TableId tableId = TableId.of(bigquery.options().projectId(), DATASET, tableName); + TableId tableId = TableId.of(bigquery.getOptions().getProjectId(), DATASET, tableName); assertEquals(tableId, bigquerySnippets.getTable(tableId.getDataset(), tableId.getTable()).getTableId()); assertNotNull(bigquerySnippets.updateTable(DATASET, tableName, "new friendly name")); @@ -140,7 +140,7 @@ public void testCreateGetAndDeleteTable() throws InterruptedException { @Test public void testCreateGetAndDeleteDataset() throws InterruptedException { - DatasetId datasetId = DatasetId.of(bigquery.options().projectId(), OTHER_DATASET); + DatasetId datasetId = DatasetId.of(bigquery.getOptions().getProjectId(), OTHER_DATASET); Dataset dataset = bigquerySnippets.createDataset(OTHER_DATASET); assertNotNull(dataset); assertEquals(datasetId, bigquerySnippets.getDataset(OTHER_DATASET).getDatasetId()); @@ -180,7 +180,7 @@ public void testWriteAndListTableData() throws IOException, InterruptedException Thread.sleep(500); listPage = bigquerySnippets.listTableData(DATASET, tableName); } - Iterator> rowIterator = listPage.values().iterator(); + Iterator> rowIterator = listPage.getValues().iterator(); assertEquals("StringValue1", rowIterator.next().get(0).getStringValue()); assertEquals("StringValue2", rowIterator.next().get(0).getStringValue()); assertTrue(bigquerySnippets.deleteTable(DATASET, tableName)); @@ -204,7 +204,7 @@ public void testInsertAllAndListTableData() throws IOException, InterruptedExcep Thread.sleep(500); listPage = bigquerySnippets.listTableDataFromId(DATASET, tableName); } - List row = listPage.values().iterator().next(); + List row = listPage.getValues().iterator().next(); assertEquals(true, row.get(0).getBooleanValue()); assertArrayEquals(new byte[]{0xD, 0xE, 0xA, 0xD}, row.get(1).getBytesValue()); assertTrue(bigquerySnippets.deleteTable(DATASET, tableName)); diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITDatasetSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITDatasetSnippets.java index 5ac6ff6430db..661e1e437c84 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITDatasetSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITDatasetSnippets.java @@ -54,7 +54,7 @@ public class ITDatasetSnippets { @BeforeClass public static void beforeClass() { - bigquery = RemoteBigQueryHelper.create().getOptions().service(); + bigquery = RemoteBigQueryHelper.create().getOptions().getService(); dataset = bigquery.create(DatasetInfo.newBuilder(DATASET).build()); nonExistingDataset = bigquery.create(DatasetInfo.newBuilder(NON_EXISTING_DATASET).build()); nonExistingDataset.delete(DatasetDeleteOption.deleteContents()); diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITJobSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITJobSnippets.java index 44ec7c02aef6..bd386f2714c7 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITJobSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITJobSnippets.java @@ -39,7 +39,7 @@ public class ITJobSnippets { @BeforeClass public static void beforeClass() { - bigquery = RemoteBigQueryHelper.create().getOptions().service(); + bigquery = RemoteBigQueryHelper.create().getOptions().getService(); } @Test diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITTableSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITTableSnippets.java index 9294053c4588..eb6e393a8f7a 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITTableSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/bigquery/snippets/ITTableSnippets.java @@ -85,10 +85,10 @@ public class ITTableSnippets { @BeforeClass public static void beforeClass() { - bigquery = RemoteBigQueryHelper.create().getOptions().service(); + bigquery = RemoteBigQueryHelper.create().getOptions().getService(); bigquery.create(DatasetInfo.newBuilder(DATASET_NAME).build()); bigquery.create(DatasetInfo.newBuilder(COPY_DATASET_NAME).build()); - storage = RemoteStorageHelper.create().options().service(); + storage = RemoteStorageHelper.create().getOptions().getService(); storage.create(BucketInfo.of(BUCKET_NAME)); } @@ -169,10 +169,10 @@ public void testInsert() throws InterruptedException { public void testInsertParams() throws InterruptedException { InsertAllResponse response = tableSnippets.insertWithParams("row1", "row2"); assertTrue(response.hasErrors()); - List> rows = ImmutableList.copyOf(tableSnippets.list().values()); + List> rows = ImmutableList.copyOf(tableSnippets.list().getValues()); while (rows.isEmpty()) { Thread.sleep(500); - rows = ImmutableList.copyOf(tableSnippets.list().values()); + rows = ImmutableList.copyOf(tableSnippets.list().getValues()); } Set> values = FluentIterable.from(rows).transform(new Function, List>() { @@ -186,15 +186,15 @@ public List apply(List row) { @Test public void testList() throws InterruptedException { - List> rows = ImmutableList.copyOf(tableSnippets.list().values()); + List> rows = ImmutableList.copyOf(tableSnippets.list().getValues()); assertEquals(0, rows.size()); InsertAllResponse response = tableSnippets.insert("row1", "row2"); assertFalse(response.hasErrors()); - rows = ImmutableList.copyOf(tableSnippets.list().values()); + rows = ImmutableList.copyOf(tableSnippets.list().getValues()); while (rows.isEmpty()) { Thread.sleep(500); - rows = ImmutableList.copyOf(tableSnippets.list().values()); + rows = ImmutableList.copyOf(tableSnippets.list().getValues()); } assertEquals(2, rows.size()); } @@ -261,11 +261,11 @@ private List> waitForTableRows(Table checkTable, int numRows) throws InterruptedException { // Wait for the data to appear. Page> page = checkTable.list(TableDataListOption.pageSize(100)); - List> rows = ImmutableList.copyOf(page.values()); + List> rows = ImmutableList.copyOf(page.getValues()); while (rows.size() != numRows) { Thread.sleep(1000); page = checkTable.list(TableDataListOption.pageSize(100)); - rows = ImmutableList.copyOf(page.values()); + rows = ImmutableList.copyOf(page.getValues()); } return rows; } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITDatastoreSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITDatastoreSnippets.java index c071f89547e7..8d96afd0c0e6 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITDatastoreSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITDatastoreSnippets.java @@ -55,7 +55,7 @@ public class ITDatastoreSnippets { @BeforeClass public static void beforeClass() { - datastore = DatastoreOptions.defaultInstance().service(); + datastore = DatastoreOptions.getDefaultInstance().getService(); datastoreSnippets = new DatastoreSnippets(datastore); } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITQuerySnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITQuerySnippets.java index bb1ee6782e18..ca410b49e711 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITQuerySnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITQuerySnippets.java @@ -54,9 +54,9 @@ public String apply(ProjectionEntity entity) { @BeforeClass public static void beforeClass() { - datastore = DatastoreOptions.defaultInstance().service(); - Key key1 = Key.newBuilder(datastore.options().projectId(), KIND, "key1").build(); - Key key2 = Key.newBuilder(datastore.options().projectId(), KIND, "key2").build(); + datastore = DatastoreOptions.getDefaultInstance().getService(); + Key key1 = Key.newBuilder(datastore.getOptions().getProjectId(), KIND, "key1").build(); + Key key2 = Key.newBuilder(datastore.getOptions().getProjectId(), KIND, "key2").build(); entity1 = Entity.newBuilder(key1).set("description", "entity1").build(); entity2 = Entity.newBuilder(key2).set("description", "entity2").build(); datastore.put(entity1, entity2); diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITTransactionSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITTransactionSnippets.java index 418c50e84dd0..68f29e831608 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITTransactionSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/datastore/snippets/ITTransactionSnippets.java @@ -60,7 +60,7 @@ private String registerKey(String keyName, String kind) { @BeforeClass public static void beforeClass() { - datastore = DatastoreOptions.defaultInstance().service(); + datastore = DatastoreOptions.getDefaultInstance().getService(); } @After diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITLoggingSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITLoggingSnippets.java index 3aeede060f55..c908e8811d2f 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITLoggingSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITLoggingSnippets.java @@ -55,7 +55,7 @@ public class ITLoggingSnippets { @BeforeClass public static void beforeClass() { RemoteLoggingHelper helper = RemoteLoggingHelper.create(); - logging = helper.options().service(); + logging = helper.getOptions().getService(); loggingSnippets = new LoggingSnippets(logging); } @@ -144,7 +144,7 @@ public void testMonitoredResourceDescriptor() throws ExecutionException, Interru @Test public void testWriteAndListLogEntries() throws InterruptedException { String logName = RemoteLoggingHelper.formatForTest("log_name"); - String filter = "logName=projects/" + logging.options().projectId() + "/logs/" + logName; + String filter = "logName=projects/" + logging.getOptions().getProjectId() + "/logs/" + logName; loggingSnippets.write(logName); Iterator iterator = loggingSnippets.listLogEntries(filter).iterateAll(); while (Iterators.size(iterator) < 2) { @@ -157,7 +157,7 @@ public void testWriteAndListLogEntries() throws InterruptedException { @Test public void testWriteAndListLogEntriesAsync() throws ExecutionException, InterruptedException { String logName = RemoteLoggingHelper.formatForTest("log_name"); - String filter = "logName=projects/" + logging.options().projectId() + "/logs/" + logName; + String filter = "logName=projects/" + logging.getOptions().getProjectId() + "/logs/" + logName; loggingSnippets.writeAsync(logName).get(); Iterator iterator = loggingSnippets.listLogEntriesAsync(filter).iterateAll(); while (Iterators.size(iterator) < 2) { diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITMetricSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITMetricSnippets.java index 847642f80996..a1e8a47cc625 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITMetricSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITMetricSnippets.java @@ -45,9 +45,9 @@ public class ITMetricSnippets { @BeforeClass public static void beforeClass() { RemoteLoggingHelper helper = RemoteLoggingHelper.create(); - logging = helper.options().service(); - MetricInfo metricInfo = MetricInfo.builder(METRIC_NAME, METRIC_FILTER) - .description(DESCRIPTION) + logging = helper.getOptions().getService(); + MetricInfo metricInfo = MetricInfo.newBuilder(METRIC_NAME, METRIC_FILTER) + .setDescription(DESCRIPTION) .build(); metricSnippets = new MetricSnippets(logging.create(metricInfo)); } @@ -64,13 +64,13 @@ public void testMetric() throws InterruptedException, ExecutionException { Metric metric = metricSnippets.reload(); assertNotNull(metric); Metric updatedMetric = metricSnippets.update(); - assertEquals(UPDATED_DESCRIPTION, updatedMetric.description()); + assertEquals(UPDATED_DESCRIPTION, updatedMetric.getDescription()); updatedMetric = metricSnippets.reloadAsync(); assertNotNull(updatedMetric); - assertEquals(UPDATED_DESCRIPTION, updatedMetric.description()); + assertEquals(UPDATED_DESCRIPTION, updatedMetric.getDescription()); metric.update(); updatedMetric = metricSnippets.updateAsync(); - assertEquals(UPDATED_DESCRIPTION, updatedMetric.description()); + assertEquals(UPDATED_DESCRIPTION, updatedMetric.getDescription()); assertTrue(metricSnippets.delete()); assertFalse(metricSnippets.deleteAsync()); } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITSinkSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITSinkSnippets.java index c390941fc8ba..4ee12361786e 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITSinkSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/logging/snippets/ITSinkSnippets.java @@ -46,10 +46,11 @@ public class ITSinkSnippets { @BeforeClass public static void beforeClass() { RemoteLoggingHelper helper = RemoteLoggingHelper.create(); - logging = helper.options().service(); - SinkInfo sinkInfo = SinkInfo.builder(SINK_NAME, Destination.DatasetDestination.of(DESTINATION)) - .filter(SINK_FILTER) - .build(); + logging = helper.getOptions().getService(); + SinkInfo sinkInfo = + SinkInfo.newBuilder(SINK_NAME, Destination.DatasetDestination.of(DESTINATION)) + .setFilter(SINK_FILTER) + .build(); sinkSnippets = new SinkSnippets(logging.create(sinkInfo)); } @@ -65,13 +66,13 @@ public void testSink() throws InterruptedException, ExecutionException { Sink sink = sinkSnippets.reload(); assertNotNull(sink); Sink updatedSink = sinkSnippets.update(); - assertEquals(UPDATED_SINK_FILTER, updatedSink.filter()); + assertEquals(UPDATED_SINK_FILTER, updatedSink.getFilter()); updatedSink = sinkSnippets.reloadAsync(); assertNotNull(updatedSink); - assertEquals(UPDATED_SINK_FILTER, updatedSink.filter()); + assertEquals(UPDATED_SINK_FILTER, updatedSink.getFilter()); sink.update(); updatedSink = sinkSnippets.updateAsync(); - assertEquals(UPDATED_SINK_FILTER, updatedSink.filter()); + assertEquals(UPDATED_SINK_FILTER, updatedSink.getFilter()); assertTrue(sinkSnippets.delete()); assertFalse(sinkSnippets.deleteAsync()); } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITPubSubSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITPubSubSnippets.java index 7caf53f936b5..81e17dd5d8ba 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITPubSubSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITPubSubSnippets.java @@ -65,7 +65,7 @@ private static String formatForTest(String resourceName) { @BeforeClass public static void beforeClass() { - pubsub = PubSubOptions.defaultInstance().service(); + pubsub = PubSubOptions.getDefaultInstance().getService(); pubsubSnippets = new PubSubSnippets(pubsub); } @@ -110,25 +110,25 @@ public void testTopicAndSubscription() throws ExecutionException, InterruptedExc while (Iterators.size(page.iterateAll()) < 1) { page = pubsubSnippets.listSubscriptionsForTopic(topicName1); } - assertEquals(subscriptionName1, page.iterateAll().next().subscription()); + assertEquals(subscriptionName1, page.iterateAll().next().getSubscription()); page = pubsubSnippets.listSubscriptionsForTopicAsync(topicName2); while (Iterators.size(page.iterateAll()) < 1) { page = pubsubSnippets.listSubscriptionsForTopicAsync(topicName2); } - assertEquals(subscriptionName2, page.iterateAll().next().subscription()); - String endpoint = "https://" + pubsub.options().projectId() + ".appspot.com/push"; + assertEquals(subscriptionName2, page.iterateAll().next().getSubscription()); + String endpoint = "https://" + pubsub.getOptions().getProjectId() + ".appspot.com/push"; pubsubSnippets.replacePushConfig(subscriptionName1, endpoint); pubsubSnippets.replacePushConfigAsync(subscriptionName2, endpoint); subscription1 = pubsubSnippets.getSubscription(subscriptionName1); subscription2 = pubsubSnippets.getSubscriptionAsync(subscriptionName2); - assertEquals(endpoint, subscription1.pushConfig().endpoint()); - assertEquals(endpoint, subscription2.pushConfig().endpoint()); + assertEquals(endpoint, subscription1.getPushConfig().getEndpoint()); + assertEquals(endpoint, subscription2.getPushConfig().getEndpoint()); pubsubSnippets.replacePushConfigToPull(subscriptionName1); pubsubSnippets.replacePushConfigToPullAsync(subscriptionName2); subscription1 = pubsubSnippets.getSubscription(subscriptionName1); subscription2 = pubsubSnippets.getSubscriptionAsync(subscriptionName2); - assertNull(subscription1.pushConfig()); - assertNull(subscription2.pushConfig()); + assertNull(subscription1.getPushConfig()); + assertNull(subscription2.getPushConfig()); assertTrue(pubsubSnippets.deleteTopic(topicName1)); assertTrue(pubsubSnippets.deleteTopicAsync(topicName2)); assertTrue(pubsubSnippets.deleteSubscription(subscriptionName1)); @@ -151,27 +151,27 @@ public void testPublishAndPullMessage() throws Exception { Iterators.addAll(messages, pubsub.pull(subscriptionName, 100)); } Iterator messageIterator = messages.iterator(); - pubsubSnippets.modifyAckDeadlineOneMessage(subscriptionName, messageIterator.next().ackId()); - pubsubSnippets.modifyAckDeadlineMoreMessages(subscriptionName, messageIterator.next().ackId(), - messageIterator.next().ackId()); - pubsubSnippets.modifyAckDeadlineMessageList(subscriptionName, messageIterator.next().ackId(), - messageIterator.next().ackId()); + pubsubSnippets.modifyAckDeadlineOneMessage(subscriptionName, messageIterator.next().getAckId()); + pubsubSnippets.modifyAckDeadlineMoreMessages(subscriptionName, + messageIterator.next().getAckId(), messageIterator.next().getAckId()); + pubsubSnippets.modifyAckDeadlineMessageList(subscriptionName, messageIterator.next().getAckId(), + messageIterator.next().getAckId()); messageIterator = messages.iterator(); - pubsubSnippets.nackOneMessage(subscriptionName, messageIterator.next().ackId()); - pubsubSnippets.nackMoreMessages(subscriptionName, messageIterator.next().ackId(), - messageIterator.next().ackId()); - pubsubSnippets.nackMessageList(subscriptionName, messageIterator.next().ackId(), - messageIterator.next().ackId()); + pubsubSnippets.nackOneMessage(subscriptionName, messageIterator.next().getAckId()); + pubsubSnippets.nackMoreMessages(subscriptionName, messageIterator.next().getAckId(), + messageIterator.next().getAckId()); + pubsubSnippets.nackMessageList(subscriptionName, messageIterator.next().getAckId(), + messageIterator.next().getAckId()); messages.clear(); while (messages.size() < 5) { Iterators.addAll(messages, pubsub.pull(subscriptionName, 100)); } messageIterator = messages.iterator(); - pubsubSnippets.ackOneMessage(subscriptionName, messageIterator.next().ackId()); - pubsubSnippets.ackMoreMessages(subscriptionName, messageIterator.next().ackId(), - messageIterator.next().ackId()); - pubsubSnippets.ackMessageList(subscriptionName, messageIterator.next().ackId(), - messageIterator.next().ackId()); + pubsubSnippets.ackOneMessage(subscriptionName, messageIterator.next().getAckId()); + pubsubSnippets.ackMoreMessages(subscriptionName, messageIterator.next().getAckId(), + messageIterator.next().getAckId()); + pubsubSnippets.ackMessageList(subscriptionName, messageIterator.next().getAckId(), + messageIterator.next().getAckId()); assertTrue(pubsubSnippets.deleteTopic(topicName)); assertTrue(pubsubSnippets.deleteSubscription(subscriptionName)); } @@ -194,27 +194,27 @@ public void testPublishAndPullMessageAsync() throws Exception { } Iterator messageIterator = messages.iterator(); pubsubSnippets.modifyAckDeadlineOneMessageAsync(subscriptionName, - messageIterator.next().ackId()); + messageIterator.next().getAckId()); pubsubSnippets.modifyAckDeadlineMoreMessagesAsync(subscriptionName, - messageIterator.next().ackId(), messageIterator.next().ackId()); + messageIterator.next().getAckId(), messageIterator.next().getAckId()); pubsubSnippets.modifyAckDeadlineMessageListAsync(subscriptionName, - messageIterator.next().ackId(), messageIterator.next().ackId()); + messageIterator.next().getAckId(), messageIterator.next().getAckId()); messageIterator = messages.iterator(); - pubsubSnippets.nackOneMessageAsync(subscriptionName, messageIterator.next().ackId()); - pubsubSnippets.nackMoreMessagesAsync(subscriptionName, messageIterator.next().ackId(), - messageIterator.next().ackId()); - pubsubSnippets.nackMessageListAsync(subscriptionName, messageIterator.next().ackId(), - messageIterator.next().ackId()); + pubsubSnippets.nackOneMessageAsync(subscriptionName, messageIterator.next().getAckId()); + pubsubSnippets.nackMoreMessagesAsync(subscriptionName, messageIterator.next().getAckId(), + messageIterator.next().getAckId()); + pubsubSnippets.nackMessageListAsync(subscriptionName, messageIterator.next().getAckId(), + messageIterator.next().getAckId()); messages.clear(); while (messages.size() < 5) { Iterators.addAll(messages, pubsub.pull(subscriptionName, 100)); } messageIterator = messages.iterator(); - pubsubSnippets.ackOneMessageAsync(subscriptionName, messageIterator.next().ackId()); - pubsubSnippets.ackMoreMessagesAsync(subscriptionName, messageIterator.next().ackId(), - messageIterator.next().ackId()); - pubsubSnippets.ackMessageListAsync(subscriptionName, messageIterator.next().ackId(), - messageIterator.next().ackId()); + pubsubSnippets.ackOneMessageAsync(subscriptionName, messageIterator.next().getAckId()); + pubsubSnippets.ackMoreMessagesAsync(subscriptionName, messageIterator.next().getAckId(), + messageIterator.next().getAckId()); + pubsubSnippets.ackMessageListAsync(subscriptionName, messageIterator.next().getAckId(), + messageIterator.next().getAckId()); assertTrue(pubsubSnippets.deleteTopicAsync(topicName)); assertTrue(pubsubSnippets.deleteSubscriptionAsync(subscriptionName)); } @@ -226,8 +226,8 @@ public void testTopicSubscriptionPolicy() { Policy policy = pubsubSnippets.getTopicPolicy(topicName); assertNotNull(policy); policy = pubsubSnippets.replaceTopicPolicy(topicName); - assertTrue(policy.bindings().containsKey(Role.viewer())); - assertTrue(policy.bindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); + assertTrue(policy.getBindings().containsKey(Role.viewer())); + assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); List permissions = pubsubSnippets.testTopicPermissions(topicName); assertTrue(permissions.get(0)); String subscriptionName = formatForTest("test-subscription-policy"); @@ -235,8 +235,8 @@ public void testTopicSubscriptionPolicy() { policy = pubsubSnippets.getSubscriptionPolicy(subscriptionName); assertNotNull(policy); policy = pubsubSnippets.replaceSubscriptionPolicy(subscriptionName); - assertTrue(policy.bindings().containsKey(Role.viewer())); - assertTrue(policy.bindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); + assertTrue(policy.getBindings().containsKey(Role.viewer())); + assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); permissions = pubsubSnippets.testSubscriptionPermissions(subscriptionName); assertTrue(permissions.get(0)); topic.delete(); @@ -250,8 +250,8 @@ public void testTopicPolicyAsync() throws ExecutionException, InterruptedExcepti Policy policy = pubsubSnippets.getTopicPolicyAsync(topicName); assertNotNull(policy); policy = pubsubSnippets.replaceTopicPolicyAsync(topicName); - assertTrue(policy.bindings().containsKey(Role.viewer())); - assertTrue(policy.bindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); + assertTrue(policy.getBindings().containsKey(Role.viewer())); + assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); List permissions = pubsubSnippets.testTopicPermissionsAsync(topicName); assertTrue(permissions.get(0)); String subscriptionName = formatForTest("test-subscription-policy-async"); @@ -259,8 +259,8 @@ public void testTopicPolicyAsync() throws ExecutionException, InterruptedExcepti policy = pubsubSnippets.getSubscriptionPolicyAsync(subscriptionName); assertNotNull(policy); policy = pubsubSnippets.replaceSubscriptionPolicyAsync(subscriptionName); - assertTrue(policy.bindings().containsKey(Role.viewer())); - assertTrue(policy.bindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); + assertTrue(policy.getBindings().containsKey(Role.viewer())); + assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); permissions = pubsubSnippets.testSubscriptionPermissionsAsync(subscriptionName); assertTrue(permissions.get(0)); topic.delete(); diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriptionSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriptionSnippets.java index 7e6f89d4074f..ffb912d9f549 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriptionSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriptionSnippets.java @@ -57,7 +57,7 @@ public class ITSubscriptionSnippets { @BeforeClass public static void beforeClass() { - pubsub = PubSubOptions.defaultInstance().service(); + pubsub = PubSubOptions.getDefaultInstance().getService(); topic = pubsub.create(TopicInfo.of(TOPIC)); subscription = pubsub.create(SubscriptionInfo.of(TOPIC, SUBSCRIPTION)); } @@ -74,19 +74,19 @@ public static void afterClass() throws Exception { @Test public void testPushConfig() throws ExecutionException, InterruptedException { SubscriptionSnippets subscriptionSnippets = new SubscriptionSnippets(subscription); - String endpoint = "https://" + pubsub.options().projectId() + ".appspot.com/push"; + String endpoint = "https://" + pubsub.getOptions().getProjectId() + ".appspot.com/push"; subscriptionSnippets.replacePushConfig(endpoint); Subscription updatedSubscription = pubsub.getSubscription(SUBSCRIPTION); - assertEquals(endpoint, updatedSubscription.pushConfig().endpoint()); + assertEquals(endpoint, updatedSubscription.getPushConfig().getEndpoint()); subscriptionSnippets.replacePushConfigToPull(); updatedSubscription = pubsub.getSubscription(SUBSCRIPTION); - assertNull(updatedSubscription.pushConfig()); + assertNull(updatedSubscription.getPushConfig()); subscriptionSnippets.replacePushConfigAsync(endpoint); updatedSubscription = pubsub.getSubscription(SUBSCRIPTION); - assertEquals(endpoint, updatedSubscription.pushConfig().endpoint()); + assertEquals(endpoint, updatedSubscription.getPushConfig().getEndpoint()); subscriptionSnippets.replacePushConfigToPullAsync(); updatedSubscription = pubsub.getSubscription(SUBSCRIPTION); - assertNull(updatedSubscription.pushConfig()); + assertNull(updatedSubscription.getPushConfig()); } @Test @@ -112,13 +112,13 @@ public void testPolicy() throws ExecutionException, InterruptedException { assertNotNull(policy); assertEquals(policy, subscriptionSnippets.getPolicyAsync()); policy = subscriptionSnippets.replacePolicy(); - assertTrue(policy.bindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); + assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); policy = subscription.replacePolicy(policy.toBuilder() .removeIdentity(Role.viewer(), Identity.allAuthenticatedUsers()) .build()); - assertFalse(policy.bindings().containsKey(Role.viewer())); + assertFalse(policy.getBindings().containsKey(Role.viewer())); policy = subscriptionSnippets.replacePolicyAsync(); - assertTrue(policy.bindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); + assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); assertTrue(subscriptionSnippets.delete()); assertFalse(subscriptionSnippets.deleteAsync()); } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITTopicSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITTopicSnippets.java index 4a091c45248c..57c3c70d04aa 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITTopicSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITTopicSnippets.java @@ -51,7 +51,7 @@ public class ITTopicSnippets { @BeforeClass public static void beforeClass() { - pubsub = PubSubOptions.defaultInstance().service(); + pubsub = PubSubOptions.getDefaultInstance().getService(); topic = pubsub.create(TopicInfo.of(TOPIC)); } @@ -84,15 +84,15 @@ public void testTopicSubscriptions() throws ExecutionException, InterruptedExcep pubsub.create(SubscriptionInfo.of(TOPIC, SUBSCRIPTION)); try { Page subscriptions = topicSnippets.listSubscriptionsForTopic(); - while (Iterators.size(subscriptions.values().iterator()) < 1) { + while (Iterators.size(subscriptions.getValues().iterator()) < 1) { subscriptions = topicSnippets.listSubscriptionsForTopic(); } - assertEquals(SUBSCRIPTION, subscriptions.values().iterator().next().subscription()); + assertEquals(SUBSCRIPTION, subscriptions.getValues().iterator().next().getSubscription()); subscriptions = topicSnippets.listSubscriptionsForTopicAsync(); - while (Iterators.size(subscriptions.values().iterator()) < 1) { + while (Iterators.size(subscriptions.getValues().iterator()) < 1) { subscriptions = topicSnippets.listSubscriptionsForTopic(); } - assertEquals(SUBSCRIPTION, subscriptions.values().iterator().next().subscription()); + assertEquals(SUBSCRIPTION, subscriptions.getValues().iterator().next().getSubscription()); } finally { pubsub.deleteSubscription(SUBSCRIPTION); } @@ -105,13 +105,13 @@ public void testPolicy() throws ExecutionException, InterruptedException { assertNotNull(policy); assertEquals(policy, topicSnippets.getPolicyAsync()); policy = topicSnippets.replacePolicy(); - assertTrue(policy.bindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); + assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); policy = topic.replacePolicy(policy.toBuilder() .removeIdentity(Role.viewer(), Identity.allAuthenticatedUsers()) .build()); - assertFalse(policy.bindings().containsKey(Role.viewer())); + assertFalse(policy.getBindings().containsKey(Role.viewer())); policy = topicSnippets.replacePolicyAsync(); - assertTrue(policy.bindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); + assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); assertTrue(topicSnippets.delete()); assertFalse(topicSnippets.deleteAsync()); } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBlobSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBlobSnippets.java index 9e998fb0038f..063899bf50d6 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBlobSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBlobSnippets.java @@ -69,7 +69,7 @@ public class ITBlobSnippets { @BeforeClass public static void beforeClass() { RemoteStorageHelper helper = RemoteStorageHelper.create(); - storage = helper.getOptions().service(); + storage = helper.getOptions().getService(); storage.create(BucketInfo.of(BUCKET)); blob = storage.create(BlobInfo.newBuilder(BUCKET, BLOB).build()); } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBucketSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBucketSnippets.java index 8aa29bab769e..7e49265b930d 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBucketSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITBucketSnippets.java @@ -66,7 +66,7 @@ public class ITBucketSnippets { @BeforeClass public static void beforeClass() { RemoteStorageHelper helper = RemoteStorageHelper.create(); - storage = helper.getOptions().service(); + storage = helper.getOptions().getService(); bucketSnippets = new BucketSnippets(storage.create(BucketInfo.of(BUCKET))); } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITStorageSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITStorageSnippets.java index d454c911b09b..4e05a3eaa5c4 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITStorageSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/storage/snippets/ITStorageSnippets.java @@ -74,7 +74,7 @@ public class ITStorageSnippets { @BeforeClass public static void beforeClass() { RemoteStorageHelper helper = RemoteStorageHelper.create(); - storage = helper.getOptions().service(); + storage = helper.getOptions().getService(); storageSnippets = new StorageSnippets(storage); storageSnippets.createBucket(BUCKET); } diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/translate/snippets/ITTranslateSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/translate/snippets/ITTranslateSnippets.java index 2fe45d2147e9..9a9168475b23 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/translate/snippets/ITTranslateSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/translate/snippets/ITTranslateSnippets.java @@ -47,7 +47,7 @@ public class ITTranslateSnippets { @BeforeClass public static void beforeClass() { RemoteTranslateHelper helper = RemoteTranslateHelper.create(); - translateSnippets = new TranslateSnippets(helper.getOptions().service()); + translateSnippets = new TranslateSnippets(helper.getOptions().getService()); } @Test diff --git a/google-cloud-logging/README.md b/google-cloud-logging/README.md index 30bdb05f87d3..52b7ade043d6 100644 --- a/google-cloud-logging/README.md +++ b/google-cloud-logging/README.md @@ -92,8 +92,8 @@ code to create your service object: import com.google.cloud.logging.Logging; import com.google.cloud.logging.LoggingOptions; -LoggingOptions options = LoggingOptions.defaultInstance(); -try(Logging logging = options.service()) { +LoggingOptions options = LoggingOptions.getDefaultInstance(); +try(Logging logging = options.getService()) { // use logging here } ``` @@ -133,8 +133,8 @@ Then, to write the log entries, use the following code: ```java LogEntry firstEntry = LogEntry.newBuilder(StringPayload.of("message")) .setLogName("test-log") - .setResource(MonitoredResource.builder("global") - .addLabel("project_id", options.projectId()) + .setResource(MonitoredResource.newBuilder("global") + .addLabel("project_id", options.getProjectId()) .build()) .build(); logging.write(Collections.singleton(firstEntry)); diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Logging.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Logging.java index 0db8c916d5f8..c9ea10659fd5 100644 --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Logging.java +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Logging.java @@ -196,7 +196,7 @@ public static EntryListOption filter(String filter) { * Creates a new sink. * *

    Example of creating a sink to export logs to a BigQuery dataset (in the - * {@link LoggingOptions#projectId()} project). + * {@link LoggingOptions#getProjectId()} project). *

     {@code
        * String sinkName = "my_sink_name";
        * String datasetName = "my_dataset";
    @@ -214,7 +214,7 @@ public static EntryListOption filter(String filter) {
        * result. {@link Future#get()} returns the created sink.
        *
        * 

    Example of asynchronously creating a sink to export logs to a BigQuery dataset (in the - * {@link LoggingOptions#projectId()} project). + * {@link LoggingOptions#getProjectId()} project). *

     {@code
        * String sinkName = "my_sink_name";
        * String datasetName = "my_dataset";
    diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingException.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingException.java
    index 947a8741ab1f..54aa9ae2badf 100644
    --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingException.java
    +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingException.java
    @@ -38,7 +38,7 @@ public LoggingException(ApiException apiException, boolean idempotent) {
       }
     
       @Override
    -  protected Set retryableErrors() {
    +  protected Set getRetryableErrors() {
         return null;
       }
     }
    diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java
    index 21eca656b972..2f109f3bd91c 100644
    --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java
    +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingHandler.java
    @@ -140,7 +140,7 @@ public LoggingHandler(String log, LoggingOptions options) {
       public LoggingHandler(String log, LoggingOptions options, MonitoredResource monitoredResource) {
         LogConfigHelper helper = new LogConfigHelper();
         String className = getClass().getName();
    -    this.options = options != null ? options : LoggingOptions.defaultInstance();
    +    this.options = options != null ? options : LoggingOptions.getDefaultInstance();
         this.flushLevel = helper.getLevelProperty(className + ".flushLevel", LoggingLevel.ERROR);
         this.flushSize = helper.getLongProperty(className + ".flushSize", 1L);
         setLevel(helper.getLevelProperty(className + ".level", Level.INFO));
    @@ -208,7 +208,7 @@ private static boolean hasLoggingHandler(Logger logger) {
       }
     
       private MonitoredResource getDefaultResource() {
    -    return MonitoredResource.of("global", ImmutableMap.of("project_id", options.projectId()));
    +    return MonitoredResource.of("global", ImmutableMap.of("project_id", options.getProjectId()));
       }
     
       private static class LogConfigHelper {
    @@ -273,7 +273,7 @@ Formatter getFormatterProperty(String name, Formatter defaultValue) {
        */
       Logging getLogging() {
         if (logging == null) {
    -      logging = options.service();
    +      logging = options.getService();
         }
         return logging;
       }
    diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingImpl.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingImpl.java
    index 33736bf0c1d5..f34a4909b645 100644
    --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingImpl.java
    +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingImpl.java
    @@ -93,7 +93,7 @@ public Void apply(WriteLogEntriesResponse input) {
     
       LoggingImpl(LoggingOptions options) {
         super(options);
    -    rpc = options.rpc();
    +    rpc = options.getRpc();
       }
     
       private static  V get(Future future) {
    @@ -145,7 +145,13 @@ private static class SinkPageFetcher extends BasePageFetcher {
         }
     
         @Override
    +    @Deprecated
         public Future> nextPage() {
    +      return getNextPage();
    +    }
    +
    +    @Override
    +    public Future> getNextPage() {
           return listSinksAsync(serviceOptions(), requestOptions());
         }
       }
    @@ -161,7 +167,13 @@ private static class MonitoredResourceDescriptorPageFetcher
         }
     
         @Override
    +    @Deprecated
         public Future> nextPage() {
    +      return getNextPage();
    +    }
    +
    +    @Override
    +    public Future> getNextPage() {
           return listMonitoredResourceDescriptorsAsync(serviceOptions(), requestOptions());
         }
       }
    @@ -176,7 +188,13 @@ private static class MetricPageFetcher extends BasePageFetcher {
         }
     
         @Override
    +    @Deprecated
         public Future> nextPage() {
    +      return getNextPage();
    +    }
    +
    +    @Override
    +    public Future> getNextPage() {
           return listMetricsAsync(serviceOptions(), requestOptions());
         }
       }
    @@ -191,7 +209,13 @@ private static class LogEntryPageFetcher extends BasePageFetcher {
         }
     
         @Override
    +    @Deprecated
         public Future> nextPage() {
    +      return getNextPage();
    +    }
    +
    +    @Override
    +    public Future> getNextPage() {
           return listLogEntriesAsync(serviceOptions(), requestOptions());
         }
       }
    @@ -204,8 +228,8 @@ public Sink create(SinkInfo sink) {
       @Override
       public Future createAsync(SinkInfo sink) {
         CreateSinkRequest request = CreateSinkRequest.newBuilder()
    -        .setParent(ConfigServiceV2Api.formatParentName(options().projectId()))
    -        .setSink(sink.toPb(options().projectId()))
    +        .setParent(ConfigServiceV2Api.formatParentName(getOptions().getProjectId()))
    +        .setSink(sink.toPb(getOptions().getProjectId()))
             .build();
         return transform(rpc.create(request), Sink.fromPbFunction(this));
       }
    @@ -218,8 +242,8 @@ public Sink update(SinkInfo sink) {
       @Override
       public Future updateAsync(SinkInfo sink) {
         UpdateSinkRequest request = UpdateSinkRequest.newBuilder()
    -        .setSinkName(ConfigServiceV2Api.formatSinkName(options().projectId(), sink.getName()))
    -        .setSink(sink.toPb(options().projectId()))
    +        .setSinkName(ConfigServiceV2Api.formatSinkName(getOptions().getProjectId(), sink.getName()))
    +        .setSink(sink.toPb(getOptions().getProjectId()))
             .build();
         return transform(rpc.update(request), Sink.fromPbFunction(this));
       }
    @@ -232,7 +256,7 @@ public Sink getSink(String sink) {
       @Override
       public Future getSinkAsync(String sink) {
         GetSinkRequest request = GetSinkRequest.newBuilder()
    -        .setSinkName(ConfigServiceV2Api.formatSinkName(options().projectId(), sink))
    +        .setSinkName(ConfigServiceV2Api.formatSinkName(getOptions().getProjectId(), sink))
             .build();
         return transform(rpc.get(request), Sink.fromPbFunction(this));
       }
    @@ -240,7 +264,7 @@ public Future getSinkAsync(String sink) {
       private static ListSinksRequest listSinksRequest(LoggingOptions serviceOptions,
           Map options) {
         ListSinksRequest.Builder builder = ListSinksRequest.newBuilder();
    -    builder.setParent(ConfigServiceV2Api.formatParentName(serviceOptions.projectId()));
    +    builder.setParent(ConfigServiceV2Api.formatParentName(serviceOptions.getProjectId()));
         Integer pageSize = PAGE_SIZE.get(options);
         String pageToken = PAGE_TOKEN.get(options);
         if (pageSize != null) {
    @@ -255,13 +279,13 @@ private static ListSinksRequest listSinksRequest(LoggingOptions serviceOptions,
       private static Future> listSinksAsync(final LoggingOptions serviceOptions,
           final Map options) {
         final ListSinksRequest request = listSinksRequest(serviceOptions, options);
    -    Future list = serviceOptions.rpc().list(request);
    +    Future list = serviceOptions.getRpc().list(request);
         return transform(list, new Function>() {
           @Override
           public AsyncPage apply(ListSinksResponse listSinksResponse) {
             List sinks = listSinksResponse.getSinksList() == null ? ImmutableList.of()
                 : Lists.transform(listSinksResponse.getSinksList(),
    -            Sink.fromPbFunction(serviceOptions.service()));
    +            Sink.fromPbFunction(serviceOptions.getService()));
             String cursor = listSinksResponse.getNextPageToken().equals("") ? null
                 : listSinksResponse.getNextPageToken();
             return new AsyncPageImpl<>(
    @@ -277,7 +301,7 @@ public Page listSinks(ListOption... options) {
     
       @Override
       public Future> listSinksAsync(ListOption... options) {
    -    return listSinksAsync(options(), optionMap(options));
    +    return listSinksAsync(getOptions(), optionMap(options));
       }
     
       @Override
    @@ -288,7 +312,7 @@ public boolean deleteSink(String sink) {
       @Override
       public Future deleteSinkAsync(String sink) {
         DeleteSinkRequest request = DeleteSinkRequest.newBuilder()
    -        .setSinkName(ConfigServiceV2Api.formatSinkName(options().projectId(), sink))
    +        .setSinkName(ConfigServiceV2Api.formatSinkName(getOptions().getProjectId(), sink))
             .build();
         return transform(rpc.delete(request), EMPTY_TO_BOOLEAN_FUNCTION);
       }
    @@ -299,7 +323,7 @@ public boolean deleteLog(String log) {
     
       public Future deleteLogAsync(String log) {
         DeleteLogRequest request = DeleteLogRequest.newBuilder()
    -        .setLogName(LoggingServiceV2Api.formatLogName(options().projectId(), log))
    +        .setLogName(LoggingServiceV2Api.formatLogName(getOptions().getProjectId(), log))
             .build();
         return transform(rpc.delete(request), EMPTY_TO_BOOLEAN_FUNCTION);
       }
    @@ -324,7 +348,7 @@ private static ListMonitoredResourceDescriptorsRequest listMonitoredResourceDesc
               final Map options) {
         final ListMonitoredResourceDescriptorsRequest request =
             listMonitoredResourceDescriptorsRequest(options);
    -    Future list = serviceOptions.rpc().list(request);
    +    Future list = serviceOptions.getRpc().list(request);
         return transform(list, new Function>() {
               @Override
    @@ -350,7 +374,7 @@ public Page listMonitoredResourceDescriptors(ListOp
     
       public Future> listMonitoredResourceDescriptorsAsync(
           ListOption... options) {
    -    return listMonitoredResourceDescriptorsAsync(options(), optionMap(options));
    +    return listMonitoredResourceDescriptorsAsync(getOptions(), optionMap(options));
       }
     
       @Override
    @@ -361,7 +385,7 @@ public Metric create(MetricInfo metric) {
       @Override
       public Future createAsync(MetricInfo metric) {
         CreateLogMetricRequest request = CreateLogMetricRequest.newBuilder()
    -        .setParent(MetricsServiceV2Api.formatParentName(options().projectId()))
    +        .setParent(MetricsServiceV2Api.formatParentName(getOptions().getProjectId()))
             .setMetric(metric.toPb())
             .build();
         return transform(rpc.create(request), Metric.fromPbFunction(this));
    @@ -375,7 +399,7 @@ public Metric update(MetricInfo metric) {
       @Override
       public Future updateAsync(MetricInfo metric) {
         UpdateLogMetricRequest request = UpdateLogMetricRequest.newBuilder()
    -        .setMetricName(MetricsServiceV2Api.formatMetricName(options().projectId(),
    +        .setMetricName(MetricsServiceV2Api.formatMetricName(getOptions().getProjectId(),
                 metric.getName()))
             .setMetric(metric.toPb())
             .build();
    @@ -390,7 +414,7 @@ public Metric getMetric(String metric) {
       @Override
       public Future getMetricAsync(String metric) {
         GetLogMetricRequest request = GetLogMetricRequest.newBuilder()
    -        .setMetricName(MetricsServiceV2Api.formatMetricName(options().projectId(), metric))
    +        .setMetricName(MetricsServiceV2Api.formatMetricName(getOptions().getProjectId(), metric))
             .build();
         return transform(rpc.get(request), Metric.fromPbFunction(this));
       }
    @@ -398,7 +422,7 @@ public Future getMetricAsync(String metric) {
       private static ListLogMetricsRequest listMetricsRequest(LoggingOptions serviceOptions,
           Map options) {
         ListLogMetricsRequest.Builder builder = ListLogMetricsRequest.newBuilder();
    -    builder.setParent(MetricsServiceV2Api.formatParentName(serviceOptions.projectId()));
    +    builder.setParent(MetricsServiceV2Api.formatParentName(serviceOptions.getProjectId()));
         Integer pageSize = PAGE_SIZE.get(options);
         String pageToken = PAGE_TOKEN.get(options);
         if (pageSize != null) {
    @@ -413,13 +437,13 @@ private static ListLogMetricsRequest listMetricsRequest(LoggingOptions serviceOp
       private static Future> listMetricsAsync(final LoggingOptions serviceOptions,
           final Map options) {
         final ListLogMetricsRequest request = listMetricsRequest(serviceOptions, options);
    -    Future list = serviceOptions.rpc().list(request);
    +    Future list = serviceOptions.getRpc().list(request);
         return transform(list, new Function>() {
           @Override
           public AsyncPage apply(ListLogMetricsResponse listMetricsResponse) {
             List metrics = listMetricsResponse.getMetricsList() == null
                 ? ImmutableList.of() : Lists.transform(listMetricsResponse.getMetricsList(),
    -                Metric.fromPbFunction(serviceOptions.service()));
    +                Metric.fromPbFunction(serviceOptions.getService()));
             String cursor = listMetricsResponse.getNextPageToken().equals("") ? null
                 : listMetricsResponse.getNextPageToken();
             return new AsyncPageImpl<>(new MetricPageFetcher(serviceOptions, cursor, options), cursor,
    @@ -435,7 +459,7 @@ public Page listMetrics(ListOption... options) {
     
       @Override
       public Future> listMetricsAsync(ListOption... options) {
    -    return listMetricsAsync(options(), optionMap(options));
    +    return listMetricsAsync(getOptions(), optionMap(options));
       }
     
       @Override
    @@ -446,14 +470,14 @@ public boolean deleteMetric(String metric) {
       @Override
       public Future deleteMetricAsync(String metric) {
         DeleteLogMetricRequest request = DeleteLogMetricRequest.newBuilder()
    -        .setMetricName(MetricsServiceV2Api.formatMetricName(options().projectId(), metric))
    +        .setMetricName(MetricsServiceV2Api.formatMetricName(getOptions().getProjectId(), metric))
             .build();
         return transform(rpc.delete(request), EMPTY_TO_BOOLEAN_FUNCTION);
       }
     
       private static WriteLogEntriesRequest writeLogEntriesRequest(LoggingOptions serviceOptions,
           Iterable logEntries, Map options) {
    -    String projectId = serviceOptions.projectId();
    +    String projectId = serviceOptions.getProjectId();
         WriteLogEntriesRequest.Builder builder = WriteLogEntriesRequest.newBuilder();
         String logName = LOG_NAME.get(options);
         if (logName != null) {
    @@ -476,14 +500,15 @@ public void write(Iterable logEntries, WriteOption... options) {
       }
     
       public Future writeAsync(Iterable logEntries, WriteOption... options) {
    -    return transform(rpc.write(writeLogEntriesRequest(options(), logEntries, optionMap(options))),
    +    return transform(
    +        rpc.write(writeLogEntriesRequest(getOptions(), logEntries, optionMap(options))),
             WRITE_RESPONSE_TO_VOID_FUNCTION);
       }
     
       private static ListLogEntriesRequest listLogEntriesRequest(LoggingOptions serviceOptions,
           Map options) {
         ListLogEntriesRequest.Builder builder = ListLogEntriesRequest.newBuilder();
    -    builder.addProjectIds(serviceOptions.projectId());
    +    builder.addProjectIds(serviceOptions.getProjectId());
         Integer pageSize = PAGE_SIZE.get(options);
         if (pageSize != null) {
           builder.setPageSize(pageSize);
    @@ -506,7 +531,7 @@ private static ListLogEntriesRequest listLogEntriesRequest(LoggingOptions servic
       private static Future> listLogEntriesAsync(
           final LoggingOptions serviceOptions, final Map options) {
         final ListLogEntriesRequest request = listLogEntriesRequest(serviceOptions, options);
    -    Future list = serviceOptions.rpc().list(request);
    +    Future list = serviceOptions.getRpc().list(request);
         return transform(list, new Function>() {
           @Override
           public AsyncPage apply(ListLogEntriesResponse listLogEntrysResponse) {
    @@ -528,7 +553,7 @@ public Page listLogEntries(EntryListOption... options) {
     
       @Override
       public Future> listLogEntriesAsync(EntryListOption... options) {
    -    return listLogEntriesAsync(options(), optionMap(options));
    +    return listLogEntriesAsync(getOptions(), optionMap(options));
       }
     
       @Override
    diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingOptions.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingOptions.java
    index 9f8b594a1084..230482e73c27 100644
    --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingOptions.java
    +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/LoggingOptions.java
    @@ -47,8 +47,16 @@ public Logging create(LoggingOptions options) {
       /**
        * Returns a default {@code LoggingOptions} instance.
        */
    +  @Deprecated
       public static LoggingOptions defaultInstance() {
    -    return builder().build();
    +    return getDefaultInstance();
    +  }
    +
    +  /**
    +   * Returns a default {@code LoggingOptions} instance.
    +   */
    +  public static LoggingOptions getDefaultInstance() {
    +    return newBuilder().build();
       }
     
       public static class DefaultLoggingRpcFactory implements LoggingRpcFactory {
    @@ -65,7 +73,7 @@ public LoggingRpc create(LoggingOptions options) {
       }
     
       @Override
    -  protected String defaultHost() {
    +  protected String getDefaultHost() {
         return DEFAULT_HOST;
       }
     
    @@ -89,22 +97,22 @@ protected LoggingOptions(Builder builder) {
       }
     
       @Override
    -  protected ExecutorFactory executorFactory() {
    -    return super.executorFactory();
    +  protected ExecutorFactory getExecutorFactory() {
    +    return super.getExecutorFactory();
       }
     
       @Override
    -  protected LoggingFactory defaultServiceFactory() {
    +  protected LoggingFactory getDefaultServiceFactory() {
         return DefaultLoggingFactory.INSTANCE;
       }
     
       @Override
    -  protected LoggingRpcFactory defaultRpcFactory() {
    +  protected LoggingRpcFactory getDefaultRpcFactory() {
         return DefaultLoggingRpcFactory.INSTANCE;
       }
     
       @Override
    -  protected Set scopes() {
    +  protected Set getScopes() {
         return SCOPES;
       }
     
    @@ -124,7 +132,12 @@ public Builder toBuilder() {
         return new Builder(this);
       }
     
    +  @Deprecated
       public static Builder builder() {
    +    return newBuilder();
    +  }
    +
    +  public static Builder newBuilder() {
         return new Builder();
       }
     }
    diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Metric.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Metric.java
    index 3be29ef1cd0d..06a87b6a80e8 100644
    --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Metric.java
    +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Metric.java
    @@ -102,7 +102,7 @@ public Metric build() {
       Metric(Logging logging, BuilderImpl builder) {
         super(builder);
         this.logging = checkNotNull(logging);
    -    options = logging.options();
    +    options = logging.getOptions();
       }
     
       @Override
    @@ -265,7 +265,7 @@ public Future updateAsync() {
     
       private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
         input.defaultReadObject();
    -    this.logging = options.service();
    +    this.logging = options.getService();
       }
     
       static Metric fromPb(Logging logging, LogMetric metricPb) {
    diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/Sink.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/Sink.java
    index 5ebac1896896..ff3d75dac01f 100644
    --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/Sink.java
    +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/Sink.java
    @@ -120,7 +120,7 @@ public Sink build() {
       Sink(Logging logging, BuilderImpl builder) {
         super(builder);
         this.logging = checkNotNull(logging);
    -    options = logging.options();
    +    options = logging.getOptions();
       }
     
       @Override
    @@ -283,7 +283,7 @@ public Future updateAsync() {
     
       private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException {
         input.defaultReadObject();
    -    this.logging = options.service();
    +    this.logging = options.getService();
       }
     
       static Sink fromPb(Logging logging, LogSink sinkPb) {
    diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/package-info.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/package-info.java
    index ab456dc1c615..de8facad6293 100644
    --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/package-info.java
    +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/package-info.java
    @@ -22,19 +22,19 @@
      * 
      * WriteAndListLogEntries.java.
      * 
     {@code
    - * LoggingOptions options = LoggingOptions.defaultInstance();
    - * try(Logging logging = options.service()) {
    + * LoggingOptions options = LoggingOptions.getDefaultInstance();
    + * try(Logging logging = options.getService()) {
      *
      *   LogEntry firstEntry = LogEntry.newBuilder(StringPayload.of("message"))
      *       .setLogName("test-log")
      *       .setResource(MonitoredResource.builder("global")
    - *           .addLabel("project_id", options.projectId())
    + *           .addLabel("project_id", options.getProjectId())
      *           .build())
      *       .build();
      *   logging.write(Collections.singleton(firstEntry));
      *
      *   Page entries = logging.listLogEntries(
    - *   EntryListOption.filter("logName=projects/" + options.projectId() + "/logs/test-log"));
    + *   EntryListOption.filter("logName=projects/" + options.getProjectId() + "/logs/test-log"));
      *   Iterator entryIterator = entries.iterateAll();
      *   while (entryIterator.hasNext()) {
      *     System.out.println(entryIterator.next());
    diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/DefaultLoggingRpc.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/DefaultLoggingRpc.java
    index 20bb13cf7273..e47aeb56766a 100644
    --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/DefaultLoggingRpc.java
    +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/DefaultLoggingRpc.java
    @@ -87,27 +87,27 @@ private InternalLoggingOptions(LoggingOptions options) {
         }
     
         @Override
    -    protected ExecutorFactory executorFactory() {
    -      return super.executorFactory();
    +    protected ExecutorFactory getExecutorFactory() {
    +      return super.getExecutorFactory();
         }
     
         @Override
    -    protected UnaryCallSettings.Builder apiCallSettings() {
    -      return super.apiCallSettings();
    +    protected UnaryCallSettings.Builder getApiCallSettings() {
    +      return super.getApiCallSettings();
         }
     
         @Override
    -    protected ConnectionSettings.Builder connectionSettings() {
    -      return super.connectionSettings();
    +    protected ConnectionSettings.Builder getConnectionSettings() {
    +      return super.getConnectionSettings();
         }
       }
     
       public DefaultLoggingRpc(LoggingOptions options) throws IOException {
         InternalLoggingOptions internalOptions = new InternalLoggingOptions(options);
    -    executorFactory = internalOptions.executorFactory();
    +    executorFactory = internalOptions.getExecutorFactory();
         executor = executorFactory.get();
    -    String libraryName = options.libraryName();
    -    String libraryVersion = firstNonNull(options.libraryVersion(), "");
    +    String libraryName = options.getLibraryName();
    +    String libraryVersion = firstNonNull(options.getLibraryVersion(), "");
         try {
           ConfigServiceV2Settings.Builder confBuilder = ConfigServiceV2Settings.defaultBuilder()
               .provideExecutorWith(executor, false)
    @@ -119,21 +119,21 @@ public DefaultLoggingRpc(LoggingOptions options) throws IOException {
               .provideExecutorWith(executor, false)
               .setClientLibHeader(libraryName, libraryVersion);
           // todo(mziccard): PublisherSettings should support null/absent credentials for testing
    -      if (options.host().contains("localhost")
    -          || options.authCredentials().equals(AuthCredentials.noAuth())) {
    -        ManagedChannel channel = NettyChannelBuilder.forTarget(options.host())
    +      if (options.getHost().contains("localhost")
    +          || options.getAuthCredentials().equals(AuthCredentials.noAuth())) {
    +        ManagedChannel channel = NettyChannelBuilder.forTarget(options.getHost())
                 .negotiationType(NegotiationType.PLAINTEXT)
                 .build();
             confBuilder.provideChannelWith(channel, true);
             logBuilder.provideChannelWith(channel, true);
             metricsBuilder.provideChannelWith(channel, true);
           } else {
    -        ConnectionSettings connectionSettings = internalOptions.connectionSettings().build();
    +        ConnectionSettings connectionSettings = internalOptions.getConnectionSettings().build();
             confBuilder.provideChannelWith(connectionSettings);
             logBuilder.provideChannelWith(connectionSettings);
             metricsBuilder.provideChannelWith(connectionSettings);
           }
    -      UnaryCallSettings.Builder callSettingsBuilder = internalOptions.apiCallSettings();
    +      UnaryCallSettings.Builder callSettingsBuilder = internalOptions.getApiCallSettings();
           confBuilder.applyToAllApiMethods(callSettingsBuilder);
           logBuilder.applyToAllApiMethods(callSettingsBuilder);
           metricsBuilder.applyToAllApiMethods(callSettingsBuilder);
    diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java
    index 65bb9bfaa0d7..d1935618a5c3 100644
    --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java
    +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/RemoteLoggingHelper.java
    @@ -29,11 +29,12 @@
     /**
      * Utility to create a remote logging configuration for testing. Logging options can be obtained via
      * the {@link #getOptions()} method. Returned options have custom
    - * {@link LoggingOptions#retryParams()}: {@link RetryParams#maxRetryDelayMillis()} is {@code 30000},
    - * {@link RetryParams#totalRetryPeriodMillis()} is {@code 120000} and
    - * {@link RetryParams#initialRetryDelayMillis()} is {@code 250}.
    - * {@link LoggingOptions#initialTimeout()} is set to 60000, {@link LoggingOptions#maxTimeout()} is
    - * set to {@code 240000} and {@link LoggingOptions#timeoutMultiplier()} is set to {@code 1.5}.
    + * {@link LoggingOptions#getRetryParams()}: {@link RetryParams#getMaxRetryDelayMillis()} is
    + * {@code 30000}, {@link RetryParams#getTotalRetryPeriodMillis()} is {@code 120000} and
    + * {@link RetryParams#getInitialRetryDelayMillis()} is {@code 250}.
    + * {@link LoggingOptions#getInitialTimeout()} is set to 60000,
    + * {@link LoggingOptions#getMaxTimeout()} is set to {@code 240000} and
    + * {@link LoggingOptions#getTimeoutMultiplier()} is set to {@code 1.5}.
      */
     public class RemoteLoggingHelper {
     
    @@ -72,13 +73,13 @@ public LoggingOptions getOptions() {
       public static RemoteLoggingHelper create(String projectId, InputStream keyStream)
           throws LoggingHelperException {
         try {
    -      LoggingOptions storageOptions = LoggingOptions.builder()
    -          .authCredentials(AuthCredentials.createForJson(keyStream))
    -          .projectId(projectId)
    -          .retryParams(retryParams())
    -          .initialTimeout(60000)
    -          .maxTimeout(120000)
    -          .timeoutMultiplier(1.5)
    +      LoggingOptions storageOptions = LoggingOptions.newBuilder()
    +          .setAuthCredentials(AuthCredentials.createForJson(keyStream))
    +          .setProjectId(projectId)
    +          .setRetryParams(retryParams())
    +          .setInitialTimeout(60000)
    +          .setMaxTimeout(120000)
    +          .setTimeoutMultiplier(1.5)
               .build();
           return new RemoteLoggingHelper(storageOptions);
         } catch (IOException ex) {
    @@ -94,11 +95,11 @@ public static RemoteLoggingHelper create(String projectId, InputStream keyStream
        * credentials.
        */
       public static RemoteLoggingHelper create() throws LoggingHelperException {
    -    LoggingOptions loggingOptions = LoggingOptions.builder()
    -        .retryParams(retryParams())
    -        .initialTimeout(60000)
    -        .maxTimeout(240000)
    -        .timeoutMultiplier(1.5)
    +    LoggingOptions loggingOptions = LoggingOptions.newBuilder()
    +        .setRetryParams(retryParams())
    +        .setInitialTimeout(60000)
    +        .setMaxTimeout(240000)
    +        .setTimeoutMultiplier(1.5)
             .build();
         return new RemoteLoggingHelper(loggingOptions);
       }
    @@ -112,10 +113,10 @@ public static String formatForTest(String name) {
       }
     
       private static RetryParams retryParams() {
    -    return RetryParams.builder()
    -        .maxRetryDelayMillis(30000)
    -        .totalRetryPeriodMillis(120000)
    -        .initialRetryDelayMillis(250)
    +    return RetryParams.newBuilder()
    +        .setMaxRetryDelayMillis(30000)
    +        .setTotalRetryPeriodMillis(120000)
    +        .setInitialRetryDelayMillis(250)
             .build();
       }
     
    diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/package-info.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/package-info.java
    index 3c765aab6095..785c698fb2c7 100644
    --- a/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/package-info.java
    +++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/testing/package-info.java
    @@ -22,7 +22,7 @@
      * 

    Before the test: *

     {@code
      * RemoteLoggingHelper helper = RemoteLoggingHelper.create();
    - * Logging logging = helper.getOptions().service();
    + * Logging logging = helper.getOptions().getService();
      * } 
    * *

    Format resource names to avoid name clashes: diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/AsyncLoggingHandlerTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/AsyncLoggingHandlerTest.java index e555a6b3cbe3..495430c23d75 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/AsyncLoggingHandlerTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/AsyncLoggingHandlerTest.java @@ -59,8 +59,8 @@ public void afterClass() { @Test public void testPublish() { - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(options.service()).andReturn(logging); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(options.getService()).andReturn(logging); LogEntry entry = LogEntry.newBuilder(Payload.StringPayload.of(MESSAGE)) .setSeverity(Severity.DEBUG) .addLabel("levelName", "FINEST") diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java index c27e02183042..3ff4e2d93457 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/BaseSystemTest.java @@ -90,7 +90,7 @@ public void testCreateGetUpdateAndDeleteSink() { assertEquals(SinkInfo.VersionFormat.V2, sink.getVersionFormat()); assertEquals("severity>=ERROR", sink.getFilter()); DatasetDestination datasetDestination = sink.getDestination(); - assertEquals(logging().options().projectId(), datasetDestination.getProject()); + assertEquals(logging().getOptions().getProjectId(), datasetDestination.getProject()); assertEquals("dataset", datasetDestination.getDataset()); assertEquals(sink, logging().getSink(name)); sink = sink.toBuilder() @@ -117,7 +117,7 @@ public void testCreateGetUpdateAndDeleteSinkAsync() assertEquals(SinkInfo.VersionFormat.V2, sink.getVersionFormat()); assertEquals("severity>=ERROR", sink.getFilter()); DatasetDestination datasetDestination = sink.getDestination(); - assertEquals(logging().options().projectId(), datasetDestination.getProject()); + assertEquals(logging().getOptions().getProjectId(), datasetDestination.getProject()); assertEquals("dataset", datasetDestination.getDataset()); assertEquals(sink, logging().getSinkAsync(name).get()); sink = sink.toBuilder() @@ -144,7 +144,7 @@ public void testUpdateNonExistingSink() { assertEquals(SinkInfo.VersionFormat.V2, sink.getVersionFormat()); assertEquals("severity>=ERROR", sink.getFilter()); DatasetDestination datasetDestination = sink.getDestination(); - assertEquals(logging().options().projectId(), datasetDestination.getProject()); + assertEquals(logging().getOptions().getProjectId(), datasetDestination.getProject()); assertEquals("dataset", datasetDestination.getDataset()); assertTrue(logging().deleteSink(name)); } @@ -162,7 +162,7 @@ public void testUpdateNonExistingSinkAsync() throws ExecutionException, Interrup assertEquals(SinkInfo.VersionFormat.V2, sink.getVersionFormat()); assertEquals("severity>=ERROR", sink.getFilter()); DatasetDestination datasetDestination = sink.getDestination(); - assertEquals(logging().options().projectId(), datasetDestination.getProject()); + assertEquals(logging().getOptions().getProjectId(), datasetDestination.getProject()); assertEquals("dataset", datasetDestination.getDataset()); assertTrue(logging().deleteSinkAsync(name).get()); } @@ -338,7 +338,8 @@ public void testListMetricsAsync() throws ExecutionException, InterruptedExcepti @Test public void testWriteAndListLogEntries() throws InterruptedException { String logName = formatForTest("test-write-log-entries-log"); - String filter = "logName = projects/" + logging().options().projectId() + "/logs/" + logName; + String filter = + "logName = projects/" + logging().getOptions().getProjectId() + "/logs/" + logName; StringPayload firstPayload = StringPayload.of("stringPayload"); LogEntry firstEntry = LogEntry.newBuilder(firstPayload) .addLabel("key1", "value1") @@ -403,7 +404,8 @@ public void testWriteAndListLogEntries() throws InterruptedException { @Test public void testWriteAndListLogEntriesAsync() throws InterruptedException, ExecutionException { String logName = formatForTest("test-write-log-entries-async-log"); - String filter = "logName = projects/" + logging().options().projectId() + "/logs/" + logName; + String filter = + "logName = projects/" + logging().getOptions().getProjectId() + "/logs/" + logName; StringPayload firstPayload = StringPayload.of("stringPayload"); LogEntry firstEntry = LogEntry.newBuilder(firstPayload).setSeverity(Severity.ALERT).build(); ProtoPayload secondPayload = @@ -460,7 +462,7 @@ public void testDeleteNonExistingLogAsync() throws ExecutionException, Interrupt @Test public void testLoggingHandler() throws InterruptedException { String logName = formatForTest("test-logging-handler"); - LoggingOptions options = logging().options(); + LoggingOptions options = logging().getOptions(); LoggingHandler handler = new LoggingHandler(logName, options); handler.setLevel(Level.INFO); Logger logger = Logger.getLogger(getClass().getName()); @@ -482,7 +484,7 @@ public void testLoggingHandler() throws InterruptedException { assertEquals(ImmutableMap.of("levelName", "INFO", "levelValue", String.valueOf(Level.INFO.intValue())), entry.getLabels()); assertEquals("global", entry.getResource().getType()); - assertEquals(ImmutableMap.of("project_id", options.projectId()), + assertEquals(ImmutableMap.of("project_id", options.getProjectId()), entry.getResource().getLabels()); assertNull(entry.getHttpRequest()); assertEquals(Severity.INFO, entry.getSeverity()); @@ -497,9 +499,9 @@ public void testLoggingHandler() throws InterruptedException { @Test public void testAsyncLoggingHandler() throws InterruptedException { String logName = formatForTest("test-async-logging-handler"); - LoggingOptions options = logging().options(); + LoggingOptions options = logging().getOptions(); MonitoredResource resource = MonitoredResource.of("gce_instance", - ImmutableMap.of("project_id", options.projectId(), + ImmutableMap.of("project_id", options.getProjectId(), "instance_id", "instance", "zone", "us-central1-a")); LoggingHandler handler = new AsyncLoggingHandler(logName, options, resource); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingHandlerTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingHandlerTest.java index 50282b59f760..e75c981376f9 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingHandlerTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingHandlerTest.java @@ -136,8 +136,8 @@ public void afterClass() { @Test public void testPublishLevels() { - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(options.service()).andReturn(logging); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(options.getService()).andReturn(logging); logging.write(ImmutableList.of(FINEST_ENTRY), WriteOption.logName(LOG_NAME), WriteOption.resource(DEFAULT_RESOURCE)); EasyMock.expectLastCall(); @@ -200,8 +200,8 @@ public void testPublishLevels() { @Test public void testPublishCustomResource() { - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(options.service()).andReturn(logging); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(options.getService()).andReturn(logging); MonitoredResource resource = MonitoredResource.of("custom", ImmutableMap.of()); logging.write(ImmutableList.of(FINEST_ENTRY), WriteOption.logName(LOG_NAME), WriteOption.resource(resource)); @@ -215,8 +215,8 @@ public void testPublishCustomResource() { @Test public void testReportFlushError() { - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(options.service()).andReturn(logging); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(options.getService()).andReturn(logging); RuntimeException ex = new RuntimeException(); logging.write(ImmutableList.of(FINEST_ENTRY), WriteOption.logName(LOG_NAME), WriteOption.resource(DEFAULT_RESOURCE)); @@ -236,7 +236,7 @@ public void testReportFlushError() { @Test public void testReportFormatError() { - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); EasyMock.replay(options, logging); Formatter formatter = EasyMock.createStrictMock(Formatter.class); RuntimeException ex = new RuntimeException(); @@ -256,8 +256,8 @@ public void testReportFormatError() { @Test public void testFlushSize() { - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(options.service()).andReturn(logging); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(options.getService()).andReturn(logging); logging.write(ImmutableList.of(FINEST_ENTRY, FINER_ENTRY, FINE_ENTRY, CONFIG_ENTRY, INFO_ENTRY, WARNING_ENTRY), WriteOption.logName(LOG_NAME), WriteOption.resource(DEFAULT_RESOURCE)); EasyMock.expectLastCall(); @@ -276,8 +276,8 @@ public void testFlushSize() { @Test public void testFlushLevel() { - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(options.service()).andReturn(logging); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(options.getService()).andReturn(logging); logging.write(ImmutableList.of(FINEST_ENTRY, FINER_ENTRY, FINE_ENTRY, CONFIG_ENTRY, INFO_ENTRY, WARNING_ENTRY), WriteOption.logName(LOG_NAME), WriteOption.resource(DEFAULT_RESOURCE)); @@ -298,8 +298,8 @@ public void testFlushLevel() { @Test public void testAddHandler() { - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(options.service()).andReturn(logging); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(options.getService()).andReturn(logging); logging.write(ImmutableList.of(FINEST_ENTRY), WriteOption.logName(LOG_NAME), WriteOption.resource(DEFAULT_RESOURCE)); EasyMock.expectLastCall(); @@ -315,7 +315,7 @@ public void testAddHandler() { @Test public void testMaskLoggers() { - EasyMock.expect(options.projectId()).andReturn(PROJECT); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT); EasyMock.replay(options, logging); LoggingHandler handler = new LoggingHandler(LOG_NAME, options); Logger logger = Logger.getLogger("com.google"); @@ -331,8 +331,8 @@ public void testMaskLoggers() { @Test public void testClose() throws Exception { - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(options.service()).andReturn(logging); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(options.getService()).andReturn(logging); logging.write(ImmutableList.of(FINEST_ENTRY), WriteOption.logName(LOG_NAME), WriteOption.resource(DEFAULT_RESOURCE)); EasyMock.expectLastCall(); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingImplTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingImplTest.java index f55b21f27efc..cbecd379e9b8 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingImplTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/LoggingImplTest.java @@ -146,10 +146,10 @@ public void setUp() { loggingRpcMock = EasyMock.createStrictMock(LoggingRpc.class); EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(LoggingOptions.class))) .andReturn(loggingRpcMock); - options = LoggingOptions.builder() - .projectId(PROJECT) - .serviceRpcFactory(rpcFactoryMock) - .retryParams(RetryParams.noRetries()) + options = LoggingOptions.newBuilder() + .setProjectId(PROJECT) + .setServiceRpcFactory(rpcFactoryMock) + .setRetryParams(RetryParams.noRetries()) .build(); } @@ -161,7 +161,7 @@ public void tearDown() { @Test public void testGetOptions() { EasyMock.replay(rpcFactoryMock, loggingRpcMock); - assertSame(options, options.service().options()); + assertSame(options, options.getService().getOptions()); } @Test @@ -174,7 +174,7 @@ public void testCreateSink() { .build(); EasyMock.expect(loggingRpcMock.create(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); Sink sink = logging.create(SINK_INFO); assertEquals(new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), sink); } @@ -189,7 +189,7 @@ public void testCreateSinkAsync() throws ExecutionException, InterruptedExceptio .build(); EasyMock.expect(loggingRpcMock.create(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); Sink sink = logging.createAsync(SINK_INFO).get(); assertEquals(new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), sink); } @@ -204,7 +204,7 @@ public void testUpdateSink() { .build(); EasyMock.expect(loggingRpcMock.update(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); Sink sink = logging.update(SINK_INFO); assertEquals(new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), sink); } @@ -219,7 +219,7 @@ public void testUpdateSinkAsync() throws ExecutionException, InterruptedExceptio .build(); EasyMock.expect(loggingRpcMock.update(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); Sink sink = logging.updateAsync(SINK_INFO).get(); assertEquals(new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), sink); } @@ -231,7 +231,7 @@ public void testGetSink() { GetSinkRequest request = GetSinkRequest.newBuilder().setSinkName(SINK_NAME_PB).build(); EasyMock.expect(loggingRpcMock.get(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); Sink sink = logging.getSink(SINK_NAME); assertEquals(new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), sink); } @@ -242,7 +242,7 @@ public void testGetSink_Null() { GetSinkRequest request = GetSinkRequest.newBuilder().setSinkName(SINK_NAME_PB).build(); EasyMock.expect(loggingRpcMock.get(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertNull(logging.getSink(SINK_NAME)); } @@ -253,7 +253,7 @@ public void testGetSinkAsync() throws ExecutionException, InterruptedException { GetSinkRequest request = GetSinkRequest.newBuilder().setSinkName(SINK_NAME_PB).build(); EasyMock.expect(loggingRpcMock.get(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); Sink sink = logging.getSinkAsync(SINK_NAME).get(); assertEquals(new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), sink); } @@ -264,7 +264,7 @@ public void testGetSinkAsync_Null() throws ExecutionException, InterruptedExcept GetSinkRequest request = GetSinkRequest.newBuilder().setSinkName(SINK_NAME_PB).build(); EasyMock.expect(loggingRpcMock.get(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertNull(logging.getSinkAsync(SINK_NAME).get()); } @@ -274,7 +274,7 @@ public void testDeleteSink() { Future response = Futures.immediateFuture(Empty.getDefaultInstance()); EasyMock.expect(loggingRpcMock.delete(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertTrue(logging.deleteSink(SINK_NAME)); } @@ -284,7 +284,7 @@ public void testDeleteSink_Null() { Future response = Futures.immediateFuture(null); EasyMock.expect(loggingRpcMock.delete(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertFalse(logging.deleteSink(SINK_NAME)); } @@ -294,7 +294,7 @@ public void testDeleteSinkAsync() throws ExecutionException, InterruptedExceptio Future response = Futures.immediateFuture(Empty.getDefaultInstance()); EasyMock.expect(loggingRpcMock.delete(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertTrue(logging.deleteSinkAsync(SINK_NAME).get()); } @@ -304,7 +304,7 @@ public void testDeleteSinkAsync_Null() throws ExecutionException, InterruptedExc Future response = Futures.immediateFuture(null); EasyMock.expect(loggingRpcMock.delete(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertFalse(logging.deleteSinkAsync(SINK_NAME).get()); } @@ -312,7 +312,7 @@ public void testDeleteSinkAsync_Null() throws ExecutionException, InterruptedExc public void testListSinks() { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListSinksRequest request = ListSinksRequest.newBuilder().setParent(PROJECT_PB).build(); List sinkList = ImmutableList.of( new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), @@ -325,15 +325,15 @@ public void testListSinks() { EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); Page page = logging.listSinks(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.values(), Sink.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.getValues(), Sink.class)); } @Test public void testListSinksNextPage() { String cursor1 = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListSinksRequest request1 = ListSinksRequest.newBuilder().setParent(PROJECT_PB).build(); ListSinksRequest request2 = ListSinksRequest.newBuilder() .setParent(PROJECT_PB) @@ -359,17 +359,17 @@ public void testListSinksNextPage() { EasyMock.expect(loggingRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(loggingRpcMock); Page page = logging.listSinks(); - assertEquals(cursor1, page.nextPageCursor()); - assertArrayEquals(sinkList1.toArray(), Iterables.toArray(page.values(), Sink.class)); - page = page.nextPage(); - assertEquals(cursor2, page.nextPageCursor()); - assertArrayEquals(sinkList2.toArray(), Iterables.toArray(page.values(), Sink.class)); + assertEquals(cursor1, page.getNextPageCursor()); + assertArrayEquals(sinkList1.toArray(), Iterables.toArray(page.getValues(), Sink.class)); + page = page.getNextPage(); + assertEquals(cursor2, page.getNextPageCursor()); + assertArrayEquals(sinkList2.toArray(), Iterables.toArray(page.getValues(), Sink.class)); } @Test public void testListSinksEmpty() { EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListSinksRequest request = ListSinksRequest.newBuilder().setParent(PROJECT_PB).build(); List sinkList = ImmutableList.of(); ListSinksResponse response = ListSinksResponse.newBuilder() @@ -380,16 +380,16 @@ public void testListSinksEmpty() { EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); Page page = logging.listSinks(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); - assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.values(), Sink.class)); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); + assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.getValues(), Sink.class)); } @Test public void testListSinksWithOptions() { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListSinksRequest request = ListSinksRequest.newBuilder() .setPageToken(cursor) .setPageSize(42) @@ -406,15 +406,15 @@ public void testListSinksWithOptions() { EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); Page page = logging.listSinks(ListOption.pageSize(42), ListOption.pageToken(cursor)); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.values(), Sink.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.getValues(), Sink.class)); } @Test public void testListSinksAsync() throws ExecutionException, InterruptedException { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListSinksRequest request = ListSinksRequest.newBuilder().setParent(PROJECT_PB).build(); List sinkList = ImmutableList.of( new Sink(logging, new SinkInfo.BuilderImpl(SINK_INFO)), @@ -427,15 +427,15 @@ public void testListSinksAsync() throws ExecutionException, InterruptedException EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listSinksAsync().get(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.values(), Sink.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.getValues(), Sink.class)); } @Test public void testListSinksAsyncNextPage() throws ExecutionException, InterruptedException { String cursor1 = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListSinksRequest request1 = ListSinksRequest.newBuilder().setParent(PROJECT_PB).build(); ListSinksRequest request2 = ListSinksRequest.newBuilder() .setParent(PROJECT_PB) @@ -461,17 +461,17 @@ public void testListSinksAsyncNextPage() throws ExecutionException, InterruptedE EasyMock.expect(loggingRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listSinksAsync().get(); - assertEquals(cursor1, page.nextPageCursor()); - assertArrayEquals(sinkList1.toArray(), Iterables.toArray(page.values(), Sink.class)); - page = page.nextPageAsync().get(); - assertEquals(cursor2, page.nextPageCursor()); - assertArrayEquals(sinkList2.toArray(), Iterables.toArray(page.values(), Sink.class)); + assertEquals(cursor1, page.getNextPageCursor()); + assertArrayEquals(sinkList1.toArray(), Iterables.toArray(page.getValues(), Sink.class)); + page = page.getNextPageAsync().get(); + assertEquals(cursor2, page.getNextPageCursor()); + assertArrayEquals(sinkList2.toArray(), Iterables.toArray(page.getValues(), Sink.class)); } @Test public void testListSinksAsyncEmpty() throws ExecutionException, InterruptedException { EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListSinksRequest request = ListSinksRequest.newBuilder().setParent(PROJECT_PB).build(); List sinkList = ImmutableList.of(); ListSinksResponse response = ListSinksResponse.newBuilder() @@ -482,16 +482,16 @@ public void testListSinksAsyncEmpty() throws ExecutionException, InterruptedExce EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listSinksAsync().get(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); - assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.values(), Sink.class)); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); + assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.getValues(), Sink.class)); } @Test public void testListSinksWithOptionsAsync() throws ExecutionException, InterruptedException { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListSinksRequest request = ListSinksRequest.newBuilder() .setPageToken(cursor) .setPageSize(42) @@ -509,8 +509,8 @@ public void testListSinksWithOptionsAsync() throws ExecutionException, Interrupt EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listSinksAsync(ListOption.pageSize(42), ListOption.pageToken(cursor)).get(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.values(), Sink.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.getValues(), Sink.class)); } @Test @@ -523,7 +523,7 @@ public void testCreateMetric() { .build(); EasyMock.expect(loggingRpcMock.create(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); Metric metric = logging.create(METRIC_INFO); assertEquals(new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)), metric); } @@ -538,7 +538,7 @@ public void testCreateMetricAsync() throws ExecutionException, InterruptedExcept .build(); EasyMock.expect(loggingRpcMock.create(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); Metric metric = logging.createAsync(METRIC_INFO).get(); assertEquals(new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)), metric); } @@ -553,7 +553,7 @@ public void testUpdateMetric() { .build(); EasyMock.expect(loggingRpcMock.update(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); Metric sink = logging.update(METRIC_INFO); assertEquals(new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)), sink); } @@ -568,7 +568,7 @@ public void testUpdateMetricAsync() throws ExecutionException, InterruptedExcept .build(); EasyMock.expect(loggingRpcMock.update(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); Metric sink = logging.updateAsync(METRIC_INFO).get(); assertEquals(new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)), sink); } @@ -581,7 +581,7 @@ public void testGetMetric() { GetLogMetricRequest.newBuilder().setMetricName(METRIC_NAME_PB).build(); EasyMock.expect(loggingRpcMock.get(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); Metric sink = logging.getMetric(METRIC_NAME); assertEquals(new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)), sink); } @@ -593,7 +593,7 @@ public void testGetMetric_Null() { GetLogMetricRequest.newBuilder().setMetricName(METRIC_NAME_PB).build(); EasyMock.expect(loggingRpcMock.get(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertNull(logging.getMetric(METRIC_NAME)); } @@ -605,7 +605,7 @@ public void testGetMetricAsync() throws ExecutionException, InterruptedException GetLogMetricRequest.newBuilder().setMetricName(METRIC_NAME_PB).build(); EasyMock.expect(loggingRpcMock.get(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); Metric sink = logging.getMetricAsync(METRIC_NAME).get(); assertEquals(new Metric(logging, new MetricInfo.BuilderImpl(METRIC_INFO)), sink); } @@ -617,7 +617,7 @@ public void testGetMetricAsync_Null() throws ExecutionException, InterruptedExce GetLogMetricRequest.newBuilder().setMetricName(METRIC_NAME_PB).build(); EasyMock.expect(loggingRpcMock.get(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertNull(logging.getMetricAsync(METRIC_NAME).get()); } @@ -628,7 +628,7 @@ public void testDeleteMetric() { Future response = Futures.immediateFuture(Empty.getDefaultInstance()); EasyMock.expect(loggingRpcMock.delete(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertTrue(logging.deleteMetric(METRIC_NAME)); } @@ -639,7 +639,7 @@ public void testDeleteMetric_Null() { Future response = Futures.immediateFuture(null); EasyMock.expect(loggingRpcMock.delete(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertFalse(logging.deleteMetric(METRIC_NAME)); } @@ -650,7 +650,7 @@ public void testDeleteMetricAsync() throws ExecutionException, InterruptedExcept Future response = Futures.immediateFuture(Empty.getDefaultInstance()); EasyMock.expect(loggingRpcMock.delete(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertTrue(logging.deleteMetricAsync(METRIC_NAME).get()); } @@ -661,7 +661,7 @@ public void testDeleteMetricAsync_Null() throws ExecutionException, InterruptedE Future response = Futures.immediateFuture(null); EasyMock.expect(loggingRpcMock.delete(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertFalse(logging.deleteMetricAsync(METRIC_NAME).get()); } @@ -669,7 +669,7 @@ public void testDeleteMetricAsync_Null() throws ExecutionException, InterruptedE public void testListMetrics() { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder().setParent(PROJECT_PB).build(); List sinkList = ImmutableList.of( @@ -683,15 +683,15 @@ public void testListMetrics() { EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); Page page = logging.listMetrics(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.values(), Metric.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.getValues(), Metric.class)); } @Test public void testListMetricsNextPage() { String cursor1 = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogMetricsRequest request1 = ListLogMetricsRequest.newBuilder().setParent(PROJECT_PB).build(); ListLogMetricsRequest request2 = ListLogMetricsRequest.newBuilder() @@ -718,17 +718,17 @@ public void testListMetricsNextPage() { EasyMock.expect(loggingRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(loggingRpcMock); Page page = logging.listMetrics(); - assertEquals(cursor1, page.nextPageCursor()); - assertArrayEquals(sinkList1.toArray(), Iterables.toArray(page.values(), Metric.class)); - page = page.nextPage(); - assertEquals(cursor2, page.nextPageCursor()); - assertArrayEquals(sinkList2.toArray(), Iterables.toArray(page.values(), Metric.class)); + assertEquals(cursor1, page.getNextPageCursor()); + assertArrayEquals(sinkList1.toArray(), Iterables.toArray(page.getValues(), Metric.class)); + page = page.getNextPage(); + assertEquals(cursor2, page.getNextPageCursor()); + assertArrayEquals(sinkList2.toArray(), Iterables.toArray(page.getValues(), Metric.class)); } @Test public void testListMetricsEmpty() { EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder().setParent(PROJECT_PB).build(); List sinkList = ImmutableList.of(); @@ -740,16 +740,16 @@ public void testListMetricsEmpty() { EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); Page page = logging.listMetrics(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); - assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.values(), Metric.class)); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); + assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.getValues(), Metric.class)); } @Test public void testListMetricsWithOptions() { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder() .setPageToken(cursor) .setPageSize(42) @@ -766,15 +766,15 @@ public void testListMetricsWithOptions() { EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); Page page = logging.listMetrics(ListOption.pageSize(42), ListOption.pageToken(cursor)); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.values(), Metric.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.getValues(), Metric.class)); } @Test public void testListMetricsAsync() throws ExecutionException, InterruptedException { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder().setParent(PROJECT_PB).build(); List sinkList = ImmutableList.of( @@ -788,15 +788,15 @@ public void testListMetricsAsync() throws ExecutionException, InterruptedExcepti EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listMetricsAsync().get(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.values(), Metric.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.getValues(), Metric.class)); } @Test public void testListMetricsAsyncNextPage() throws ExecutionException, InterruptedException { String cursor1 = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogMetricsRequest request1 = ListLogMetricsRequest.newBuilder().setParent(PROJECT_PB).build(); ListLogMetricsRequest request2 = ListLogMetricsRequest.newBuilder() @@ -823,17 +823,17 @@ public void testListMetricsAsyncNextPage() throws ExecutionException, Interrupte EasyMock.expect(loggingRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listMetricsAsync().get(); - assertEquals(cursor1, page.nextPageCursor()); - assertArrayEquals(sinkList1.toArray(), Iterables.toArray(page.values(), Metric.class)); - page = page.nextPageAsync().get(); - assertEquals(cursor2, page.nextPageCursor()); - assertArrayEquals(sinkList2.toArray(), Iterables.toArray(page.values(), Metric.class)); + assertEquals(cursor1, page.getNextPageCursor()); + assertArrayEquals(sinkList1.toArray(), Iterables.toArray(page.getValues(), Metric.class)); + page = page.getNextPageAsync().get(); + assertEquals(cursor2, page.getNextPageCursor()); + assertArrayEquals(sinkList2.toArray(), Iterables.toArray(page.getValues(), Metric.class)); } @Test public void testListMetricsAsyncEmpty() throws ExecutionException, InterruptedException { EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder().setParent(PROJECT_PB).build(); List sinkList = ImmutableList.of(); @@ -845,16 +845,16 @@ public void testListMetricsAsyncEmpty() throws ExecutionException, InterruptedEx EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listMetricsAsync().get(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); - assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.values(), Metric.class)); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); + assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.getValues(), Metric.class)); } @Test public void testListMetricsWithOptionsAsync() throws ExecutionException, InterruptedException { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogMetricsRequest request = ListLogMetricsRequest.newBuilder() .setPageToken(cursor) .setPageSize(42) @@ -872,15 +872,15 @@ public void testListMetricsWithOptionsAsync() throws ExecutionException, Interru EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listMetricsAsync(ListOption.pageSize(42), ListOption.pageToken(cursor)).get(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.values(), Metric.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(sinkList.toArray(), Iterables.toArray(page.getValues(), Metric.class)); } @Test public void testListResourceDescriptor() { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder().build(); List descriptorList = ImmutableList.of(DESCRIPTOR, DESCRIPTOR); @@ -894,16 +894,16 @@ public void testListResourceDescriptor() { EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); Page page = logging.listMonitoredResourceDescriptors(); - assertEquals(cursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); assertArrayEquals(descriptorList.toArray(), - Iterables.toArray(page.values(), MonitoredResourceDescriptor.class)); + Iterables.toArray(page.getValues(), MonitoredResourceDescriptor.class)); } @Test public void testListResourceDescriptorNextPage() { String cursor1 = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListMonitoredResourceDescriptorsRequest request1 = ListMonitoredResourceDescriptorsRequest.newBuilder().build(); ListMonitoredResourceDescriptorsRequest request2 = @@ -929,19 +929,19 @@ public void testListResourceDescriptorNextPage() { EasyMock.expect(loggingRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(loggingRpcMock); Page page = logging.listMonitoredResourceDescriptors(); - assertEquals(cursor1, page.nextPageCursor()); - assertArrayEquals(descriptorList1.toArray(), Iterables.toArray(page.values(), + assertEquals(cursor1, page.getNextPageCursor()); + assertArrayEquals(descriptorList1.toArray(), Iterables.toArray(page.getValues(), MonitoredResourceDescriptor.class)); - page = page.nextPage(); - assertEquals(cursor2, page.nextPageCursor()); + page = page.getNextPage(); + assertEquals(cursor2, page.getNextPageCursor()); assertArrayEquals(descriptorList2.toArray(), - Iterables.toArray(page.values(), MonitoredResourceDescriptor.class)); + Iterables.toArray(page.getValues(), MonitoredResourceDescriptor.class)); } @Test public void testListResourceDescriptorEmpty() { EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder().build(); List descriptorList = ImmutableList.of(); @@ -955,17 +955,17 @@ public void testListResourceDescriptorEmpty() { EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); Page page = logging.listMonitoredResourceDescriptors(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); assertArrayEquals(descriptorList.toArray(), - Iterables.toArray(page.values(), MonitoredResourceDescriptor.class)); + Iterables.toArray(page.getValues(), MonitoredResourceDescriptor.class)); } @Test public void testListResourceDescriptorWithOptions() { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder() .setPageToken(cursor) @@ -983,16 +983,16 @@ public void testListResourceDescriptorWithOptions() { EasyMock.replay(loggingRpcMock); Page page = logging.listMonitoredResourceDescriptors( ListOption.pageSize(42), ListOption.pageToken(cursor)); - assertEquals(cursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); assertArrayEquals(descriptorList.toArray(), - Iterables.toArray(page.values(), MonitoredResourceDescriptor.class)); + Iterables.toArray(page.getValues(), MonitoredResourceDescriptor.class)); } @Test public void testListResourceDescriptorAsync() throws ExecutionException, InterruptedException { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder().build(); List descriptorList = ImmutableList.of(DESCRIPTOR, DESCRIPTOR); @@ -1007,16 +1007,16 @@ public void testListResourceDescriptorAsync() throws ExecutionException, Interru EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listMonitoredResourceDescriptorsAsync().get(); - assertEquals(cursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); assertArrayEquals(descriptorList.toArray(), - Iterables.toArray(page.values(), MonitoredResourceDescriptor.class)); + Iterables.toArray(page.getValues(), MonitoredResourceDescriptor.class)); } @Test public void testListResourceDescriptorAsyncNextPage() throws ExecutionException, InterruptedException { String cursor1 = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListMonitoredResourceDescriptorsRequest request1 = ListMonitoredResourceDescriptorsRequest.newBuilder().build(); ListMonitoredResourceDescriptorsRequest request2 = @@ -1043,20 +1043,20 @@ public void testListResourceDescriptorAsyncNextPage() throws ExecutionException, EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listMonitoredResourceDescriptorsAsync().get(); - assertEquals(cursor1, page.nextPageCursor()); - assertArrayEquals(descriptorList1.toArray(), Iterables.toArray(page.values(), + assertEquals(cursor1, page.getNextPageCursor()); + assertArrayEquals(descriptorList1.toArray(), Iterables.toArray(page.getValues(), MonitoredResourceDescriptor.class)); - page = page.nextPageAsync().get(); - assertEquals(cursor2, page.nextPageCursor()); + page = page.getNextPageAsync().get(); + assertEquals(cursor2, page.getNextPageCursor()); assertArrayEquals(descriptorList2.toArray(), - Iterables.toArray(page.values(), MonitoredResourceDescriptor.class)); + Iterables.toArray(page.getValues(), MonitoredResourceDescriptor.class)); } @Test public void testListResourceDescriptorAsyncEmpty() throws ExecutionException, InterruptedException { EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder().build(); List descriptorList = ImmutableList.of(); @@ -1071,10 +1071,10 @@ public void testListResourceDescriptorAsyncEmpty() EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listMonitoredResourceDescriptorsAsync().get(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); assertArrayEquals(descriptorList.toArray(), - Iterables.toArray(page.values(), MonitoredResourceDescriptor.class)); + Iterables.toArray(page.getValues(), MonitoredResourceDescriptor.class)); } @Test @@ -1082,7 +1082,7 @@ public void testListResourceDescriptorAsyncWithOptions() throws ExecutionException, InterruptedException { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListMonitoredResourceDescriptorsRequest request = ListMonitoredResourceDescriptorsRequest.newBuilder() .setPageToken(cursor) @@ -1100,9 +1100,9 @@ public void testListResourceDescriptorAsyncWithOptions() EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listMonitoredResourceDescriptorsAsync( ListOption.pageSize(42), ListOption.pageToken(cursor)).get(); - assertEquals(cursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); assertArrayEquals(descriptorList.toArray(), - Iterables.toArray(page.values(), MonitoredResourceDescriptor.class)); + Iterables.toArray(page.getValues(), MonitoredResourceDescriptor.class)); } @Test @@ -1111,7 +1111,7 @@ public void testDeleteLog() { Future response = Futures.immediateFuture(Empty.getDefaultInstance()); EasyMock.expect(loggingRpcMock.delete(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertTrue(logging.deleteLog(LOG_NAME)); } @@ -1120,7 +1120,7 @@ public void testDeleteLog_Null() { DeleteLogRequest request = DeleteLogRequest.newBuilder().setLogName(LOG_NAME_PB).build(); EasyMock.expect(loggingRpcMock.delete(request)).andReturn(Futures.immediateFuture(null)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertFalse(logging.deleteLog(LOG_NAME)); } @@ -1130,7 +1130,7 @@ public void testDeleteLogAync() throws ExecutionException, InterruptedException Future response = Futures.immediateFuture(Empty.getDefaultInstance()); EasyMock.expect(loggingRpcMock.delete(request)).andReturn(response); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertTrue(logging.deleteLogAsync(LOG_NAME).get()); } @@ -1139,7 +1139,7 @@ public void testDeleteLogAsync_Null() throws ExecutionException, InterruptedExce DeleteLogRequest request = DeleteLogRequest.newBuilder().setLogName(LOG_NAME_PB).build(); EasyMock.expect(loggingRpcMock.delete(request)).andReturn(Futures.immediateFuture(null)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); assertFalse(logging.deleteLogAsync(LOG_NAME).get()); } @@ -1152,7 +1152,7 @@ public void testWriteLogEntries() { WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(Futures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); logging.write(ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2)); } @@ -1169,7 +1169,7 @@ public void testWriteLogEntriesWithOptions() { WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(Futures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); logging.write(ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2), WriteOption.logName(LOG_NAME), WriteOption.resource(MONITORED_RESOURCE), WriteOption.labels(labels)); } @@ -1183,7 +1183,7 @@ public void testWriteLogEntriesAsync() throws ExecutionException, InterruptedExc WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(Futures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); logging.writeAsync(ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2)).get(); } @@ -1200,7 +1200,7 @@ public void testWriteLogEntriesAsyncWithOptions() { WriteLogEntriesResponse response = WriteLogEntriesResponse.newBuilder().build(); EasyMock.expect(loggingRpcMock.write(request)).andReturn(Futures.immediateFuture(response)); EasyMock.replay(rpcFactoryMock, loggingRpcMock); - logging = options.service(); + logging = options.getService(); logging.writeAsync(ImmutableList.of(LOG_ENTRY1, LOG_ENTRY2), WriteOption.logName(LOG_NAME), WriteOption.resource(MONITORED_RESOURCE), WriteOption.labels(labels)); } @@ -1209,7 +1209,7 @@ public void testWriteLogEntriesAsyncWithOptions() { public void testListLogEntries() { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogEntriesRequest request = ListLogEntriesRequest.newBuilder() .addProjectIds(PROJECT) .build(); @@ -1222,15 +1222,15 @@ public void testListLogEntries() { EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); Page page = logging.listLogEntries(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(entriesList.toArray(), Iterables.toArray(page.values(), LogEntry.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(entriesList.toArray(), Iterables.toArray(page.getValues(), LogEntry.class)); } @Test public void testListLogEntriesNextPage() throws ExecutionException, InterruptedException { String cursor1 = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogEntriesRequest request1 = ListLogEntriesRequest.newBuilder() .addProjectIds(PROJECT) .build(); @@ -1255,18 +1255,20 @@ public void testListLogEntriesNextPage() throws ExecutionException, InterruptedE EasyMock.expect(loggingRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listLogEntriesAsync().get(); - assertEquals(cursor1, page.nextPageCursor()); - assertArrayEquals(descriptorList1.toArray(), Iterables.toArray(page.values(), LogEntry.class)); - page = page.nextPageAsync().get(); - assertEquals(cursor2, page.nextPageCursor()); - assertArrayEquals(descriptorList2.toArray(), Iterables.toArray(page.values(), LogEntry.class)); + assertEquals(cursor1, page.getNextPageCursor()); + assertArrayEquals(descriptorList1.toArray(), + Iterables.toArray(page.getValues(), LogEntry.class)); + page = page.getNextPageAsync().get(); + assertEquals(cursor2, page.getNextPageCursor()); + assertArrayEquals(descriptorList2.toArray(), + Iterables.toArray(page.getValues(), LogEntry.class)); } @Test public void testListLogEntriesEmpty() { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogEntriesRequest request = ListLogEntriesRequest.newBuilder() .addProjectIds(PROJECT) .build(); @@ -1279,15 +1281,15 @@ public void testListLogEntriesEmpty() { EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); Page page = logging.listLogEntries(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(entriesList.toArray(), Iterables.toArray(page.values(), LogEntry.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(entriesList.toArray(), Iterables.toArray(page.getValues(), LogEntry.class)); } @Test public void testListLogEntriesWithOptions() { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogEntriesRequest request = ListLogEntriesRequest.newBuilder() .addProjectIds(PROJECT) .setOrderBy("timestamp desc") @@ -1303,15 +1305,15 @@ public void testListLogEntriesWithOptions() { EasyMock.replay(loggingRpcMock); Page page = logging.listLogEntries(EntryListOption.filter("logName:syslog"), EntryListOption.sortOrder(SortingField.TIMESTAMP, Logging.SortingOrder.DESCENDING)); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(entriesList.toArray(), Iterables.toArray(page.values(), LogEntry.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(entriesList.toArray(), Iterables.toArray(page.getValues(), LogEntry.class)); } @Test public void testListLogEntriesAsync() throws ExecutionException, InterruptedException { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogEntriesRequest request = ListLogEntriesRequest.newBuilder() .addProjectIds(PROJECT) .build(); @@ -1324,15 +1326,15 @@ public void testListLogEntriesAsync() throws ExecutionException, InterruptedExce EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listLogEntriesAsync().get(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(entriesList.toArray(), Iterables.toArray(page.values(), LogEntry.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(entriesList.toArray(), Iterables.toArray(page.getValues(), LogEntry.class)); } @Test public void testListLogEntriesAsyncNextPage() { String cursor1 = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogEntriesRequest request1 = ListLogEntriesRequest.newBuilder() .addProjectIds(PROJECT) .build(); @@ -1357,18 +1359,20 @@ public void testListLogEntriesAsyncNextPage() { EasyMock.expect(loggingRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(loggingRpcMock); Page page = logging.listLogEntries(); - assertEquals(cursor1, page.nextPageCursor()); - assertArrayEquals(descriptorList1.toArray(), Iterables.toArray(page.values(), LogEntry.class)); - page = page.nextPage(); - assertEquals(cursor2, page.nextPageCursor()); - assertArrayEquals(descriptorList2.toArray(), Iterables.toArray(page.values(), LogEntry.class)); + assertEquals(cursor1, page.getNextPageCursor()); + assertArrayEquals(descriptorList1.toArray(), + Iterables.toArray(page.getValues(), LogEntry.class)); + page = page.getNextPage(); + assertEquals(cursor2, page.getNextPageCursor()); + assertArrayEquals(descriptorList2.toArray(), + Iterables.toArray(page.getValues(), LogEntry.class)); } @Test public void testListLogEntriesAyncEmpty() throws ExecutionException, InterruptedException { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogEntriesRequest request = ListLogEntriesRequest.newBuilder() .addProjectIds(PROJECT) .build(); @@ -1381,15 +1385,15 @@ public void testListLogEntriesAyncEmpty() throws ExecutionException, Interrupted EasyMock.expect(loggingRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listLogEntriesAsync().get(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(entriesList.toArray(), Iterables.toArray(page.values(), LogEntry.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(entriesList.toArray(), Iterables.toArray(page.getValues(), LogEntry.class)); } @Test public void testListLogEntriesAsyncWithOptions() throws ExecutionException, InterruptedException { String cursor = "cursor"; EasyMock.replay(rpcFactoryMock); - logging = options.service(); + logging = options.getService(); ListLogEntriesRequest request = ListLogEntriesRequest.newBuilder() .addProjectIds(PROJECT) .setOrderBy("timestamp desc") @@ -1405,7 +1409,7 @@ public void testListLogEntriesAsyncWithOptions() throws ExecutionException, Inte EasyMock.replay(loggingRpcMock); AsyncPage page = logging.listLogEntriesAsync(EntryListOption.filter("logName:syslog"), EntryListOption.sortOrder(SortingField.TIMESTAMP, Logging.SortingOrder.DESCENDING)).get(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(entriesList.toArray(), Iterables.toArray(page.values(), LogEntry.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(entriesList.toArray(), Iterables.toArray(page.getValues(), LogEntry.class)); } } diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricTest.java index 6f9b00edc23f..1fa008c72f16 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/MetricTest.java @@ -52,7 +52,7 @@ public class MetricTest { private Metric metric; private void initializeExpectedMetric(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); logging = createStrictMock(Logging.class); expectedMetric = new Metric(serviceMockReturnsOptions, new Metric.BuilderImpl(METRIC_INFO)); @@ -110,7 +110,7 @@ public void testReload() { MetricInfo updatedInfo = METRIC_INFO.toBuilder().setFilter(NEW_FILTER).build(); Metric expectedMetric = new Metric(serviceMockReturnsOptions, new MetricInfo.BuilderImpl(updatedInfo)); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.getMetric(NAME)).andReturn(expectedMetric); replay(logging); initializeMetric(); @@ -121,7 +121,7 @@ public void testReload() { @Test public void testReloadNull() { initializeExpectedMetric(1); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.getMetric(NAME)).andReturn(null); replay(logging); initializeMetric(); @@ -133,7 +133,7 @@ public void testReloadAsync() throws ExecutionException, InterruptedException { initializeExpectedMetric(2); MetricInfo updatedInfo = METRIC_INFO.toBuilder().setFilter(NEW_FILTER).build(); Metric expectedMetric = new Metric(serviceMockReturnsOptions, new MetricInfo.BuilderImpl(updatedInfo)); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.getMetricAsync(NAME)) .andReturn(Futures.immediateFuture(expectedMetric)); replay(logging); @@ -145,7 +145,7 @@ public void testReloadAsync() throws ExecutionException, InterruptedException { @Test public void testReloadAsyncNull() throws ExecutionException, InterruptedException { initializeExpectedMetric(1); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.getMetricAsync(NAME)).andReturn(Futures.immediateFuture(null)); replay(logging); initializeMetric(); @@ -158,7 +158,7 @@ public void testUpdate() { MetricInfo updatedInfo = METRIC_INFO.toBuilder().setFilter(NEW_FILTER).build(); Metric expectedMetric = new Metric(serviceMockReturnsOptions, new MetricInfo.BuilderImpl(updatedInfo)); - expect(logging.options()).andReturn(mockOptions).times(2); + expect(logging.getOptions()).andReturn(mockOptions).times(2); expect(logging.update(expectedMetric)).andReturn(expectedMetric); replay(logging); initializeMetric(); @@ -172,7 +172,7 @@ public void testUpdateAsync() throws ExecutionException, InterruptedException { MetricInfo updatedInfo = METRIC_INFO.toBuilder().setFilter(NEW_FILTER).build(); Metric expectedMetric = new Metric(serviceMockReturnsOptions, new MetricInfo.BuilderImpl(updatedInfo)); - expect(logging.options()).andReturn(mockOptions).times(2); + expect(logging.getOptions()).andReturn(mockOptions).times(2); expect(logging.updateAsync(expectedMetric)).andReturn(Futures.immediateFuture(expectedMetric)); replay(logging); initializeMetric(); @@ -183,7 +183,7 @@ public void testUpdateAsync() throws ExecutionException, InterruptedException { @Test public void testDeleteTrue() { initializeExpectedMetric(1); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.deleteMetric(NAME)).andReturn(true); replay(logging); initializeMetric(); @@ -193,7 +193,7 @@ public void testDeleteTrue() { @Test public void testDeleteFalse() { initializeExpectedMetric(1); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.deleteMetric(NAME)).andReturn(false); replay(logging); initializeMetric(); @@ -203,7 +203,7 @@ public void testDeleteFalse() { @Test public void testDeleteAsyncTrue() throws ExecutionException, InterruptedException { initializeExpectedMetric(1); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.deleteMetricAsync(NAME)).andReturn(Futures.immediateFuture(true)); replay(logging); initializeMetric(); @@ -213,7 +213,7 @@ public void testDeleteAsyncTrue() throws ExecutionException, InterruptedExceptio @Test public void testDeleteAsyncFalse() throws ExecutionException, InterruptedException { initializeExpectedMetric(1); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.deleteMetricAsync(NAME)).andReturn(Futures.immediateFuture(false)); replay(logging); initializeMetric(); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java index ca172c933506..bdb7d0e908b0 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/SerializationTest.java @@ -39,11 +39,11 @@ public class SerializationTest extends BaseSerializationTest { - private static final Logging LOGGING = LoggingOptions.builder() - .projectId("p") - .authCredentials(AuthCredentials.noAuth()) - .host("localhost") - .build().service(); + private static final Logging LOGGING = LoggingOptions.newBuilder() + .setProjectId("p") + .setAuthCredentials(AuthCredentials.noAuth()) + .setHost("localhost") + .build().getService(); private static final HttpRequest HTTP_REQUEST = HttpRequest.newBuilder() .setRequestMethod(HttpRequest.RequestMethod.GET) .setStatus(404) @@ -80,9 +80,9 @@ public class SerializationTest extends BaseSerializationTest { @Override protected Serializable[] serializableObjects() { - LoggingOptions options = LoggingOptions.builder() - .projectId("p1") - .initialTimeout(1234) + LoggingOptions options = LoggingOptions.newBuilder() + .setProjectId("p1") + .setInitialTimeout(1234) .build(); return new Serializable[]{options, HTTP_REQUEST, OPERATION, STRING_PAYLOAD, JSON_PAYLOAD, PROTO_PAYLOAD, ENTRY, METRIC_INFO, METRIC, BUCKET_DESTINATION, DATASET_DESTINATION, diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkTest.java index de4325765ef5..4b4d79284d90 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/SinkTest.java @@ -59,7 +59,7 @@ public class SinkTest { private Sink sink; private void initializeExpectedSink(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); logging = createStrictMock(Logging.class); expectedSink = new Sink(serviceMockReturnsOptions, new Sink.BuilderImpl(SINK_INFO)); @@ -119,7 +119,7 @@ public void testReload() { SinkInfo updatedInfo = SINK_INFO.toBuilder().setFilter(NEW_FILTER).build(); Sink expectedSink = new Sink(serviceMockReturnsOptions, new SinkInfo.BuilderImpl(updatedInfo)); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.getSink(NAME)).andReturn(expectedSink); replay(logging); initializeSink(); @@ -130,7 +130,7 @@ public void testReload() { @Test public void testReloadNull() { initializeExpectedSink(1); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.getSink(NAME)).andReturn(null); replay(logging); initializeSink(); @@ -142,7 +142,7 @@ public void testReloadAsync() throws ExecutionException, InterruptedException { initializeExpectedSink(2); SinkInfo updatedInfo = SINK_INFO.toBuilder().setFilter(NEW_FILTER).build(); Sink expectedSink = new Sink(serviceMockReturnsOptions, new SinkInfo.BuilderImpl(updatedInfo)); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.getSinkAsync(NAME)) .andReturn(Futures.immediateFuture(expectedSink)); replay(logging); @@ -154,7 +154,7 @@ public void testReloadAsync() throws ExecutionException, InterruptedException { @Test public void testReloadAsyncNull() throws ExecutionException, InterruptedException { initializeExpectedSink(1); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.getSinkAsync(NAME)).andReturn(Futures.immediateFuture(null)); replay(logging); initializeSink(); @@ -166,7 +166,7 @@ public void testUpdate() { initializeExpectedSink(2); SinkInfo updatedInfo = SINK_INFO.toBuilder().setFilter(NEW_FILTER).build(); Sink expectedSink = new Sink(serviceMockReturnsOptions, new SinkInfo.BuilderImpl(updatedInfo)); - expect(logging.options()).andReturn(mockOptions).times(2); + expect(logging.getOptions()).andReturn(mockOptions).times(2); expect(logging.update(expectedSink)).andReturn(expectedSink); replay(logging); initializeSink(); @@ -179,7 +179,7 @@ public void testUpdateAsync() throws ExecutionException, InterruptedException { initializeExpectedSink(2); SinkInfo updatedInfo = SINK_INFO.toBuilder().setFilter(NEW_FILTER).build(); Sink expectedSink = new Sink(serviceMockReturnsOptions, new SinkInfo.BuilderImpl(updatedInfo)); - expect(logging.options()).andReturn(mockOptions).times(2); + expect(logging.getOptions()).andReturn(mockOptions).times(2); expect(logging.updateAsync(expectedSink)).andReturn(Futures.immediateFuture(expectedSink)); replay(logging); initializeSink(); @@ -190,7 +190,7 @@ public void testUpdateAsync() throws ExecutionException, InterruptedException { @Test public void testDeleteTrue() { initializeExpectedSink(1); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.deleteSink(NAME)).andReturn(true); replay(logging); initializeSink(); @@ -200,7 +200,7 @@ public void testDeleteTrue() { @Test public void testDeleteFalse() { initializeExpectedSink(1); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.deleteSink(NAME)).andReturn(false); replay(logging); initializeSink(); @@ -210,7 +210,7 @@ public void testDeleteFalse() { @Test public void testDeleteAsyncTrue() throws ExecutionException, InterruptedException { initializeExpectedSink(1); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.deleteSinkAsync(NAME)).andReturn(Futures.immediateFuture(true)); replay(logging); initializeSink(); @@ -220,7 +220,7 @@ public void testDeleteAsyncTrue() throws ExecutionException, InterruptedExceptio @Test public void testDeleteAsyncFalse() throws ExecutionException, InterruptedException { initializeExpectedSink(1); - expect(logging.options()).andReturn(mockOptions); + expect(logging.getOptions()).andReturn(mockOptions); expect(logging.deleteSinkAsync(NAME)).andReturn(Futures.immediateFuture(false)); replay(logging); initializeSink(); diff --git a/google-cloud-logging/src/test/java/com/google/cloud/logging/it/ITLoggingTest.java b/google-cloud-logging/src/test/java/com/google/cloud/logging/it/ITLoggingTest.java index f3df67838816..d1578a8de1cc 100644 --- a/google-cloud-logging/src/test/java/com/google/cloud/logging/it/ITLoggingTest.java +++ b/google-cloud-logging/src/test/java/com/google/cloud/logging/it/ITLoggingTest.java @@ -35,7 +35,7 @@ public class ITLoggingTest extends BaseSystemTest { @BeforeClass public static void beforeClass() { RemoteLoggingHelper helper = RemoteLoggingHelper.create(); - logging = helper.getOptions().service(); + logging = helper.getOptions().getService(); } @AfterClass diff --git a/google-cloud-pubsub/README.md b/google-cloud-pubsub/README.md index ed2f91bfe787..446a3c148ba4 100644 --- a/google-cloud-pubsub/README.md +++ b/google-cloud-pubsub/README.md @@ -92,7 +92,7 @@ code to create your service object: import com.google.cloud.pubsub.PubSub; import com.google.cloud.pubsub.PubSubOptions; -try(PubSub pubsub = PubSubOptions.defaultInstance().service()) { +try(PubSub pubsub = PubSubOptions.getDefaultInstance().getService()) { // use pubsub here } ``` diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/AckDeadlineRenewer.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/AckDeadlineRenewer.java index d72f788cff65..8bc81606c1ab 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/AckDeadlineRenewer.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/AckDeadlineRenewer.java @@ -154,11 +154,11 @@ public String toString() { } AckDeadlineRenewer(PubSub pubsub) { - PubSubOptions options = pubsub.options(); + PubSubOptions options = pubsub.getOptions(); this.pubsub = pubsub; - this.executorFactory = options.executorFactory(); + this.executorFactory = options.getExecutorFactory(); this.executor = executorFactory.get(); - this.clock = options.clock(); + this.clock = options.getClock(); this.messageQueue = new LinkedList<>(); this.messageDeadlines = new HashMap<>(); } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Message.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Message.java index bd9e0a3c30b9..d728dad43aea 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Message.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Message.java @@ -75,8 +75,8 @@ private static final class InternalByteArray extends ByteArray { } @Override - protected ByteString byteString() { - return super.byteString(); + protected ByteString getByteString() { + return super.getByteString(); } } @@ -366,7 +366,7 @@ PubsubMessage toPb() { if (id != null) { builder.setMessageId(id); } - builder.setData(payload.byteString()); + builder.setData(payload.getByteString()); builder.putAllAttributes(attributes); Timestamp.Builder tsBuilder = Timestamp.newBuilder(); if (publishTime != null) { diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/MessageConsumerImpl.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/MessageConsumerImpl.java index cb08dde00327..3a41b1501ef6 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/MessageConsumerImpl.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/MessageConsumerImpl.java @@ -154,7 +154,7 @@ public void failure(Throwable error) { private PullRequest createPullRequest() { return PullRequest.newBuilder() - .setSubscription(formatSubscriptionName(pubsubOptions.projectId(), subscription)) + .setSubscription(formatSubscriptionName(pubsubOptions.getProjectId(), subscription)) .setMaxMessages(maxQueuedCallbacks - queuedCallbacks.get()) .setReturnImmediately(false) .build(); @@ -166,11 +166,11 @@ private Runnable ackingRunnable(final ReceivedMessage receivedMessage) { public void run() { try { messageProcessor.process(receivedMessage); - pubsub.ackAsync(receivedMessage.subscription(), receivedMessage.ackId()); + pubsub.ackAsync(receivedMessage.getSubscription(), receivedMessage.getAckId()); } catch (Exception ex) { - pubsub.nackAsync(receivedMessage.subscription(), receivedMessage.ackId()); + pubsub.nackAsync(receivedMessage.getSubscription(), receivedMessage.getAckId()); } finally { - deadlineRenewer.remove(receivedMessage.subscription(), receivedMessage.ackId()); + deadlineRenewer.remove(receivedMessage.getSubscription(), receivedMessage.getAckId()); queuedCallbacks.decrementAndGet(); // We can now pull more messages, according to the next pull policy. pullIfNeeded(); @@ -184,8 +184,8 @@ private MessageConsumerImpl(Builder builder) { this.pubsubOptions = builder.pubsubOptions; this.subscription = builder.subscription; this.messageProcessor = builder.messageProcessor; - this.pubsubRpc = pubsubOptions.rpc(); - this.pubsub = pubsubOptions.service(); + this.pubsubRpc = pubsubOptions.getRpc(); + this.pubsub = pubsubOptions.getService(); this.deadlineRenewer = builder.deadlineRenewer; this.queuedCallbacks = new AtomicInteger(); this.consumerExecutor = SharedResourceHolder.get(CONSUMER_EXECUTOR); diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubException.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubException.java index 0ff6fa7e56c3..fa18d85e2eeb 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubException.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubException.java @@ -40,7 +40,7 @@ public PubSubException(ApiException apiException, boolean idempotent) { } @Override - protected Set retryableErrors() { + protected Set getRetryableErrors() { return null; } } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubImpl.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubImpl.java index f9ed0a1178b1..494bb3ff43a1 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubImpl.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubImpl.java @@ -112,14 +112,14 @@ public Policy apply(com.google.iam.v1.Policy policyPb) { PubSubImpl(PubSubOptions options) { super(options); - rpc = options.rpc(); + rpc = options.getRpc(); ackDeadlineRenewer = new AckDeadlineRenewer(this); } @VisibleForTesting PubSubImpl(PubSubOptions options, AckDeadlineRenewer ackDeadlineRenewer) { super(options); - rpc = options.rpc(); + rpc = options.getRpc(); this.ackDeadlineRenewer = ackDeadlineRenewer; } @@ -156,7 +156,13 @@ private static class TopicPageFetcher extends BasePageFetcher { } @Override + @Deprecated public Future> nextPage() { + return getNextPage(); + } + + @Override + public Future> getNextPage() { return listTopicsAsync(serviceOptions(), requestOptions()); } } @@ -171,7 +177,13 @@ private static class SubscriptionPageFetcher extends BasePageFetcher> nextPage() { + return getNextPage(); + } + + @Override + public Future> getNextPage() { return listSubscriptionsAsync(serviceOptions(), requestOptions()); } } @@ -189,7 +201,13 @@ private static class SubscriptionNamePageFetcher extends BasePageFetcher> nextPage() { + return getNextPage(); + } + + @Override + public Future> getNextPage() { return listSubscriptionsAsync(topic, serviceOptions(), requestOptions()); } } @@ -217,7 +235,8 @@ public Topic create(TopicInfo topic) { @Override public Future createAsync(TopicInfo topic) { - return transform(rpc.create(topic.toPb(options().projectId())), Topic.fromPbFunction(this)); + return transform(rpc.create(topic.toPb(getOptions().getProjectId())), + Topic.fromPbFunction(this)); } @Override @@ -228,7 +247,7 @@ public Topic getTopic(String topic) { @Override public Future getTopicAsync(String topic) { GetTopicRequest request = GetTopicRequest.newBuilder() - .setTopic(PublisherApi.formatTopicName(options().projectId(), topic)) + .setTopic(PublisherApi.formatTopicName(getOptions().getProjectId(), topic)) .build(); return transform(rpc.get(request), Topic.fromPbFunction(this)); } @@ -241,7 +260,7 @@ public boolean deleteTopic(String topic) { @Override public Future deleteTopicAsync(String topic) { DeleteTopicRequest request = DeleteTopicRequest.newBuilder() - .setTopic(PublisherApi.formatTopicName(options().projectId(), topic)) + .setTopic(PublisherApi.formatTopicName(getOptions().getProjectId(), topic)) .build(); return transform(rpc.delete(request), EMPTY_TO_BOOLEAN_FUNCTION); } @@ -249,7 +268,7 @@ public Future deleteTopicAsync(String topic) { private static ListTopicsRequest listTopicsRequest(PubSubOptions serviceOptions, Map options) { ListTopicsRequest.Builder builder = ListTopicsRequest.newBuilder(); - builder.setProject(SubscriberApi.formatProjectName(serviceOptions.projectId())); + builder.setProject(SubscriberApi.formatProjectName(serviceOptions.getProjectId())); Integer pageSize = PAGE_SIZE.get(options); String pageToken = PAGE_TOKEN.get(options); if (pageSize != null) { @@ -264,13 +283,13 @@ private static ListTopicsRequest listTopicsRequest(PubSubOptions serviceOptions, private static Future> listTopicsAsync(final PubSubOptions serviceOptions, final Map options) { final ListTopicsRequest request = listTopicsRequest(serviceOptions, options); - Future list = serviceOptions.rpc().list(request); + Future list = serviceOptions.getRpc().list(request); return transform(list, new Function>() { @Override public AsyncPage apply(ListTopicsResponse listTopicsResponse) { List topics = listTopicsResponse.getTopicsList() == null ? ImmutableList.of() : Lists.transform(listTopicsResponse.getTopicsList(), - Topic.fromPbFunction(serviceOptions.service())); + Topic.fromPbFunction(serviceOptions.getService())); String cursor = listTopicsResponse.getNextPageToken().equals("") ? null : listTopicsResponse.getNextPageToken(); return new AsyncPageImpl<>( @@ -286,7 +305,7 @@ public Page listTopics(ListOption... options) { @Override public Future> listTopicsAsync(ListOption... options) { - return listTopicsAsync(options(), optionMap(options)); + return listTopicsAsync(getOptions(), optionMap(options)); } @Override @@ -297,7 +316,7 @@ public String publish(String topic, Message message) { private static PublishRequest publishRequest(PubSubOptions serviceOptions, String topic, Iterable messages) { PublishRequest.Builder builder = PublishRequest.newBuilder(); - builder.setTopic(PublisherApi.formatTopicName(serviceOptions.projectId(), topic)); + builder.setTopic(PublisherApi.formatTopicName(serviceOptions.getProjectId(), topic)); builder.addAllMessages(Iterables.transform(messages, Message.TO_PB_FUNCTION)); return builder.build(); } @@ -305,7 +324,7 @@ private static PublishRequest publishRequest(PubSubOptions serviceOptions, Strin @Override public Future publishAsync(String topic, Message message) { return transform( - rpc.publish(publishRequest(options(), topic, Collections.singletonList(message))), + rpc.publish(publishRequest(getOptions(), topic, Collections.singletonList(message))), new Function() { @Override public String apply(PublishResponse publishResponse) { @@ -331,7 +350,7 @@ public List publish(String topic, Iterable messages) { @Override public Future> publishAsync(String topic, Iterable messages) { - return transform(rpc.publish(publishRequest(options(), topic, messages)), + return transform(rpc.publish(publishRequest(getOptions(), topic, messages)), new Function>() { @Override public List apply(PublishResponse publishResponse) { @@ -347,7 +366,7 @@ public Subscription create(SubscriptionInfo subscription) { @Override public Future createAsync(SubscriptionInfo subscription) { - return transform(rpc.create(subscription.toPb(options().projectId())), + return transform(rpc.create(subscription.toPb(getOptions().getProjectId())), Subscription.fromPbFunction(this)); } @@ -359,7 +378,8 @@ public Subscription getSubscription(String subscription) { @Override public Future getSubscriptionAsync(String subscription) { GetSubscriptionRequest request = GetSubscriptionRequest.newBuilder() - .setSubscription(SubscriberApi.formatSubscriptionName(options().projectId(), subscription)) + .setSubscription( + SubscriberApi.formatSubscriptionName(getOptions().getProjectId(), subscription)) .build(); return transform(rpc.get(request), Subscription.fromPbFunction(this)); } @@ -372,7 +392,8 @@ public void replacePushConfig(String subscription, PushConfig pushConfig) { @Override public Future replacePushConfigAsync(String subscription, PushConfig pushConfig) { ModifyPushConfigRequest request = ModifyPushConfigRequest.newBuilder() - .setSubscription(SubscriberApi.formatSubscriptionName(options().projectId(), subscription)) + .setSubscription( + SubscriberApi.formatSubscriptionName(getOptions().getProjectId(), subscription)) .setPushConfig(pushConfig != null ? pushConfig.toPb() : com.google.pubsub.v1.PushConfig.getDefaultInstance()) .build(); @@ -387,7 +408,8 @@ public boolean deleteSubscription(String subscription) { @Override public Future deleteSubscriptionAsync(String subscription) { DeleteSubscriptionRequest request = DeleteSubscriptionRequest.newBuilder() - .setSubscription(SubscriberApi.formatSubscriptionName(options().projectId(), subscription)) + .setSubscription( + SubscriberApi.formatSubscriptionName(getOptions().getProjectId(), subscription)) .build(); return transform(rpc.delete(request), EMPTY_TO_BOOLEAN_FUNCTION); } @@ -395,7 +417,7 @@ public Future deleteSubscriptionAsync(String subscription) { private static ListSubscriptionsRequest listSubscriptionsRequest(PubSubOptions serviceOptions, Map options) { ListSubscriptionsRequest.Builder builder = ListSubscriptionsRequest.newBuilder(); - builder.setProject(SubscriberApi.formatProjectName(serviceOptions.projectId())); + builder.setProject(SubscriberApi.formatProjectName(serviceOptions.getProjectId())); Integer pageSize = PAGE_SIZE.getInteger(options); String pageToken = PAGE_TOKEN.getString(options); if (pageSize != null) { @@ -410,14 +432,14 @@ private static ListSubscriptionsRequest listSubscriptionsRequest(PubSubOptions s private static Future> listSubscriptionsAsync( final PubSubOptions serviceOptions, final Map options) { final ListSubscriptionsRequest request = listSubscriptionsRequest(serviceOptions, options); - Future list = serviceOptions.rpc().list(request); + Future list = serviceOptions.getRpc().list(request); return transform(list, new Function>() { @Override public AsyncPage apply(ListSubscriptionsResponse listSubscriptionsResponse) { List subscriptions = listSubscriptionsResponse.getSubscriptionsList() == null ? ImmutableList.of() : Lists.transform(listSubscriptionsResponse.getSubscriptionsList(), - Subscription.fromPbFunction(serviceOptions.service())); + Subscription.fromPbFunction(serviceOptions.getService())); String cursor = listSubscriptionsResponse.getNextPageToken().equals("") ? null : listSubscriptionsResponse.getNextPageToken(); return new AsyncPageImpl<>(new SubscriptionPageFetcher(serviceOptions, cursor, options), @@ -432,13 +454,13 @@ public Page listSubscriptions(ListOption... options) { } public Future> listSubscriptionsAsync(ListOption... options) { - return listSubscriptionsAsync(options(), optionMap(options)); + return listSubscriptionsAsync(getOptions(), optionMap(options)); } private static ListTopicSubscriptionsRequest listSubscriptionsRequest(String topic, PubSubOptions serviceOptions, Map options) { ListTopicSubscriptionsRequest.Builder builder = ListTopicSubscriptionsRequest.newBuilder(); - builder.setTopic(PublisherApi.formatTopicName(serviceOptions.projectId(), topic)); + builder.setTopic(PublisherApi.formatTopicName(serviceOptions.getProjectId(), topic)); Integer pageSize = PAGE_SIZE.getInteger(options); String pageToken = PAGE_TOKEN.getString(options); if (pageSize != null) { @@ -454,7 +476,7 @@ private static Future> listSubscriptionsAsync(final St final PubSubOptions serviceOptions, final Map options) { final ListTopicSubscriptionsRequest request = listSubscriptionsRequest(topic, serviceOptions, options); - Future list = serviceOptions.rpc().list(request); + Future list = serviceOptions.getRpc().list(request); return transform(list, new Function>() { @Override @@ -487,7 +509,7 @@ public Page listSubscriptions(String topic, ListOption... option @Override public Future> listSubscriptionsAsync(String topic, ListOption... options) { - return listSubscriptionsAsync(topic, options(), optionMap(options)); + return listSubscriptionsAsync(topic, getOptions(), optionMap(options)); } @Override @@ -498,7 +520,8 @@ public Iterator pull(String subscription, int maxMessages) { @Override public Future> pullAsync(final String subscription, int maxMessages) { PullRequest request = PullRequest.newBuilder().setReturnImmediately(true) - .setSubscription(SubscriberApi.formatSubscriptionName(options().projectId(), subscription)) + .setSubscription( + SubscriberApi.formatSubscriptionName(getOptions().getProjectId(), subscription)) .setMaxMessages(maxMessages) .setReturnImmediately(true) .build(); @@ -536,7 +559,7 @@ public ReceivedMessage apply(com.google.pubsub.v1.ReceivedMessage receivedMessag public MessageConsumer pullAsync(String subscription, MessageProcessor callback, PullOption... options) { Map optionMap = optionMap(options); - return MessageConsumerImpl.builder(options(), subscription, ackDeadlineRenewer, callback) + return MessageConsumerImpl.builder(getOptions(), subscription, ackDeadlineRenewer, callback) .maxQueuedCallbacks(MAX_QUEUED_CALLBACKS.getInteger(optionMap)) .executorFactory(EXECUTOR_FACTORY.getExecutorFactory(optionMap)) .build(); @@ -560,7 +583,8 @@ public void ack(String subscription, Iterable ackIds) { @Override public Future ackAsync(String subscription, Iterable ackIds) { AcknowledgeRequest request = AcknowledgeRequest.newBuilder() - .setSubscription(SubscriberApi.formatSubscriptionName(options().projectId(), subscription)) + .setSubscription( + SubscriberApi.formatSubscriptionName(getOptions().getProjectId(), subscription)) .addAllAckIds(ackIds) .build(); return transform(rpc.acknowledge(request), EMPTY_TO_VOID_FUNCTION); @@ -608,7 +632,8 @@ public void modifyAckDeadline(String subscription, int deadline, TimeUnit unit, public Future modifyAckDeadlineAsync(String subscription, int deadline, TimeUnit unit, Iterable ackIds) { ModifyAckDeadlineRequest request = ModifyAckDeadlineRequest.newBuilder() - .setSubscription(SubscriberApi.formatSubscriptionName(options().projectId(), subscription)) + .setSubscription( + SubscriberApi.formatSubscriptionName(getOptions().getProjectId(), subscription)) .setAckDeadlineSeconds((int) TimeUnit.SECONDS.convert(deadline, unit)) .addAllAckIds(ackIds) .build(); @@ -622,7 +647,8 @@ public Policy getTopicPolicy(String topic) { @Override public Future getTopicPolicyAsync(String topic) { - return transform(rpc.getIamPolicy(PublisherApi.formatTopicName(options().projectId(), topic)), + return transform( + rpc.getIamPolicy(PublisherApi.formatTopicName(getOptions().getProjectId(), topic)), POLICY_TO_PB_FUNCTION); } @@ -635,7 +661,7 @@ public Policy replaceTopicPolicy(String topic, Policy newPolicy) { public Future replaceTopicPolicyAsync(String topic, Policy newPolicy) { SetIamPolicyRequest request = SetIamPolicyRequest.newBuilder() .setPolicy(PolicyMarshaller.INSTANCE.toPb(newPolicy)) - .setResource(PublisherApi.formatTopicName(options().projectId(), topic)) + .setResource(PublisherApi.formatTopicName(getOptions().getProjectId(), topic)) .build(); return transform(rpc.setIamPolicy(request), POLICY_TO_PB_FUNCTION); } @@ -648,7 +674,7 @@ public List testTopicPermissions(String topic, final List permi @Override public Future> testTopicPermissionsAsync(String topic, List permissions) { TestIamPermissionsRequest request = TestIamPermissionsRequest.newBuilder() - .setResource(PublisherApi.formatTopicName(options().projectId(), topic)) + .setResource(PublisherApi.formatTopicName(getOptions().getProjectId(), topic)) .addAllPermissions(permissions) .build(); return transform(rpc.testIamPermissions(request), permissionsFromPbFunction(permissions)); @@ -662,7 +688,8 @@ public Policy getSubscriptionPolicy(String subscription) { @Override public Future getSubscriptionPolicyAsync(String subscription) { return transform( - rpc.getIamPolicy(SubscriberApi.formatSubscriptionName(options().projectId(), subscription)), + rpc.getIamPolicy( + SubscriberApi.formatSubscriptionName(getOptions().getProjectId(), subscription)), POLICY_TO_PB_FUNCTION); } @@ -675,7 +702,8 @@ public Policy replaceSubscriptionPolicy(String subscription, Policy newPolicy) { public Future replaceSubscriptionPolicyAsync(String subscription, Policy newPolicy) { SetIamPolicyRequest request = SetIamPolicyRequest.newBuilder() .setPolicy(PolicyMarshaller.INSTANCE.toPb(newPolicy)) - .setResource(SubscriberApi.formatSubscriptionName(options().projectId(), subscription)) + .setResource( + SubscriberApi.formatSubscriptionName(getOptions().getProjectId(), subscription)) .build(); return transform(rpc.setIamPolicy(request), POLICY_TO_PB_FUNCTION); } @@ -689,7 +717,8 @@ public List testSubscriptionPermissions(String subscription, List> testSubscriptionPermissionsAsync(String subscription, List permissions) { TestIamPermissionsRequest request = TestIamPermissionsRequest.newBuilder() - .setResource(SubscriberApi.formatSubscriptionName(options().projectId(), subscription)) + .setResource( + SubscriberApi.formatSubscriptionName(getOptions().getProjectId(), subscription)) .addAllPermissions(permissions) .build(); return transform(rpc.testIamPermissions(request), permissionsFromPbFunction(permissions)); diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubOptions.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubOptions.java index e1693ee3cd38..760bd6b6b8b0 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubOptions.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/PubSubOptions.java @@ -48,8 +48,16 @@ public PubSub create(PubSubOptions options) { /** * Returns a default {@code PubSubOptions} instance. */ + @Deprecated public static PubSubOptions defaultInstance() { - return builder().build(); + return getDefaultInstance(); + } + + /** + * Returns a default {@code PubSubOptions} instance. + */ + public static PubSubOptions getDefaultInstance() { + return newBuilder().build(); } public static class DefaultPubSubRpcFactory implements PubSubRpcFactory { @@ -66,7 +74,7 @@ public PubSubRpc create(PubSubOptions options) { } @Override - protected String defaultHost() { + protected String getDefaultHost() { String host = System.getProperty(EMULATOR_HOST_ENV_VAR, System.getenv(EMULATOR_HOST_ENV_VAR)); return host != null ? host : DEFAULT_HOST; } @@ -91,22 +99,22 @@ protected PubSubOptions(Builder builder) { } @Override - protected ExecutorFactory executorFactory() { - return super.executorFactory(); + protected ExecutorFactory getExecutorFactory() { + return super.getExecutorFactory(); } @Override - protected PubSubFactory defaultServiceFactory() { + protected PubSubFactory getDefaultServiceFactory() { return DefaultPubSubFactory.INSTANCE; } @Override - protected PubSubRpcFactory defaultRpcFactory() { + protected PubSubRpcFactory getDefaultRpcFactory() { return DefaultPubSubRpcFactory.INSTANCE; } @Override - protected Set scopes() { + protected Set getScopes() { return SCOPES; } @@ -125,7 +133,12 @@ public Builder toBuilder() { return new Builder(this); } + @Deprecated public static Builder builder() { + return newBuilder(); + } + + public static Builder newBuilder() { return new Builder(); } } diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/ReceivedMessage.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/ReceivedMessage.java index 1ebfd6bdcab1..4afbef2e5a9b 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/ReceivedMessage.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/ReceivedMessage.java @@ -136,7 +136,7 @@ public ReceivedMessage build() { subscription = checkNotNull(builder.subscription); ackId = checkNotNull(builder.ackId); pubsub = checkNotNull(builder.pubsub); - options = pubsub.options(); + options = pubsub.getOptions(); } @Override @@ -285,7 +285,7 @@ public Future modifyAckDeadlineAsync(int deadline, TimeUnit unit) { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); - this.pubsub = options.service(); + this.pubsub = options.getService(); } static ReceivedMessage fromPb(PubSub pubsub, String subscription, diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Subscription.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Subscription.java index 0c847a23932b..85a270a5fcc0 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Subscription.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Subscription.java @@ -160,7 +160,7 @@ public Subscription build() { Subscription(PubSub pubsub, BuilderImpl builder) { super(builder); this.pubsub = checkNotNull(pubsub); - options = pubsub.options(); + options = pubsub.getOptions(); } @Override @@ -591,7 +591,7 @@ public Future> testPermissionsAsync(List permissions) { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); - this.pubsub = options.service(); + this.pubsub = options.getService(); } static Subscription fromPb(PubSub storage, com.google.pubsub.v1.Subscription subscriptionPb) { diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/SubscriptionInfo.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/SubscriptionInfo.java index 6c62b85772c0..5392789c546a 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/SubscriptionInfo.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/SubscriptionInfo.java @@ -83,14 +83,14 @@ public abstract static class Builder { /** * Sets the topic the subscription refers to, given the topic name. The topic is assumed to - * reside in the {@link PubSubOptions#projectId()} project. + * reside in the {@link PubSubOptions#getProjectId()} project. */ @Deprecated public abstract Builder topic(String topic); /** * Sets the topic the subscription refers to, given the topic name. The topic is assumed to - * reside in the {@link PubSubOptions#projectId()} project. + * reside in the {@link PubSubOptions#getProjectId()} project. */ public abstract Builder setTopic(String topic); @@ -108,7 +108,7 @@ public abstract static class Builder { /** * Sets the topic the subscription refers to, given the topic identity. If * {@code topic.project()} is {@code null} the topic is assumed to reside in the - * {@link PubSubOptions#projectId()} project. + * {@link PubSubOptions#getProjectId()} project. */ @Deprecated public abstract Builder topic(TopicId topic); @@ -116,7 +116,7 @@ public abstract static class Builder { /** * Sets the topic the subscription refers to, given the topic identity. If * {@code topic.project()} is {@code null} the topic is assumed to reside in the - * {@link PubSubOptions#projectId()} project. + * {@link PubSubOptions#getProjectId()} project. */ public abstract Builder setTopic(TopicId topic); @@ -270,9 +270,9 @@ public SubscriptionInfo build() { /** * Returns the identity of the topic this subscription refers to. If {@link TopicId#project()} is - * {@code null} the topic is assumed to reside in the {@link PubSubOptions#projectId()} project. - * After a topic is deleted, existing subscriptions to that topic are not deleted, but their topic - * field is set to {@link TopicId#deletedTopic()}. + * {@code null} the topic is assumed to reside in the {@link PubSubOptions#getProjectId()} + * project. After a topic is deleted, existing subscriptions to that topic are not deleted, but + * their topic field is set to {@link TopicId#deletedTopic()}. */ @Deprecated public TopicId topic() { @@ -281,9 +281,9 @@ public TopicId topic() { /** * Returns the identity of the topic this subscription refers to. If {@link TopicId#project()} is - * {@code null} the topic is assumed to reside in the {@link PubSubOptions#projectId()} project. - * After a topic is deleted, existing subscriptions to that topic are not deleted, but their topic - * field is set to {@link TopicId#deletedTopic()}. + * {@code null} the topic is assumed to reside in the {@link PubSubOptions#getProjectId()} + * project. After a topic is deleted, existing subscriptions to that topic are not deleted, but + * their topic field is set to {@link TopicId#deletedTopic()}. */ public TopicId getTopic() { return topic; @@ -423,7 +423,8 @@ public Builder toBuilder() { /** * Creates a pull {@code SubscriptionInfo} object given the name of the topic and the name of the - * subscription. The topic is assumed to reside in the {@link PubSubOptions#projectId()} project. + * subscription. The topic is assumed to reside in the {@link PubSubOptions#getProjectId()} + * project. * * @param topic the name of the topic the subscription refers to * @param name the name of the subscription. The name must start with a letter, and contain only @@ -439,7 +440,7 @@ public static SubscriptionInfo of(String topic, String name) { /** * Creates a pull {@code SubscriptionInfo} object given the identity of the topic and the name of * the subscription. If {@code topic.project()} is {@code null} the topic is assumed to reside in - * the {@link PubSubOptions#projectId()} project. + * the {@link PubSubOptions#getProjectId()} project. * * @param topic the identity of the topic the subscription refers to * @param name the name of the subscription. The name must start with a letter, and contain only @@ -455,7 +456,7 @@ public static SubscriptionInfo of(TopicId topic, String name) { /** * Creates a push {@code SubscriptionInfo} object given the name of the topic, the name of the * subscription and the push endpoint. The topic is assumed to reside in the - * {@link PubSubOptions#projectId()} project. + * {@link PubSubOptions#getProjectId()} project. * * @param topic the name of the topic the subscription refers to * @param name the name of the subscription. The name must start with a letter, and contain only @@ -473,7 +474,7 @@ public static SubscriptionInfo of(String topic, String name, String endpoint) { /** * Creates a push {@code SubscriptionInfo} object given the identity of the topic, the name of the * subscription and the push endpoint. If {@code topic.project()} is {@code null} the topic is - * assumed to reside in the {@link PubSubOptions#projectId()} project. + * assumed to reside in the {@link PubSubOptions#getProjectId()} project. * * @param topic the identity of the topic the subscription refers to * @param name the name of the subscription. The name must start with a letter, and contain only @@ -490,7 +491,7 @@ public static SubscriptionInfo of(TopicId topic, String name, String endpoint) { /** * Creates a builder for {@code SubscriptionInfo} objects given the name of the topic and the name - * of the subscription. The topic is assumed to reside in the {@link PubSubOptions#projectId()} + * of the subscription. The topic is assumed to reside in the {@link PubSubOptions#getProjectId()} * project. * * @param topic the name of the topic the subscription refers to @@ -507,7 +508,7 @@ public static Builder builder(String topic, String name) { /** * Creates a builder for {@code SubscriptionInfo} objects given the name of the topic and the name - * of the subscription. The topic is assumed to reside in the {@link PubSubOptions#projectId()} + * of the subscription. The topic is assumed to reside in the {@link PubSubOptions#getProjectId()} * project. * * @param topic the name of the topic the subscription refers to @@ -524,7 +525,7 @@ public static Builder newBuilder(String topic, String name) { /** * Creates a builder for {@code SubscriptionInfo} objects given the identity of the topic and the * name of the subscription. If {@code topic.project()} is {@code null} the topic is assumed to - * reside in the {@link PubSubOptions#projectId()} project. + * reside in the {@link PubSubOptions#getProjectId()} project. * * @param topic the identity of the topic the subscription refers to * @param name the name of the subscription. The name must start with a letter, and contain only @@ -541,7 +542,7 @@ public static Builder builder(TopicId topic, String name) { /** * Creates a builder for {@code SubscriptionInfo} objects given the identity of the topic and the * name of the subscription. If {@code topic.project()} is {@code null} the topic is assumed to - * reside in the {@link PubSubOptions#projectId()} project. + * reside in the {@link PubSubOptions#getProjectId()} project. * * @param topic the identity of the topic the subscription refers to * @param name the name of the subscription. The name must start with a letter, and contain only diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Topic.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Topic.java index fad88501059e..3a5a8dd7c58c 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Topic.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/Topic.java @@ -80,7 +80,7 @@ public Topic build() { Topic(PubSub pubsub, BuilderImpl builder) { super(builder); this.pubsub = checkNotNull(pubsub); - options = pubsub.options(); + options = pubsub.getOptions(); } @Override @@ -537,7 +537,7 @@ public Future> testPermissionsAsync(List permissions) { private void readObject(ObjectInputStream input) throws IOException, ClassNotFoundException { input.defaultReadObject(); - this.pubsub = options.service(); + this.pubsub = options.getService(); } static Topic fromPb(PubSub pubsub, com.google.pubsub.v1.Topic topicPb) { diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/TopicId.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/TopicId.java index f21810fe3dbc..8bc783c39e44 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/TopicId.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/TopicId.java @@ -52,7 +52,7 @@ private TopicId(String project, String topic) { /** * Returns the name of the project where the topic resides. If {@code null} the topic is assumed - * to reside in the {@link PubSubOptions#projectId()} project. + * to reside in the {@link PubSubOptions#getProjectId()} project. */ @Deprecated public String project() { @@ -61,7 +61,7 @@ public String project() { /** * Returns the name of the project where the topic resides. If {@code null} the topic is assumed - * to reside in the {@link PubSubOptions#projectId()} project. + * to reside in the {@link PubSubOptions#getProjectId()} project. */ public String getProject() { return project; diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/package-info.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/package-info.java index 7f3e6aae9b74..c98a5f5c8820 100644 --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/package-info.java +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/package-info.java @@ -23,7 +23,7 @@ * * CreateTopicAndPublishMessages.java. *

     {@code
    - * try (PubSub pubsub = PubSubOptions.defaultInstance().service()) {
    + * try (PubSub pubsub = PubSubOptions.getDefaultInstance().getService()) {
      *   Topic topic = pubsub.create(TopicInfo.of("test-topic"));
      *   Message message1 = Message.of("First message");
      *   Message message2 = Message.of("Second message");
    @@ -35,7 +35,7 @@
      * 
      * CreateSubscriptionAndPullMessages.java.
      * 
     {@code
    - * try (PubSub pubsub = PubSubOptions.defaultInstance().service()) {
    + * try (PubSub pubsub = PubSubOptions.getDefaultInstance().getService()) {
      *   Subscription subscription =
      *   pubsub.create(SubscriptionInfo.of("test-topic", "test-subscription"));
      *   MessageProcessor callback = new MessageProcessor() {
    diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/DefaultPubSubRpc.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/DefaultPubSubRpc.java
    index ec82f6d46822..255171d1c47f 100644
    --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/DefaultPubSubRpc.java
    +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/spi/DefaultPubSubRpc.java
    @@ -89,18 +89,18 @@ private InternalPubSubOptions(PubSubOptions options) {
         }
     
         @Override
    -    protected ExecutorFactory executorFactory() {
    -      return super.executorFactory();
    +    protected ExecutorFactory getExecutorFactory() {
    +      return super.getExecutorFactory();
         }
     
         @Override
    -    protected UnaryCallSettings.Builder apiCallSettings() {
    -      return super.apiCallSettings();
    +    protected UnaryCallSettings.Builder getApiCallSettings() {
    +      return super.getApiCallSettings();
         }
     
         @Override
    -    protected ConnectionSettings.Builder connectionSettings() {
    -      return super.connectionSettings();
    +    protected ConnectionSettings.Builder getConnectionSettings() {
    +      return super.getConnectionSettings();
         }
       }
     
    @@ -130,10 +130,10 @@ public void onFailure(Throwable error) {
     
       public DefaultPubSubRpc(PubSubOptions options) throws IOException {
         InternalPubSubOptions internalOptions = new InternalPubSubOptions(options);
    -    executorFactory = internalOptions.executorFactory();
    +    executorFactory = internalOptions.getExecutorFactory();
         executor = executorFactory.get();
    -    String libraryName = options.libraryName();
    -    String libraryVersion = firstNonNull(options.libraryVersion(), "");
    +    String libraryName = options.getLibraryName();
    +    String libraryVersion = firstNonNull(options.getLibraryVersion(), "");
         try {
           PublisherSettings.Builder pubBuilder = PublisherSettings.defaultBuilder()
               .provideExecutorWith(executor, false)
    @@ -142,19 +142,19 @@ public DefaultPubSubRpc(PubSubOptions options) throws IOException {
               .provideExecutorWith(executor, false)
               .setClientLibHeader(libraryName, libraryVersion);
           // todo(mziccard): PublisherSettings should support null/absent credentials for testing
    -      if (options.host().contains("localhost")
    -          || options.authCredentials().equals(AuthCredentials.noAuth())) {
    -        ManagedChannel channel = NettyChannelBuilder.forTarget(options.host())
    +      if (options.getHost().contains("localhost")
    +          || options.getAuthCredentials().equals(AuthCredentials.noAuth())) {
    +        ManagedChannel channel = NettyChannelBuilder.forTarget(options.getHost())
                 .negotiationType(NegotiationType.PLAINTEXT)
                 .build();
             pubBuilder.provideChannelWith(channel, true);
             subBuilder.provideChannelWith(channel, true);
           } else {
    -        ConnectionSettings connectionSettings = internalOptions.connectionSettings().build();
    +        ConnectionSettings connectionSettings = internalOptions.getConnectionSettings().build();
             pubBuilder.provideChannelWith(connectionSettings);
             subBuilder.provideChannelWith(connectionSettings);
           }
    -      UnaryCallSettings.Builder callSettingsBuilder = internalOptions.apiCallSettings();
    +      UnaryCallSettings.Builder callSettingsBuilder = internalOptions.getApiCallSettings();
           pubBuilder.applyToAllApiMethods(callSettingsBuilder);
           subBuilder.applyToAllApiMethods(callSettingsBuilder);
           publisherApi = PublisherApi.create(pubBuilder.build());
    diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java
    index a7978d9b4ee7..5715879291c2 100644
    --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java
    +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/LocalPubsubHelper.java
    @@ -155,11 +155,11 @@ public PubSubOptions options() {
        * localhost.
        */
       public PubSubOptions getOptions() {
    -    return PubSubOptions.builder()
    -        .projectId(projectId)
    -        .host("localhost:" + port)
    -        .authCredentials(AuthCredentials.noAuth())
    -        .retryParams(RetryParams.noRetries())
    +    return PubSubOptions.newBuilder()
    +        .setProjectId(projectId)
    +        .setHost("localhost:" + port)
    +        .setAuthCredentials(AuthCredentials.noAuth())
    +        .setRetryParams(RetryParams.noRetries())
             .build();
       }
     }
    diff --git a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/package-info.java b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/package-info.java
    index 63148437be2b..70c90a709b15 100644
    --- a/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/package-info.java
    +++ b/google-cloud-pubsub/src/main/java/com/google/cloud/pubsub/testing/package-info.java
    @@ -22,7 +22,7 @@
      * 
     {@code
      * LocalPubSubHelper helper = LocalPubSubHelper.create();
      * helper.start();
    - * PubSub localPubsub = helper.getOptions().service();
    + * PubSub localPubsub = helper.getOptions().getService();
      * } 
    * *

    After the test: diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/AckDeadlineRenewerTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/AckDeadlineRenewerTest.java index bf912e0a79f7..482cca2eb789 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/AckDeadlineRenewerTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/AckDeadlineRenewerTest.java @@ -55,10 +55,10 @@ public class AckDeadlineRenewerTest { @Before public void setUp() { pubsub = EasyMock.createStrictMock(PubSub.class); - PubSubOptions options = PubSubOptions.builder() - .projectId("projectId") + PubSubOptions options = PubSubOptions.newBuilder() + .setProjectId("projectId") .build(); - EasyMock.expect(pubsub.options()).andReturn(options); + EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.replay(pubsub); ackDeadlineRenewer = new AckDeadlineRenewer(pubsub); } @@ -246,11 +246,11 @@ public void testClose() throws Exception { ScheduledExecutorService executor = EasyMock.createStrictMock(ScheduledExecutorService.class); ExecutorFactory executorFactory = EasyMock.createStrictMock(ExecutorFactory.class); EasyMock.expect(executorFactory.get()).andReturn(executor); - PubSubOptions options = PubSubOptions.builder() - .projectId("projectId") - .executorFactory(executorFactory) + PubSubOptions options = PubSubOptions.newBuilder() + .setProjectId("projectId") + .setExecutorFactory(executorFactory) .build(); - EasyMock.expect(pubsub.options()).andReturn(options); + EasyMock.expect(pubsub.getOptions()).andReturn(options); executorFactory.release(executor); EasyMock.expectLastCall(); EasyMock.replay(executor, executorFactory, pubsub); @@ -269,11 +269,11 @@ public void testCloseWithMessage() throws Exception { ScheduledFuture future = EasyMock.createStrictMock(ScheduledFuture.class); EasyMock.expect(executor.schedule(EasyMock.anyObject(), EasyMock.anyLong(), EasyMock.eq(TimeUnit.MILLISECONDS))).andReturn(future); - PubSubOptions options = PubSubOptions.builder() - .projectId("projectId") - .executorFactory(executorFactory) + PubSubOptions options = PubSubOptions.newBuilder() + .setProjectId("projectId") + .setExecutorFactory(executorFactory) .build(); - EasyMock.expect(pubsub.options()).andReturn(options); + EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(future.cancel(true)).andReturn(true); executorFactory.release(executor); EasyMock.expectLastCall(); diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/BaseSystemTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/BaseSystemTest.java index 99fa0a902449..b30d7a0f8c7b 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/BaseSystemTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/BaseSystemTest.java @@ -218,7 +218,7 @@ public void testCreateGetAndDeleteSubscription() { pubsub().create(TopicInfo.of(topic)); String name = formatForTest("test-create-get-delete-subscription"); Subscription subscription = pubsub().create(SubscriptionInfo.of(topic, name)); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.getTopic()); + assertEquals(TopicId.of(pubsub().getOptions().getProjectId(), topic), subscription.getTopic()); assertEquals(name, subscription.getName()); assertNull(subscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 @@ -246,12 +246,12 @@ public void testCreateGetAndDeleteSubscriptionAsync() String topic = formatForTest("test-create-get-delete-async-subscription-topic"); pubsub().create(TopicInfo.of(topic)); String name = formatForTest("test-create-get-delete-async-subscription"); - String endpoint = "https://" + pubsub().options().projectId() + ".appspot.com/push"; + String endpoint = "https://" + pubsub().getOptions().getProjectId() + ".appspot.com/push"; PushConfig pushConfig = PushConfig.of(endpoint); Future subscriptionFuture = pubsub().createAsync( SubscriptionInfo.newBuilder(topic, name).setPushConfig(pushConfig).build()); Subscription subscription = subscriptionFuture.get(); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.getTopic()); + assertEquals(TopicId.of(pubsub().getOptions().getProjectId(), topic), subscription.getTopic()); assertEquals(name, subscription.getName()); assertEquals(pushConfig, subscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 @@ -270,7 +270,7 @@ public void testGetSubscriptionDeletedTopic() { pubsub().create(TopicInfo.of(topic)); String name = formatForTest("test-get-deleted-topic-subscription"); Subscription subscription = pubsub().create(SubscriptionInfo.of(topic, name)); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.getTopic()); + assertEquals(TopicId.of(pubsub().getOptions().getProjectId(), topic), subscription.getTopic()); assertEquals(name, subscription.getName()); assertNull(subscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 @@ -289,18 +289,19 @@ public void testReplaceSubscriptionPushConfig() { String topic = formatForTest("test-replace-push-config-topic"); pubsub().create(TopicInfo.of(topic)); String name = formatForTest("test-replace-push-config-subscription"); - String endpoint = "https://" + pubsub().options().projectId() + ".appspot.com/push"; + String endpoint = "https://" + pubsub().getOptions().getProjectId() + ".appspot.com/push"; PushConfig pushConfig = PushConfig.of(endpoint); Subscription subscription = pubsub().create(SubscriptionInfo.newBuilder(topic, name).setPushConfig(pushConfig).build()); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.getTopic()); + assertEquals(TopicId.of(pubsub().getOptions().getProjectId(), topic), subscription.getTopic()); assertEquals(name, subscription.getName()); assertEquals(pushConfig, subscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 // assertEquals(10, subscription.ackDeadlineSeconds()); pubsub().replacePushConfig(name, null); Subscription remoteSubscription = pubsub().getSubscription(name); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), remoteSubscription.getTopic()); + assertEquals(TopicId.of(pubsub().getOptions().getProjectId(), topic), + remoteSubscription.getTopic()); assertEquals(name, remoteSubscription.getName()); assertNull(remoteSubscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 @@ -325,16 +326,17 @@ public void testReplaceSubscriptionPushConfigAsync() Future subscriptionFuture = pubsub().createAsync(SubscriptionInfo.of(topic, name)); Subscription subscription = subscriptionFuture.get(); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), subscription.getTopic()); + assertEquals(TopicId.of(pubsub().getOptions().getProjectId(), topic), subscription.getTopic()); assertEquals(name, subscription.getName()); assertNull(subscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 // assertEquals(10, subscription.ackDeadlineSeconds()); - String endpoint = "https://" + pubsub().options().projectId() + ".appspot.com/push"; + String endpoint = "https://" + pubsub().getOptions().getProjectId() + ".appspot.com/push"; PushConfig pushConfig = PushConfig.of(endpoint); pubsub().replacePushConfigAsync(name, pushConfig).get(); Subscription remoteSubscription = pubsub().getSubscriptionAsync(name).get(); - assertEquals(TopicId.of(pubsub().options().projectId(), topic), remoteSubscription.getTopic()); + assertEquals(TopicId.of(pubsub().getOptions().getProjectId(), topic), + remoteSubscription.getTopic()); assertEquals(name, remoteSubscription.getName()); assertEquals(pushConfig, remoteSubscription.getPushConfig()); // todo(mziccard) seems not to work on the emulator (returns 60) - see #989 @@ -372,11 +374,11 @@ public void testListSubscriptions() { Set topicSubscriptionNames = Sets.newHashSet(); Page topic1Subscriptions = topic1.listSubscriptions(PubSub.ListOption.pageSize(1)); - Iterator firstStringPageIterator = topic1Subscriptions.values().iterator(); + Iterator firstStringPageIterator = topic1Subscriptions.getValues().iterator(); topicSubscriptionNames.add(firstStringPageIterator.next().getSubscription()); assertFalse(firstStringPageIterator.hasNext()); Iterator topicSubscriptionsIterator = - topic1Subscriptions.nextPage().iterateAll(); + topic1Subscriptions.getNextPage().iterateAll(); while (topicSubscriptionsIterator.hasNext()) { topicSubscriptionNames.add(topicSubscriptionsIterator.next().getSubscription()); } @@ -419,11 +421,11 @@ public void testListSubscriptionsAsync() throws ExecutionException, InterruptedE Set topicSubscriptionNames = Sets.newHashSet(); AsyncPage topic1Subscriptions = topic1.listSubscriptionsAsync(PubSub.ListOption.pageSize(1)).get(); - Iterator firstStringPageIterator = topic1Subscriptions.values().iterator(); + Iterator firstStringPageIterator = topic1Subscriptions.getValues().iterator(); topicSubscriptionNames.add(firstStringPageIterator.next().getSubscription()); assertFalse(firstStringPageIterator.hasNext()); Iterator topicSubscriptionsIterator = - topic1Subscriptions.nextPageAsync().get().iterateAll(); + topic1Subscriptions.getNextPageAsync().get().iterateAll(); while (topicSubscriptionsIterator.hasNext()) { topicSubscriptionNames.add(topicSubscriptionsIterator.next().getSubscription()); } diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/LocalSystemTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/LocalSystemTest.java index 60fd17342b56..391ad1e937c4 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/LocalSystemTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/LocalSystemTest.java @@ -42,7 +42,7 @@ protected String formatForTest(String resourceName) { public static void startServer() throws IOException, InterruptedException { pubsubHelper = LocalPubsubHelper.create(); pubsubHelper.start(); - pubsub = pubsubHelper.getOptions().service(); + pubsub = pubsubHelper.getOptions().getService(); } @AfterClass diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/MessageConsumerImplTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/MessageConsumerImplTest.java index 1a0d70b8150d..c0acf8199ce0 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/MessageConsumerImplTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/MessageConsumerImplTest.java @@ -148,10 +148,10 @@ public Void answer() throws Throwable { @Test public void testMessageConsumerAck() throws Exception { PullRequest request = pullRequest(MAX_QUEUED_CALLBACKS); - EasyMock.expect(options.rpc()).andReturn(pubsubRpc); - EasyMock.expect(options.service()).andReturn(pubsub); - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(pubsub.options()).andReturn(options).times(2); + EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); + EasyMock.expect(options.getService()).andReturn(pubsub); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(pubsub.getOptions()).andReturn(options).times(2); final CountDownLatch latch = new CountDownLatch(2); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID1)).andReturn(null); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID2)).andReturn(null); @@ -179,10 +179,10 @@ public void testMessageConsumerAck() throws Exception { @Test public void testMessageConsumerNack() throws Exception { PullRequest request = pullRequest(MAX_QUEUED_CALLBACKS); - EasyMock.expect(options.rpc()).andReturn(pubsubRpc); - EasyMock.expect(options.service()).andReturn(pubsub); - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(pubsub.options()).andReturn(options).times(2); + EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); + EasyMock.expect(options.getService()).andReturn(pubsub); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(pubsub.getOptions()).andReturn(options).times(2); final CountDownLatch latch = new CountDownLatch(2); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID1)).andReturn(null); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID2)).andReturn(null); @@ -217,12 +217,12 @@ public void testMessageConsumerMultipleCallsAck() throws Exception { final PullResponse response2 = PullResponse.newBuilder() .addReceivedMessages(MESSAGE2_PB) .build(); - EasyMock.expect(options.rpc()).andReturn(pubsubRpc); - EasyMock.expect(options.service()).andReturn(pubsub); - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); + EasyMock.expect(options.getService()).andReturn(pubsub); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); final CountDownLatch nextPullLatch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(2); - EasyMock.expect(pubsub.options()).andReturn(options); + EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID1)).andAnswer(new IAnswer>() { @Override public Future answer() throws Throwable { @@ -230,7 +230,7 @@ public Future answer() throws Throwable { return null; } }); - EasyMock.expect(pubsub.options()).andReturn(options); + EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID2)).andReturn(null); EasyMock.replay(pubsub); EasyMock.expect(pubsubRpc.pull(request1)).andReturn(new TestPullFuture(response1)); @@ -270,12 +270,12 @@ public void testMessageConsumerMultipleCallsNack() throws Exception { final PullResponse response2 = PullResponse.newBuilder() .addReceivedMessages(MESSAGE2_PB) .build(); - EasyMock.expect(options.rpc()).andReturn(pubsubRpc); - EasyMock.expect(options.service()).andReturn(pubsub); - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); + EasyMock.expect(options.getService()).andReturn(pubsub); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); final CountDownLatch nextPullLatch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(2); - EasyMock.expect(pubsub.options()).andReturn(options); + EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID1)).andAnswer(new IAnswer>() { @Override public Future answer() throws Throwable { @@ -283,7 +283,7 @@ public Future answer() throws Throwable { return null; } }); - EasyMock.expect(pubsub.options()).andReturn(options); + EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID2)).andReturn(null); EasyMock.replay(pubsub); EasyMock.expect(pubsubRpc.pull(request1)).andReturn(new TestPullFuture(response1)); @@ -320,10 +320,10 @@ public void testMessageConsumerMaxCallbacksAck() throws Exception { final PullResponse otherPullResponse = PullResponse.newBuilder() .addReceivedMessages(MESSAGE1_PB) .build(); - EasyMock.expect(options.rpc()).andReturn(pubsubRpc); - EasyMock.expect(options.service()).andReturn(pubsub); - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(pubsub.options()).andReturn(options).times(2); + EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); + EasyMock.expect(options.getService()).andReturn(pubsub); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(pubsub.getOptions()).andReturn(options).times(2); final CountDownLatch nextPullLatch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(3); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID1)).andReturn(null); @@ -334,7 +334,7 @@ public Future answer() throws Throwable { return null; } }); - EasyMock.expect(pubsub.options()).andReturn(options); + EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID1)).andReturn(null); EasyMock.replay(pubsub); EasyMock.expect(pubsubRpc.pull(request1)).andReturn(new TestPullFuture(PULL_RESPONSE)); @@ -375,10 +375,10 @@ public void testMessageConsumerMaxCallbacksNack() throws Exception { final PullResponse otherPullResponse = PullResponse.newBuilder() .addReceivedMessages(MESSAGE1_PB) .build(); - EasyMock.expect(options.rpc()).andReturn(pubsubRpc); - EasyMock.expect(options.service()).andReturn(pubsub); - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(pubsub.options()).andReturn(options).times(2); + EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); + EasyMock.expect(options.getService()).andReturn(pubsub); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(pubsub.getOptions()).andReturn(options).times(2); final CountDownLatch nextPullLatch = new CountDownLatch(1); final CountDownLatch latch = new CountDownLatch(3); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID1)).andReturn(null); @@ -389,7 +389,7 @@ public Future answer() throws Throwable { return null; } }); - EasyMock.expect(pubsub.options()).andReturn(options); + EasyMock.expect(pubsub.getOptions()).andReturn(options); EasyMock.expect(pubsub.nackAsync(SUBSCRIPTION, ACK_ID1)).andReturn(null); EasyMock.replay(pubsub); EasyMock.expect(pubsubRpc.pull(request1)).andReturn(new TestPullFuture(PULL_RESPONSE)); @@ -425,8 +425,8 @@ public PullFuture answer() throws Throwable { @Test public void testClose() throws Exception { - EasyMock.expect(options.rpc()).andReturn(pubsubRpc); - EasyMock.expect(options.service()).andReturn(pubsub); + EasyMock.expect(options.getRpc()).andReturn(pubsubRpc); + EasyMock.expect(options.getService()).andReturn(pubsub); final ExecutorService executor = EasyMock.createStrictMock(ExecutorService.class); executor.shutdown(); EasyMock.expectLastCall(); diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PubSubImplTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PubSubImplTest.java index dbf93c210bb0..8b5c32bbceae 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PubSubImplTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/PubSubImplTest.java @@ -127,7 +127,7 @@ public com.google.pubsub.v1.Topic apply(TopicInfo topicInfo) { .setMessage(MESSAGE2.toPb()) .setAckId("ackId2") .build(); - private static final Policy POLICY = Policy.builder() + private static final Policy POLICY = Policy.newBuilder() .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers()) .build(); private static final com.google.iam.v1.Policy POLICY_PB = PolicyMarshaller.INSTANCE.toPb(POLICY); @@ -170,9 +170,9 @@ public void setUp() { pubsubRpcMock = EasyMock.createStrictMock(PubSubRpc.class); renewerMock = EasyMock.createStrictMock(AckDeadlineRenewer.class); options = EasyMock.createMock(PubSubOptions.class); - EasyMock.expect(options.projectId()).andReturn(PROJECT).anyTimes(); - EasyMock.expect(options.rpc()).andReturn(pubsubRpcMock).anyTimes(); - EasyMock.expect(options.retryParams()).andReturn(RetryParams.noRetries()).anyTimes(); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).anyTimes(); + EasyMock.expect(options.getRpc()).andReturn(pubsubRpcMock).anyTimes(); + EasyMock.expect(options.getRetryParams()).andReturn(RetryParams.noRetries()).anyTimes(); EasyMock.replay(rpcFactoryMock, pubsubRpcMock, renewerMock, options); EasyMock.reset(pubsubRpcMock, renewerMock); } @@ -184,9 +184,9 @@ public void tearDown() { private void resetOptionsForList(int pageCount) { EasyMock.reset(options); - EasyMock.expect(options.projectId()).andReturn(PROJECT).times(pageCount); - EasyMock.expect(options.rpc()).andReturn(pubsubRpcMock).times(pageCount); - EasyMock.expect(options.service()).andReturn(pubsub).times(pageCount); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT).times(pageCount); + EasyMock.expect(options.getRpc()).andReturn(pubsubRpcMock).times(pageCount); + EasyMock.expect(options.getService()).andReturn(pubsub).times(pageCount); EasyMock.replay(options); } @@ -194,7 +194,7 @@ private void resetOptionsForList(int pageCount) { public void testGetOptions() { EasyMock.replay(pubsubRpcMock, renewerMock); pubsub = new PubSubImpl(options, renewerMock); - assertSame(options, pubsub.options()); + assertSame(options, pubsub.getOptions()); } @Test @@ -320,8 +320,8 @@ public void testListTopics() { EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); Page page = pubsub.listTopics(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(topicList.toArray(), Iterables.toArray(page.values(), Topic.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(topicList.toArray(), Iterables.toArray(page.getValues(), Topic.class)); } @Test @@ -354,11 +354,11 @@ public void testListTopicsNextPage() { EasyMock.expect(pubsubRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(pubsubRpcMock, renewerMock); Page page = pubsub.listTopics(); - assertEquals(cursor1, page.nextPageCursor()); - assertArrayEquals(topicList1.toArray(), Iterables.toArray(page.values(), Topic.class)); - page = page.nextPage(); - assertEquals(cursor2, page.nextPageCursor()); - assertArrayEquals(topicList2.toArray(), Iterables.toArray(page.values(), Topic.class)); + assertEquals(cursor1, page.getNextPageCursor()); + assertArrayEquals(topicList1.toArray(), Iterables.toArray(page.getValues(), Topic.class)); + page = page.getNextPage(); + assertEquals(cursor2, page.getNextPageCursor()); + assertArrayEquals(topicList2.toArray(), Iterables.toArray(page.getValues(), Topic.class)); } @Test @@ -375,8 +375,8 @@ public void testListTopicsEmpty() { EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); Page page = pubsub.listTopics(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); assertArrayEquals(topicList.toArray(), Iterators.toArray(page.iterateAll(), Topic.class)); } @@ -401,9 +401,9 @@ public void testListTopicsWithOptions() { EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); Page page = pubsub.listTopics(ListOption.pageSize(42), ListOption.pageToken(cursor)); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); - assertArrayEquals(topicList.toArray(), Iterables.toArray(page.values(), Topic.class)); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); + assertArrayEquals(topicList.toArray(), Iterables.toArray(page.getValues(), Topic.class)); } @Test @@ -423,8 +423,8 @@ public void testListTopicsAsync() throws ExecutionException, InterruptedExceptio EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); AsyncPage page = pubsub.listTopicsAsync().get(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(topicList.toArray(), Iterables.toArray(page.values(), Topic.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(topicList.toArray(), Iterables.toArray(page.getValues(), Topic.class)); } @Test @@ -457,11 +457,11 @@ public void testListTopicsAsyncNextPage() throws ExecutionException, Interrupted EasyMock.expect(pubsubRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(pubsubRpcMock, renewerMock); AsyncPage page = pubsub.listTopicsAsync().get(); - assertEquals(cursor1, page.nextPageCursor()); - assertArrayEquals(topicList1.toArray(), Iterables.toArray(page.values(), Topic.class)); - page = page.nextPageAsync().get(); - assertEquals(cursor2, page.nextPageCursor()); - assertArrayEquals(topicList2.toArray(), Iterables.toArray(page.values(), Topic.class)); + assertEquals(cursor1, page.getNextPageCursor()); + assertArrayEquals(topicList1.toArray(), Iterables.toArray(page.getValues(), Topic.class)); + page = page.getNextPageAsync().get(); + assertEquals(cursor2, page.getNextPageCursor()); + assertArrayEquals(topicList2.toArray(), Iterables.toArray(page.getValues(), Topic.class)); } @Test @@ -478,9 +478,9 @@ public void testListTopicsAsyncEmpty() throws ExecutionException, InterruptedExc EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); AsyncPage page = pubsub.listTopicsAsync().get(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPageAsync().get()); - assertNull(page.nextPage()); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPageAsync().get()); + assertNull(page.getNextPage()); assertArrayEquals(topicList.toArray(), Iterators.toArray(page.iterateAll(), Topic.class)); } @@ -506,9 +506,9 @@ public void testListTopicsAsyncWithOptions() throws ExecutionException, Interrup EasyMock.replay(pubsubRpcMock, renewerMock); AsyncPage page = pubsub.listTopicsAsync(ListOption.pageSize(42), ListOption.pageToken(cursor)).get(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPageAsync().get()); - assertArrayEquals(topicList.toArray(), Iterables.toArray(page.values(), Topic.class)); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPageAsync().get()); + assertArrayEquals(topicList.toArray(), Iterables.toArray(page.getValues(), Topic.class)); } @Test @@ -808,9 +808,9 @@ public void testListSubscriptions() { EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); Page page = pubsub.listSubscriptions(); - assertEquals(cursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); assertArrayEquals(subscriptionList.toArray(), - Iterables.toArray(page.values(), Subscription.class)); + Iterables.toArray(page.getValues(), Subscription.class)); } @Test @@ -845,13 +845,13 @@ public void testListSubscriptionsNextPage() { EasyMock.expect(pubsubRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(pubsubRpcMock, renewerMock); Page page = pubsub.listSubscriptions(); - assertEquals(cursor1, page.nextPageCursor()); + assertEquals(cursor1, page.getNextPageCursor()); assertArrayEquals(subscriptionList1.toArray(), - Iterables.toArray(page.values(), Subscription.class)); - page = page.nextPage(); - assertEquals(cursor2, page.nextPageCursor()); + Iterables.toArray(page.getValues(), Subscription.class)); + page = page.getNextPage(); + assertEquals(cursor2, page.getNextPageCursor()); assertArrayEquals(subscriptionList2.toArray(), - Iterables.toArray(page.values(), Subscription.class)); + Iterables.toArray(page.getValues(), Subscription.class)); } @Test @@ -870,10 +870,10 @@ public void testListSubscriptionsEmpty() { EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); Page page = pubsub.listSubscriptions(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); assertArrayEquals(subscriptionList.toArray(), - Iterables.toArray(page.values(), Subscription.class)); + Iterables.toArray(page.getValues(), Subscription.class)); } @Test @@ -898,10 +898,10 @@ public void testListSubscriptionsWithOptions() { EasyMock.replay(pubsubRpcMock, renewerMock); Page page = pubsub.listSubscriptions(ListOption.pageSize(42), ListOption.pageToken(cursor)); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); assertArrayEquals(subscriptionList.toArray(), - Iterables.toArray(page.values(), Subscription.class)); + Iterables.toArray(page.getValues(), Subscription.class)); } @Test @@ -923,9 +923,9 @@ public void testListSubscriptionsAsync() throws ExecutionException, InterruptedE EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); AsyncPage page = pubsub.listSubscriptionsAsync().get(); - assertEquals(cursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); assertArrayEquals(subscriptionList.toArray(), - Iterables.toArray(page.values(), Subscription.class)); + Iterables.toArray(page.getValues(), Subscription.class)); } @Test @@ -960,13 +960,13 @@ public void testListSubscriptionsAsyncNextPage() throws ExecutionException, Inte EasyMock.expect(pubsubRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(pubsubRpcMock, renewerMock); AsyncPage page = pubsub.listSubscriptionsAsync().get(); - assertEquals(cursor1, page.nextPageCursor()); + assertEquals(cursor1, page.getNextPageCursor()); assertArrayEquals(subscriptionList1.toArray(), - Iterables.toArray(page.values(), Subscription.class)); - page = page.nextPageAsync().get(); - assertEquals(cursor2, page.nextPageCursor()); + Iterables.toArray(page.getValues(), Subscription.class)); + page = page.getNextPageAsync().get(); + assertEquals(cursor2, page.getNextPageCursor()); assertArrayEquals(subscriptionList2.toArray(), - Iterables.toArray(page.values(), Subscription.class)); + Iterables.toArray(page.getValues(), Subscription.class)); } @Test @@ -985,11 +985,11 @@ public void testListSubscriptionsAsyncEmpty() throws ExecutionException, Interru EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); AsyncPage page = pubsub.listSubscriptionsAsync().get(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPageAsync().get()); - assertNull(page.nextPage()); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPageAsync().get()); + assertNull(page.getNextPage()); assertArrayEquals(subscriptionList.toArray(), - Iterables.toArray(page.values(), Subscription.class)); + Iterables.toArray(page.getValues(), Subscription.class)); } @Test @@ -1015,11 +1015,11 @@ public void testListSubscriptionsAsyncWithOptions() EasyMock.replay(pubsubRpcMock, renewerMock); AsyncPage page = pubsub.listSubscriptionsAsync(ListOption.pageSize(42), ListOption.pageToken(cursor)).get(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); - assertNull(page.nextPageAsync().get()); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); + assertNull(page.getNextPageAsync().get()); assertArrayEquals(subscriptionList.toArray(), - Iterables.toArray(page.values(), Subscription.class)); + Iterables.toArray(page.getValues(), Subscription.class)); } @Test @@ -1041,9 +1041,9 @@ public void testListTopicSubscriptions() { EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); Page page = pubsub.listSubscriptions(TOPIC); - assertEquals(cursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); assertArrayEquals(subscriptionList.toArray(), - Iterables.toArray(page.values(), SubscriptionId.class)); + Iterables.toArray(page.getValues(), SubscriptionId.class)); } @Test @@ -1079,13 +1079,13 @@ public void testListTopicSubscriptionsNextPage() { EasyMock.expect(pubsubRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(pubsubRpcMock, renewerMock); Page page = pubsub.listSubscriptions(TOPIC); - assertEquals(cursor1, page.nextPageCursor()); + assertEquals(cursor1, page.getNextPageCursor()); assertArrayEquals(subscriptionList1.toArray(), - Iterables.toArray(page.values(), SubscriptionId.class)); - page = page.nextPage(); - assertEquals(cursor2, page.nextPageCursor()); + Iterables.toArray(page.getValues(), SubscriptionId.class)); + page = page.getNextPage(); + assertEquals(cursor2, page.getNextPageCursor()); assertArrayEquals(subscriptionList2.toArray(), - Iterables.toArray(page.values(), SubscriptionId.class)); + Iterables.toArray(page.getValues(), SubscriptionId.class)); } @Test @@ -1104,10 +1104,10 @@ public void testListTopicSubscriptionsEmpty() { EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); Page page = pubsub.listSubscriptions(TOPIC); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); assertArrayEquals(subscriptionList.toArray(), - Iterables.toArray(page.values(), SubscriptionId.class)); + Iterables.toArray(page.getValues(), SubscriptionId.class)); } @Test @@ -1132,10 +1132,10 @@ public void testListTopicSubscriptionsWithOptions() { EasyMock.replay(pubsubRpcMock, renewerMock); Page page = pubsub.listSubscriptions(TOPIC, ListOption.pageSize(42), ListOption.pageToken(cursor)); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); assertArrayEquals(subscriptionList.toArray(), - Iterables.toArray(page.values(), SubscriptionId.class)); + Iterables.toArray(page.getValues(), SubscriptionId.class)); } @Test @@ -1157,9 +1157,9 @@ public void testListTopicSubscriptionsAsync() throws ExecutionException, Interru EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); AsyncPage page = pubsub.listSubscriptionsAsync(TOPIC).get(); - assertEquals(cursor, page.nextPageCursor()); + assertEquals(cursor, page.getNextPageCursor()); assertArrayEquals(subscriptionList.toArray(), - Iterables.toArray(page.values(), SubscriptionId.class)); + Iterables.toArray(page.getValues(), SubscriptionId.class)); } @Test @@ -1196,13 +1196,13 @@ public void testListTopicSubscriptionsAsyncNextPage() EasyMock.expect(pubsubRpcMock.list(request2)).andReturn(futureResponse2); EasyMock.replay(pubsubRpcMock, renewerMock); AsyncPage page = pubsub.listSubscriptionsAsync(TOPIC).get(); - assertEquals(cursor1, page.nextPageCursor()); + assertEquals(cursor1, page.getNextPageCursor()); assertArrayEquals(subscriptionList1.toArray(), - Iterables.toArray(page.values(), SubscriptionId.class)); - page = page.nextPageAsync().get(); - assertEquals(cursor2, page.nextPageCursor()); + Iterables.toArray(page.getValues(), SubscriptionId.class)); + page = page.getNextPageAsync().get(); + assertEquals(cursor2, page.getNextPageCursor()); assertArrayEquals(subscriptionList2.toArray(), - Iterables.toArray(page.values(), SubscriptionId.class)); + Iterables.toArray(page.getValues(), SubscriptionId.class)); } @Test @@ -1222,11 +1222,11 @@ public void testListTopicSubscriptionsAsyncEmpty() EasyMock.expect(pubsubRpcMock.list(request)).andReturn(futureResponse); EasyMock.replay(pubsubRpcMock, renewerMock); AsyncPage page = pubsub.listSubscriptionsAsync(TOPIC).get(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); - assertNull(page.nextPageAsync().get()); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); + assertNull(page.getNextPageAsync().get()); assertArrayEquals(subscriptionList.toArray(), - Iterables.toArray(page.values(), SubscriptionId.class)); + Iterables.toArray(page.getValues(), SubscriptionId.class)); } @Test @@ -1252,11 +1252,11 @@ public void testListTopicSubscriptionsAsyncWithOptions() EasyMock.replay(pubsubRpcMock, renewerMock); AsyncPage page = pubsub.listSubscriptionsAsync( TOPIC, ListOption.pageSize(42), ListOption.pageToken(cursor)).get(); - assertNull(page.nextPageCursor()); - assertNull(page.nextPage()); - assertNull(page.nextPageAsync().get()); + assertNull(page.getNextPageCursor()); + assertNull(page.getNextPage()); + assertNull(page.getNextPageAsync().get()); assertArrayEquals(subscriptionList.toArray(), - Iterables.toArray(page.values(), SubscriptionId.class)); + Iterables.toArray(page.getValues(), SubscriptionId.class)); } @Test @@ -1385,9 +1385,9 @@ public void testPullMessagesAsyncError() throws ExecutionException, InterruptedE public void testMessageConsumer() throws Exception { pubsub = new PubSubImpl(options, renewerMock); EasyMock.reset(options); - EasyMock.expect(options.service()).andReturn(pubsub); - EasyMock.expect(options.rpc()).andReturn(pubsubRpcMock); - EasyMock.expect(options.projectId()).andReturn(PROJECT); + EasyMock.expect(options.getService()).andReturn(pubsub); + EasyMock.expect(options.getRpc()).andReturn(pubsubRpcMock); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT); EasyMock.replay(options); PullRequest request = PullRequest.newBuilder() .setSubscription(SUBSCRIPTION_NAME_PB) @@ -1413,9 +1413,9 @@ public PullFuture answer() throws Throwable { public void testMessageConsumerWithOptions() throws Exception { pubsub = new PubSubImpl(options, renewerMock); EasyMock.reset(options); - EasyMock.expect(options.service()).andReturn(pubsub); - EasyMock.expect(options.rpc()).andReturn(pubsubRpcMock); - EasyMock.expect(options.projectId()).andReturn(PROJECT); + EasyMock.expect(options.getService()).andReturn(pubsub); + EasyMock.expect(options.getRpc()).andReturn(pubsubRpcMock); + EasyMock.expect(options.getProjectId()).andReturn(PROJECT); EasyMock.replay(options); ExecutorFactory executorFactoryMock = EasyMock.createStrictMock(ExecutorFactory.class); ExecutorService executorServiceMock = EasyMock.createStrictMock(ExecutorService.class); diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/ReceivedMessageTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/ReceivedMessageTest.java index dd2bd636d088..c740063c533b 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/ReceivedMessageTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/ReceivedMessageTest.java @@ -69,7 +69,7 @@ public class ReceivedMessageTest { private ReceivedMessage message; private void initializeExpectedMessage(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); pubsub = createStrictMock(PubSub.class); expectedMessage = @@ -167,7 +167,7 @@ public void testToBuilder() { @Test public void testAck() { initializeExpectedMessage(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); pubsub.ack(SUBSCRIPTION, ACK_ID); EasyMock.expectLastCall(); replay(pubsub); @@ -178,7 +178,7 @@ public void testAck() { @Test public void testAckAsync() throws ExecutionException, InterruptedException { initializeExpectedMessage(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.ackAsync(SUBSCRIPTION, ACK_ID)).andReturn(Futures.immediateFuture(null)); EasyMock.expectLastCall(); replay(pubsub); @@ -189,7 +189,7 @@ public void testAckAsync() throws ExecutionException, InterruptedException { @Test public void testModifyAckDeadline() { initializeExpectedMessage(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); pubsub.modifyAckDeadline(SUBSCRIPTION, 10, TimeUnit.SECONDS, ACK_ID); EasyMock.expectLastCall(); replay(pubsub); @@ -200,7 +200,7 @@ public void testModifyAckDeadline() { @Test public void testModifyAckDeadlineAsync() throws ExecutionException, InterruptedException { initializeExpectedMessage(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.modifyAckDeadlineAsync(SUBSCRIPTION, 10, TimeUnit.SECONDS, ACK_ID)) .andReturn(Futures.immediateFuture(null)); EasyMock.expectLastCall(); diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SerializationTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SerializationTest.java index 8201f0d6413c..74f38fcebc9b 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SerializationTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SerializationTest.java @@ -28,11 +28,11 @@ public class SerializationTest extends BaseSerializationTest { - private static final PubSub PUB_SUB = PubSubOptions.builder() - .projectId("p") - .authCredentials(AuthCredentials.noAuth()) - .host("localhost") - .build().service(); + private static final PubSub PUB_SUB = PubSubOptions.newBuilder() + .setProjectId("p") + .setAuthCredentials(AuthCredentials.noAuth()) + .setHost("localhost") + .build().getService(); private static final Message MESSAGE = Message.of("payload"); private static final com.google.pubsub.v1.ReceivedMessage RECEIVED_MESSAGE_PB = com.google.pubsub.v1.ReceivedMessage.newBuilder() @@ -82,13 +82,13 @@ public int hashCode() { @Override protected Serializable[] serializableObjects() { - PubSubOptions options = PubSubOptions.builder() - .projectId("p1") - .initialTimeout(1234) + PubSubOptions options = PubSubOptions.newBuilder() + .setProjectId("p1") + .setInitialTimeout(1234) .build(); PubSubOptions otherOptions = options.toBuilder() - .projectId("p2") - .executorFactory(new TestExecutorFactory()) + .setProjectId("p2") + .setExecutorFactory(new TestExecutorFactory()) .build(); return new Serializable[]{options, otherOptions, MESSAGE, RECEIVED_MESSAGE, SUBSCRIPTION_INFO, SUBSCRIPTION, SUBSCRIPTION_ID, TOPIC_INFO, TOPIC, PAGE_TOKEN_OPTION, PAGE_SIZE_OPTION, diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionTest.java index 6baffd5826c8..0e6ac4cc2b61 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/SubscriptionTest.java @@ -68,7 +68,7 @@ public class SubscriptionTest { .setMessage(MESSAGE2.toPb()) .setAckId("ackId2") .build(); - private static final Policy POLICY = Policy.builder() + private static final Policy POLICY = Policy.newBuilder() .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers()) .build(); @@ -79,7 +79,7 @@ public class SubscriptionTest { private Subscription subscription; private void initializeExpectedSubscription(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); pubsub = createStrictMock(PubSub.class); expectedSubscription = new Subscription(serviceMockReturnsOptions, @@ -150,7 +150,7 @@ public void testReload() { SubscriptionInfo updatedInfo = SUBSCRIPTION_INFO.toBuilder().setName("newSubscription").build(); Subscription expectedSubscription = new Subscription(serviceMockReturnsOptions, new SubscriptionInfo.BuilderImpl(updatedInfo)); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getSubscription(NAME)).andReturn(expectedSubscription); replay(pubsub); initializeSubscription(); @@ -161,7 +161,7 @@ public void testReload() { @Test public void testReloadNull() { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getSubscription(NAME)).andReturn(null); replay(pubsub); initializeSubscription(); @@ -174,7 +174,7 @@ public void testReloadAsync() throws ExecutionException, InterruptedException { SubscriptionInfo updatedInfo = SUBSCRIPTION_INFO.toBuilder().setName("newSubscription").build(); Subscription expectedSubscription = new Subscription(serviceMockReturnsOptions, new SubscriptionInfo.BuilderImpl(updatedInfo)); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getSubscriptionAsync(NAME)) .andReturn(Futures.immediateFuture(expectedSubscription)); replay(pubsub); @@ -186,7 +186,7 @@ public void testReloadAsync() throws ExecutionException, InterruptedException { @Test public void testReloadAsyncNull() throws ExecutionException, InterruptedException { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getSubscriptionAsync(NAME)) .andReturn(Futures.immediateFuture(null)); replay(pubsub); @@ -197,7 +197,7 @@ public void testReloadAsyncNull() throws ExecutionException, InterruptedExceptio @Test public void testDeleteTrue() { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.deleteSubscription(NAME)).andReturn(true); replay(pubsub); initializeSubscription(); @@ -207,7 +207,7 @@ public void testDeleteTrue() { @Test public void testDeleteFalse() { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.deleteSubscription(NAME)).andReturn(false); replay(pubsub); initializeSubscription(); @@ -217,7 +217,7 @@ public void testDeleteFalse() { @Test public void testDeleteAsyncTrue() throws ExecutionException, InterruptedException { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.deleteSubscriptionAsync(NAME)) .andReturn(Futures.immediateFuture(true)); replay(pubsub); @@ -228,7 +228,7 @@ public void testDeleteAsyncTrue() throws ExecutionException, InterruptedExceptio @Test public void testDeleteAsyncFalse() throws ExecutionException, InterruptedException { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.deleteSubscriptionAsync(NAME)) .andReturn(Futures.immediateFuture(false)); replay(pubsub); @@ -239,7 +239,7 @@ public void testDeleteAsyncFalse() throws ExecutionException, InterruptedExcepti @Test public void testReplacePushConfig() { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); PushConfig pushConfig = PushConfig.of("https://example.com/newPush"); pubsub.replacePushConfig(NAME, pushConfig); EasyMock.expectLastCall(); @@ -251,7 +251,7 @@ public void testReplacePushConfig() { @Test public void testReplacePushConfig_Null() { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); pubsub.replacePushConfig(NAME, null); EasyMock.expectLastCall(); replay(pubsub); @@ -262,7 +262,7 @@ public void testReplacePushConfig_Null() { @Test public void testReplacePushConfig_Async() throws ExecutionException, InterruptedException { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); PushConfig pushConfig = PushConfig.of("https://example.com/newPush"); expect(pubsub.replacePushConfigAsync(NAME, pushConfig)) .andReturn(Futures.immediateFuture(null)); @@ -275,7 +275,7 @@ public void testReplacePushConfig_Async() throws ExecutionException, Interrupted @Test public void testReplacePushConfigAsync_Null() throws ExecutionException, InterruptedException { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.replacePushConfigAsync(NAME, null)) .andReturn(Futures.immediateFuture(null)); replay(pubsub); @@ -286,12 +286,12 @@ public void testReplacePushConfigAsync_Null() throws ExecutionException, Interru @Test public void testPull() { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions).times(2); + expect(pubsub.getOptions()).andReturn(mockOptions).times(2); replay(pubsub); ReceivedMessage message1 = ReceivedMessage.fromPb(pubsub, NAME, MESSAGE_PB1); ReceivedMessage message2 = ReceivedMessage.fromPb(pubsub, NAME, MESSAGE_PB2); reset(pubsub); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); List messages = ImmutableList.of(message1, message2); expect(pubsub.pull(NAME, 42)).andReturn(messages.iterator()); replay(pubsub); @@ -302,12 +302,12 @@ public void testPull() { @Test public void testPullAsync() throws ExecutionException, InterruptedException { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions).times(2); + expect(pubsub.getOptions()).andReturn(mockOptions).times(2); replay(pubsub); ReceivedMessage message1 = ReceivedMessage.fromPb(pubsub, NAME, MESSAGE_PB1); ReceivedMessage message2 = ReceivedMessage.fromPb(pubsub, NAME, MESSAGE_PB2); reset(pubsub); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); List messages = ImmutableList.of(message1, message2); expect(pubsub.pullAsync(NAME, 42)).andReturn(Futures.immediateFuture(messages.iterator())); replay(pubsub); @@ -321,7 +321,7 @@ public void testMessageConsumer() throws ExecutionException, InterruptedExceptio MessageConsumer messageConsumer = createStrictMock(MessageConsumer.class); MessageProcessor messageProcessor = createStrictMock(MessageProcessor.class); replay(messageConsumer, messageProcessor); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.pullAsync(NAME, messageProcessor)).andReturn(messageConsumer); replay(pubsub); initializeSubscription(); @@ -335,7 +335,7 @@ public void testMessageConsumerWithOptions() throws ExecutionException, Interrup MessageConsumer messageConsumer = createStrictMock(MessageConsumer.class); MessageProcessor messageProcessor = createStrictMock(MessageProcessor.class); replay(messageConsumer, messageProcessor); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.pullAsync(NAME, messageProcessor, PullOption.maxQueuedCallbacks(2))) .andReturn(messageConsumer); replay(pubsub); @@ -348,7 +348,7 @@ public void testMessageConsumerWithOptions() throws ExecutionException, Interrup @Test public void testGetPolicy() { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getSubscriptionPolicy(NAME)).andReturn(POLICY); replay(pubsub); initializeSubscription(); @@ -359,7 +359,7 @@ public void testGetPolicy() { @Test public void testGetPolicyNull() { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getSubscriptionPolicy(NAME)).andReturn(null); replay(pubsub); initializeSubscription(); @@ -369,7 +369,7 @@ public void testGetPolicyNull() { @Test public void testGetPolicyAsync() throws ExecutionException, InterruptedException { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getSubscriptionPolicyAsync(NAME)).andReturn(Futures.immediateFuture(POLICY)); replay(pubsub); initializeSubscription(); @@ -380,7 +380,7 @@ public void testGetPolicyAsync() throws ExecutionException, InterruptedException @Test public void testReplacePolicy() { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.replaceSubscriptionPolicy(NAME, POLICY)).andReturn(POLICY); replay(pubsub); initializeSubscription(); @@ -391,7 +391,7 @@ public void testReplacePolicy() { @Test public void testReplacePolicyAsync() throws ExecutionException, InterruptedException { initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.replaceSubscriptionPolicyAsync(NAME, POLICY)) .andReturn(Futures.immediateFuture(POLICY)); replay(pubsub); @@ -405,7 +405,7 @@ public void testTestPermissions() { List permissions = ImmutableList.of("pubsub.subscriptions.get"); List permissionsResult = ImmutableList.of(true); initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.testSubscriptionPermissions(NAME, permissions)).andReturn(permissionsResult); replay(pubsub); initializeSubscription(); @@ -417,7 +417,7 @@ public void testTestPermissionsAsync() throws ExecutionException, InterruptedExc List permissions = ImmutableList.of("pubsub.subscriptions.get"); List permissionsResult = ImmutableList.of(true); initializeExpectedSubscription(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.testSubscriptionPermissionsAsync(NAME, permissions)) .andReturn(Futures.immediateFuture(permissionsResult)); replay(pubsub); diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicTest.java index 0b22a2c0b98e..438759b73184 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/TopicTest.java @@ -48,7 +48,7 @@ public class TopicTest { private static final String NAME = "topic"; private static final TopicInfo TOPIC_INFO = TopicInfo.of(NAME); - private static final Policy POLICY = Policy.builder() + private static final Policy POLICY = Policy.newBuilder() .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers()) .build(); @@ -59,7 +59,7 @@ public class TopicTest { private Topic topic; private void initializeExpectedTopic(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); pubsub = createStrictMock(PubSub.class); expectedTopic = new Topic(serviceMockReturnsOptions, new Topic.BuilderImpl(TOPIC_INFO)); @@ -105,7 +105,7 @@ public void testReload() { TopicInfo updatedInfo = TOPIC_INFO.toBuilder().setName("newTopic").build(); Topic expectedTopic = new Topic(serviceMockReturnsOptions, new TopicInfo.BuilderImpl(updatedInfo)); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getTopic(NAME)).andReturn(expectedTopic); replay(pubsub); initializeTopic(); @@ -116,7 +116,7 @@ public void testReload() { @Test public void testReloadNull() { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getTopic(NAME)).andReturn(null); replay(pubsub); initializeTopic(); @@ -129,7 +129,7 @@ public void testReloadAsync() throws ExecutionException, InterruptedException { TopicInfo updatedInfo = TOPIC_INFO.toBuilder().setName("newTopic").build(); Topic expectedTopic = new Topic(serviceMockReturnsOptions, new TopicInfo.BuilderImpl(updatedInfo)); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getTopicAsync(NAME)) .andReturn(Futures.immediateFuture(expectedTopic)); replay(pubsub); @@ -141,7 +141,7 @@ public void testReloadAsync() throws ExecutionException, InterruptedException { @Test public void testReloadAsyncNull() throws ExecutionException, InterruptedException { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getTopicAsync(NAME)).andReturn(Futures.immediateFuture(null)); replay(pubsub); initializeTopic(); @@ -151,7 +151,7 @@ public void testReloadAsyncNull() throws ExecutionException, InterruptedExceptio @Test public void testDeleteTrue() { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.deleteTopic(NAME)).andReturn(true); replay(pubsub); initializeTopic(); @@ -161,7 +161,7 @@ public void testDeleteTrue() { @Test public void testDeleteFalse() { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.deleteTopic(NAME)).andReturn(false); replay(pubsub); initializeTopic(); @@ -171,7 +171,7 @@ public void testDeleteFalse() { @Test public void testDeleteAsyncTrue() throws ExecutionException, InterruptedException { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.deleteTopicAsync(NAME)).andReturn(Futures.immediateFuture(true)); replay(pubsub); initializeTopic(); @@ -181,7 +181,7 @@ public void testDeleteAsyncTrue() throws ExecutionException, InterruptedExceptio @Test public void testDeleteAsyncFalse() throws ExecutionException, InterruptedException { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.deleteTopicAsync(NAME)).andReturn(Futures.immediateFuture(false)); replay(pubsub); initializeTopic(); @@ -191,7 +191,7 @@ public void testDeleteAsyncFalse() throws ExecutionException, InterruptedExcepti @Test public void testPublishOneMessage() { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); Message message = Message.of("payload1"); String messageId = "messageId"; expect(pubsub.publish(NAME, message)).andReturn(messageId); @@ -203,7 +203,7 @@ public void testPublishOneMessage() { @Test public void testPublishOneMessageAsync() throws ExecutionException, InterruptedException { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); Message message = Message.of("payload1"); String messageId = "messageId"; expect(pubsub.publishAsync(NAME, message)) @@ -216,7 +216,7 @@ public void testPublishOneMessageAsync() throws ExecutionException, InterruptedE @Test public void testPublishMoreMessages() { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); Message message1 = Message.of("payload1"); Message message2 = Message.of("payload2"); List messageIds = ImmutableList.of("messageId1", "messageId2"); @@ -229,7 +229,7 @@ public void testPublishMoreMessages() { @Test public void testPublishMoreMessagesAsync() throws ExecutionException, InterruptedException { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); Message message1 = Message.of("payload1"); Message message2 = Message.of("payload2"); List messageIds = ImmutableList.of("messageId1", "messageId2"); @@ -243,7 +243,7 @@ public void testPublishMoreMessagesAsync() throws ExecutionException, Interrupte @Test public void testPublishMessageList() { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); Message message1 = Message.of("payload1"); Message message2 = Message.of("payload2"); List messages = ImmutableList.of(message1, message2); @@ -257,7 +257,7 @@ public void testPublishMessageList() { @Test public void testPublishMessageListAsync() throws ExecutionException, InterruptedException { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); Message message1 = Message.of("payload1"); Message message2 = Message.of("payload2"); List messages = ImmutableList.of(message1, message2); @@ -272,7 +272,7 @@ public void testPublishMessageListAsync() throws ExecutionException, Interrupted @Test public void testListSubscriptions() { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); final List subscriptions = ImmutableList.of( new SubscriptionId("project", "subscription1"), new SubscriptionId("project", "subscription2")); @@ -280,13 +280,13 @@ public void testListSubscriptions() { expect(pubsub.listSubscriptions(NAME)).andReturn(result); replay(pubsub); initializeTopic(); - assertEquals(subscriptions, topic.listSubscriptions().values()); + assertEquals(subscriptions, topic.listSubscriptions().getValues()); } @Test public void testListSubscriptionsWithOptions() { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); final List subscriptions = ImmutableList.of( new SubscriptionId("project", "subscription1"), new SubscriptionId("project", "subscription2")); @@ -294,13 +294,13 @@ public void testListSubscriptionsWithOptions() { expect(pubsub.listSubscriptions(NAME, ListOption.pageSize(42))).andReturn(result); replay(pubsub); initializeTopic(); - assertEquals(subscriptions, topic.listSubscriptions(ListOption.pageSize(42)).values()); + assertEquals(subscriptions, topic.listSubscriptions(ListOption.pageSize(42)).getValues()); } @Test public void testListSubscriptionsAsync() throws ExecutionException, InterruptedException { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); final List subscriptions = ImmutableList.of( new SubscriptionId("project", "subscription1"), new SubscriptionId("project", "subscription2")); @@ -309,14 +309,14 @@ public void testListSubscriptionsAsync() throws ExecutionException, InterruptedE .andReturn(Futures.immediateFuture(result)); replay(pubsub); initializeTopic(); - assertEquals(subscriptions, topic.listSubscriptionsAsync().get().values()); + assertEquals(subscriptions, topic.listSubscriptionsAsync().get().getValues()); } @Test public void testListSubscriptionsAsyncWithOptions() throws ExecutionException, InterruptedException { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); final List subscriptions = ImmutableList.of( new SubscriptionId("project", "subscription1"), new SubscriptionId("project", "subscription2")); @@ -326,13 +326,13 @@ public void testListSubscriptionsAsyncWithOptions() replay(pubsub); initializeTopic(); assertEquals(subscriptions, - topic.listSubscriptionsAsync(ListOption.pageSize(42)).get().values()); + topic.listSubscriptionsAsync(ListOption.pageSize(42)).get().getValues()); } @Test public void testGetPolicy() { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getTopicPolicy(NAME)).andReturn(POLICY); replay(pubsub); initializeTopic(); @@ -343,7 +343,7 @@ public void testGetPolicy() { @Test public void testGetPolicyNull() { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getTopicPolicy(NAME)).andReturn(null); replay(pubsub); initializeTopic(); @@ -353,7 +353,7 @@ public void testGetPolicyNull() { @Test public void testGetPolicyAsync() throws ExecutionException, InterruptedException { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.getTopicPolicyAsync(NAME)).andReturn(Futures.immediateFuture(POLICY)); replay(pubsub); initializeTopic(); @@ -364,7 +364,7 @@ public void testGetPolicyAsync() throws ExecutionException, InterruptedException @Test public void testReplacePolicy() { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.replaceTopicPolicy(NAME, POLICY)).andReturn(POLICY); replay(pubsub); initializeTopic(); @@ -375,7 +375,7 @@ public void testReplacePolicy() { @Test public void testReplacePolicyAsync() throws ExecutionException, InterruptedException { initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.replaceTopicPolicyAsync(NAME, POLICY)).andReturn(Futures.immediateFuture(POLICY)); replay(pubsub); initializeTopic(); @@ -388,7 +388,7 @@ public void testTestPermissions() { List permissions = ImmutableList.of("pubsub.topics.get"); List permissionsResult = ImmutableList.of(true); initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.testTopicPermissions(NAME, permissions)).andReturn(permissionsResult); replay(pubsub); initializeTopic(); @@ -400,7 +400,7 @@ public void testTestPermissionsAsync() throws ExecutionException, InterruptedExc List permissions = ImmutableList.of("pubsub.topics.get"); List permissionsResult = ImmutableList.of(true); initializeExpectedTopic(1); - expect(pubsub.options()).andReturn(mockOptions); + expect(pubsub.getOptions()).andReturn(mockOptions); expect(pubsub.testTopicPermissionsAsync(NAME, permissions)) .andReturn(Futures.immediateFuture(permissionsResult)); replay(pubsub); diff --git a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/it/ITPubSubTest.java b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/it/ITPubSubTest.java index 249942b705cf..9f9ccdecee25 100644 --- a/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/it/ITPubSubTest.java +++ b/google-cloud-pubsub/src/test/java/com/google/cloud/pubsub/it/ITPubSubTest.java @@ -41,7 +41,7 @@ public class ITPubSubTest extends BaseSystemTest { - private static final PubSub PUB_SUB = PubSubOptions.defaultInstance().service(); + private static final PubSub PUB_SUB = PubSubOptions.getDefaultInstance().getService(); private static final String NAME_SUFFIX = UUID.randomUUID().toString(); @Rule @@ -68,8 +68,8 @@ public void testTopicPolicy() { policy = pubsub().replaceTopicPolicy(topicName, policy.toBuilder() .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers()) .build()); - assertTrue(policy.bindings().containsKey(Role.viewer())); - assertTrue(policy.bindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); + assertTrue(policy.getBindings().containsKey(Role.viewer())); + assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); List permissions = pubsub().testTopicPermissions(topicName, ImmutableList.of("pubsub.topics.get")); assertTrue(permissions.get(0)); @@ -90,8 +90,8 @@ public void testTopicPolicyAsync() throws ExecutionException, InterruptedExcepti policy = pubsub().replaceTopicPolicyAsync(topicName, policy.toBuilder() .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers()) .build()).get(); - assertTrue(policy.bindings().containsKey(Role.viewer())); - assertTrue(policy.bindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); + assertTrue(policy.getBindings().containsKey(Role.viewer())); + assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); List permissions = pubsub().testTopicPermissionsAsync(topicName, ImmutableList.of("pubsub.topics.get")).get(); assertTrue(permissions.get(0)); @@ -108,8 +108,8 @@ public void testSubscriptionPolicy() { policy = pubsub().replaceSubscriptionPolicy(subscriptionName, policy.toBuilder() .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers()) .build()); - assertTrue(policy.bindings().containsKey(Role.viewer())); - assertTrue(policy.bindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); + assertTrue(policy.getBindings().containsKey(Role.viewer())); + assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); List permissions = pubsub().testSubscriptionPermissions(subscriptionName, ImmutableList.of("pubsub.subscriptions.get")); assertTrue(permissions.get(0)); @@ -127,8 +127,8 @@ public void testSubscriptionPolicyAsync() throws ExecutionException, Interrupted policy = pubsub().replaceSubscriptionPolicyAsync(subscriptionName, policy.toBuilder() .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers()) .build()).get(); - assertTrue(policy.bindings().containsKey(Role.viewer())); - assertTrue(policy.bindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); + assertTrue(policy.getBindings().containsKey(Role.viewer())); + assertTrue(policy.getBindings().get(Role.viewer()).contains(Identity.allAuthenticatedUsers())); List permissions = pubsub().testSubscriptionPermissionsAsync(subscriptionName, ImmutableList.of("pubsub.subscriptions.get")).get(); assertTrue(permissions.get(0)); diff --git a/google-cloud-resourcemanager/README.md b/google-cloud-resourcemanager/README.md index 73ca172f3658..8ebf987bbb74 100644 --- a/google-cloud-resourcemanager/README.md +++ b/google-cloud-resourcemanager/README.md @@ -83,7 +83,7 @@ code to create your service object: import com.google.cloud.resourcemanager.ResourceManager; import com.google.cloud.resourcemanager.ResourceManagerOptions; -ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service(); +ResourceManager resourceManager = ResourceManagerOptions.getDefaultInstance().getService(); ``` #### Getting a specific project diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/PolicyMarshaller.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/PolicyMarshaller.java index 1d756433f577..b0c1f459bc46 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/PolicyMarshaller.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/PolicyMarshaller.java @@ -41,10 +41,10 @@ private PolicyMarshaller() {} private static class Builder extends Policy.Builder { private Builder(Map> bindings, String etag, Integer version) { - bindings(bindings); - etag(etag); + setBindings(bindings); + setEtag(etag); if (version != null) { - version(version); + setVersion(version); } } } @@ -67,16 +67,16 @@ protected com.google.api.services.cloudresourcemanager.model.Policy toPb(Policy new com.google.api.services.cloudresourcemanager.model.Policy(); List bindingPbList = new LinkedList<>(); - for (Map.Entry> binding : policy.bindings().entrySet()) { + for (Map.Entry> binding : policy.getBindings().entrySet()) { Binding bindingPb = new Binding(); - bindingPb.setRole(binding.getKey().value()); + bindingPb.setRole(binding.getKey().getValue()); bindingPb.setMembers( Lists.transform(new ArrayList<>(binding.getValue()), IDENTITY_STR_VALUE_FUNCTION)); bindingPbList.add(bindingPb); } policyPb.setBindings(bindingPbList); - policyPb.setEtag(policy.etag()); - policyPb.setVersion(policy.version()); + policyPb.setEtag(policy.getEtag()); + policyPb.setVersion(policy.getVersion()); return policyPb; } } diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/Project.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/Project.java index a34765c1c94b..1927ecc5adaf 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/Project.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/Project.java @@ -140,7 +140,7 @@ public Project build() { Project(ResourceManager resourceManager, ProjectInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.resourceManager = checkNotNull(resourceManager); - this.options = resourceManager.options(); + this.options = resourceManager.getOptions(); } /** @@ -304,7 +304,7 @@ public final int hashCode() { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); - this.resourceManager = options.service(); + this.resourceManager = options.getService(); } static Project fromPb(ResourceManager resourceManager, diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManager.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManager.java index 87f95b2f6431..694c7d1a4542 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManager.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManager.java @@ -59,7 +59,13 @@ enum ProjectField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerException.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerException.java index 2a6906fc0090..e6171955f516 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerException.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerException.java @@ -60,7 +60,7 @@ public ResourceManagerException(IOException exception) { } @Override - protected Set retryableErrors() { + protected Set getRetryableErrors() { return RETRYABLE_ERRORS; } diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerImpl.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerImpl.java index 67daa57a02b7..46b0dc1ff6ca 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerImpl.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerImpl.java @@ -44,7 +44,7 @@ final class ResourceManagerImpl ResourceManagerImpl(ResourceManagerOptions options) { super(options); - resourceManagerRpc = options.rpc(); + resourceManagerRpc = options.getRpc(); } @Override @@ -56,7 +56,7 @@ public Project create(final ProjectInfo project) { public com.google.api.services.cloudresourcemanager.model.Project call() { return resourceManagerRpc.create(project.toPb()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException ex) { throw ResourceManagerException.translateAndThrow(ex); } @@ -71,7 +71,7 @@ public Void call() { resourceManagerRpc.delete(projectId); return null; } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException ex) { throw ResourceManagerException.translateAndThrow(ex); } @@ -87,7 +87,7 @@ public Project get(final String projectId, ProjectGetOption... options) { public com.google.api.services.cloudresourcemanager.model.Project call() { return resourceManagerRpc.get(projectId, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Project.fromPb(this, answer); } catch (RetryHelperException ex) { throw ResourceManagerException.translateAndThrow(ex); @@ -108,14 +108,20 @@ private static class ProjectPageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listProjects(serviceOptions, requestOptions); } } @Override public Page list(ProjectListOption... options) { - return listProjects(options(), optionMap(options)); + return listProjects(getOptions(), optionMap(options)); } private static Page listProjects(final ResourceManagerOptions serviceOptions, @@ -127,10 +133,10 @@ private static Page listProjects(final ResourceManagerOptions serviceOp @Override public Tuple> call() { - return serviceOptions.rpc().list(optionsMap); + return serviceOptions.getRpc().list(optionsMap); } }, - serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable projects = result.y() == null @@ -142,7 +148,7 @@ Iterable> call() { public Project apply( com.google.api.services.cloudresourcemanager.model.Project projectPb) { return new Project( - serviceOptions.service(), + serviceOptions.getService(), new ProjectInfo.BuilderImpl(ProjectInfo.fromPb(projectPb))); } }); @@ -162,7 +168,7 @@ public Project replace(final ProjectInfo newProject) { public com.google.api.services.cloudresourcemanager.model.Project call() { return resourceManagerRpc.replace(newProject.toPb()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException ex) { throw ResourceManagerException.translateAndThrow(ex); } @@ -177,7 +183,7 @@ public Void call() { resourceManagerRpc.undelete(projectId); return null; } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException ex) { throw ResourceManagerException.translateAndThrow(ex); } @@ -193,7 +199,7 @@ public Policy getPolicy(final String projectId) { public com.google.api.services.cloudresourcemanager.model.Policy call() { return resourceManagerRpc.getPolicy(projectId); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : PolicyMarshaller.INSTANCE.fromPb(answer); } catch (RetryHelperException ex) { throw ResourceManagerException.translateAndThrow(ex); @@ -210,7 +216,7 @@ public com.google.api.services.cloudresourcemanager.model.Policy call() { return resourceManagerRpc.replacePolicy(projectId, PolicyMarshaller.INSTANCE.toPb(newPolicy)); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException ex) { throw ResourceManagerException.translateAndThrow(ex); } @@ -225,7 +231,7 @@ public List testPermissions(final String projectId, final List public List call() { return resourceManagerRpc.testPermissions(projectId, permissions); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException ex) { throw ResourceManagerException.translateAndThrow(ex); } diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerOptions.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerOptions.java index bceb40af8703..649dc5306f20 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerOptions.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/ResourceManagerOptions.java @@ -44,8 +44,16 @@ public ResourceManager create(ResourceManagerOptions options) { /** * Returns a default {@code ResourceManagerOptions} instance. */ + @Deprecated public static ResourceManagerOptions defaultInstance() { - return builder().build(); + return getDefaultInstance(); + } + + /** + * Returns a default {@code ResourceManagerOptions} instance. + */ + public static ResourceManagerOptions getDefaultInstance() { + return newBuilder().build(); } public static class DefaultResourceManagerRpcFactory implements ResourceManagerRpcFactory { @@ -59,7 +67,7 @@ public ResourceManagerRpc create(ResourceManagerOptions options) { } @Override - protected String defaultHost() { + protected String getDefaultHost() { return DEFAULT_HOST; } @@ -88,17 +96,17 @@ protected boolean projectIdRequired() { } @Override - protected ResourceManagerFactory defaultServiceFactory() { + protected ResourceManagerFactory getDefaultServiceFactory() { return DefaultResourceManagerFactory.INSTANCE; } @Override - protected ResourceManagerRpcFactory defaultRpcFactory() { + protected ResourceManagerRpcFactory getDefaultRpcFactory() { return DefaultResourceManagerRpcFactory.INSTANCE; } @Override - protected Set scopes() { + protected Set getScopes() { return SCOPES; } @@ -118,7 +126,12 @@ public Builder toBuilder() { return new Builder(this); } + @Deprecated public static Builder builder() { + return newBuilder(); + } + + public static Builder newBuilder() { return new Builder(); } } diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/package-info.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/package-info.java index 3f8d94de756e..41bbd2a662c4 100644 --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/package-info.java +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/package-info.java @@ -22,13 +22,13 @@ * * GetOrCreateProject.java. *

     {@code
    - * ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service();
    + * ResourceManager resourceManager = ResourceManagerOptions.getDefaultInstance().getService();
      * String projectId = "my-globally-unique-project-id"; // Change to a unique project ID.
      * Project project = resourceManager.get(projectId);
      * if (project == null) {
      *   project = resourceManager.create(ProjectInfo.builder(projectId).build());
      * }
    - * System.out.println("Got project " + project.projectId() + " from the server.");
    + * System.out.println("Got project " + project.getProjectId() + " from the server.");
      * }
    *

    * This second example shows how to update a project if it exists and list all projects the user has @@ -36,7 +36,7 @@ * * UpdateAndListProjects.java. *

     {@code
    - * ResourceManager resourceManager = ResourceManagerOptions.defaultInstance().service();
    + * ResourceManager resourceManager = ResourceManagerOptions.getDefaultInstance().getService();
      * Project project = resourceManager.get("some-project-id"); // Use an existing project's ID
      * if (project != null) {
      *   Project newProject = project.toBuilder()
    diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/spi/DefaultResourceManagerRpc.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/spi/DefaultResourceManagerRpc.java
    index 43cb40bcd306..f156a6d6c8fc 100644
    --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/spi/DefaultResourceManagerRpc.java
    +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/spi/DefaultResourceManagerRpc.java
    @@ -50,12 +50,12 @@ public class DefaultResourceManagerRpc implements ResourceManagerRpc {
       private final Cloudresourcemanager resourceManager;
     
       public DefaultResourceManagerRpc(ResourceManagerOptions options) {
    -    HttpTransport transport = options.httpTransportFactory().create();
    -    HttpRequestInitializer initializer = options.httpRequestInitializer();
    +    HttpTransport transport = options.getHttpTransportFactory().create();
    +    HttpRequestInitializer initializer = options.getHttpRequestInitializer();
         resourceManager =
             new Cloudresourcemanager.Builder(transport, new JacksonFactory(), initializer)
    -            .setRootUrl(options.host())
    -            .setApplicationName(options.applicationName())
    +            .setRootUrl(options.getHost())
    +            .setApplicationName(options.getApplicationName())
                 .build();
       }
     
    @@ -90,7 +90,7 @@ public Project get(String projectId, Map options) {
               .execute();
         } catch (IOException ex) {
           ResourceManagerException translated = translate(ex);
    -      if (translated.code() == HTTP_FORBIDDEN || translated.code() == HTTP_NOT_FOUND) {
    +      if (translated.getCode() == HTTP_FORBIDDEN || translated.getCode() == HTTP_NOT_FOUND) {
             // Service can return either 403 or 404 to signify that the project doesn't exist.
             return null;
           } else {
    @@ -142,7 +142,7 @@ public Policy getPolicy(String projectId) throws ResourceManagerException {
               .execute();
         } catch (IOException ex) {
           ResourceManagerException translated = translate(ex);
    -      if (translated.code() == HTTP_FORBIDDEN) {
    +      if (translated.getCode() == HTTP_FORBIDDEN) {
             // Service returns permission denied if policy doesn't exist.
             return null;
           } else {
    diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java
    index d794514e1b2f..d5200f954b6b 100644
    --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java
    +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelper.java
    @@ -684,9 +684,9 @@ public ResourceManagerOptions options() {
        * Returns a {@link ResourceManagerOptions} instance that sets the host to use the mock server.
        */
       public ResourceManagerOptions getOptions() {
    -    return ResourceManagerOptions.builder()
    -        .host("http://localhost:" + port)
    -        .authCredentials(AuthCredentials.noAuth())
    +    return ResourceManagerOptions.newBuilder()
    +        .setHost("http://localhost:" + port)
    +        .setAuthCredentials(AuthCredentials.noAuth())
             .build();
       }
     
    diff --git a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/package-info.java b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/package-info.java
    index b65d84934ac4..9071c91f004c 100644
    --- a/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/package-info.java
    +++ b/google-cloud-resourcemanager/src/main/java/com/google/cloud/resourcemanager/testing/package-info.java
    @@ -22,7 +22,7 @@
      * 
     {@code
      * LocalResourceManagerHelper resourceManagerHelper = LocalResourceManagerHelper.create();
      * resourceManagerHelper.start();
    - * ResourceManager resourceManager = resourceManagerHelper.getOptions().service();
    + * ResourceManager resourceManager = resourceManagerHelper.getOptions().getService();
      * }
    * *

    After the test: diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/PolicyMarshallerTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/PolicyMarshallerTest.java index f017a9a2c03c..95e7596449b6 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/PolicyMarshallerTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/PolicyMarshallerTest.java @@ -39,7 +39,7 @@ public class PolicyMarshallerTest { private static final Role EDITOR = Role.editor(); private static final Role OWNER = Role.owner(); private static final Role SOME_ROLE = Role.of("roles/some-role"); - private static final Policy SIMPLE_POLICY = Policy.builder() + private static final Policy SIMPLE_POLICY = Policy.newBuilder() .addIdentity(OWNER, USER) .addIdentity(VIEWER, ALL_USERS) .addIdentity(EDITOR, ALL_AUTH_USERS, DOMAIN) @@ -58,8 +58,8 @@ public void testToAndFromPb() { com.google.api.services.cloudresourcemanager.model.Policy policyPb = new com.google.api.services.cloudresourcemanager.model.Policy(); Policy policy = PolicyMarshaller.INSTANCE.fromPb(policyPb); - assertTrue(policy.bindings().isEmpty()); - assertNull(policy.etag()); - assertEquals(0, policy.version()); + assertTrue(policy.getBindings().isEmpty()); + assertNull(policy.getEtag()); + assertEquals(0, policy.getVersion()); } } diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectInfoTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectInfoTest.java index 2d3db2b13364..b2ca95207ad6 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectInfoTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectInfoTest.java @@ -44,7 +44,8 @@ public class ProjectInfoTest { .setState(STATE) .setParent(PARENT) .build(); - private static final ProjectInfo PARTIAL_PROJECT_INFO = ProjectInfo.newBuilder(PROJECT_ID).build(); + private static final ProjectInfo PARTIAL_PROJECT_INFO = + ProjectInfo.newBuilder(PROJECT_ID).build(); private static final ProjectInfo UNNAMED_PROJECT_FROM_LIST = PARTIAL_PROJECT_INFO.toBuilder().setName("Unnamed").build(); private static final ProjectInfo DEPRECATED_PROJECT_INFO = ProjectInfo.builder(PROJECT_ID) diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectTest.java index bb23c8e5b1ae..c98a9a000381 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ProjectTest.java @@ -56,7 +56,7 @@ public class ProjectTest { private static final Identity USER = Identity.user("abc@gmail.com"); private static final Identity SERVICE_ACCOUNT = Identity.serviceAccount("service-account@gmail.com"); - private static final Policy POLICY = Policy.builder() + private static final Policy POLICY = Policy.newBuilder() .addIdentity(Role.owner(), USER) .addIdentity(Role.editor(), SERVICE_ACCOUNT) .build(); @@ -78,7 +78,7 @@ public void tearDown() throws Exception { } private void initializeExpectedProject(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); expectedProject = new Project(serviceMockReturnsOptions, new ProjectInfo.BuilderImpl(PROJECT_INFO)); @@ -97,7 +97,7 @@ public void testToBuilder() { @Test public void testBuilder() { - expect(resourceManager.options()).andReturn(mockOptions).times(7); + expect(resourceManager.getOptions()).andReturn(mockOptions).times(7); replay(resourceManager); Project.Builder builder = new Project.Builder(new Project(resourceManager, new ProjectInfo.BuilderImpl("wrong-id"))); @@ -114,7 +114,7 @@ public void testBuilder() { assertEquals(PROJECT_NUMBER, project.getProjectNumber()); assertEquals(CREATE_TIME_MILLIS, project.getCreateTimeMillis()); assertEquals(STATE, project.getState()); - assertEquals(resourceManager.options(), project.getResourceManager().options()); + assertEquals(resourceManager.getOptions(), project.getResourceManager().getOptions()); assertNull(project.getParent()); ResourceId parent = new ResourceId("id", "type"); project = project.toBuilder() @@ -130,13 +130,13 @@ public void testBuilder() { assertEquals(PROJECT_NUMBER, project.getProjectNumber()); assertEquals(CREATE_TIME_MILLIS, project.getCreateTimeMillis()); assertEquals(STATE, project.getState()); - assertEquals(resourceManager.options(), project.getResourceManager().options()); + assertEquals(resourceManager.getOptions(), project.getResourceManager().getOptions()); assertEquals(parent, project.getParent()); } @Test public void testBuilderDeprecated() { - expect(resourceManager.options()).andReturn(mockOptions).times(4); + expect(resourceManager.getOptions()).andReturn(mockOptions).times(4); replay(resourceManager); Project.Builder builder = new Project.Builder(new Project(resourceManager, new ProjectInfo.BuilderImpl("wrong-id"))); @@ -153,7 +153,7 @@ public void testBuilderDeprecated() { assertEquals(PROJECT_NUMBER, project.projectNumber()); assertEquals(CREATE_TIME_MILLIS, project.createTimeMillis()); assertEquals(STATE, project.state()); - assertEquals(resourceManager.options(), project.resourceManager().options()); + assertEquals(resourceManager.getOptions(), project.resourceManager().getOptions()); assertNull(project.getParent()); } @@ -172,7 +172,7 @@ public void testReload() { ProjectInfo newInfo = PROJECT_INFO.toBuilder().addLabel("k3", "v3").build(); Project expectedProject = new Project(serviceMockReturnsOptions, new ProjectInfo.BuilderImpl(newInfo)); - expect(resourceManager.options()).andReturn(mockOptions); + expect(resourceManager.getOptions()).andReturn(mockOptions); expect(resourceManager.get(PROJECT_INFO.getProjectId())).andReturn(expectedProject); replay(resourceManager); initializeProject(); @@ -191,7 +191,7 @@ public void testLoadNull() { @Test public void testReloadNull() { initializeExpectedProject(1); - expect(resourceManager.options()).andReturn(mockOptions); + expect(resourceManager.getOptions()).andReturn(mockOptions); expect(resourceManager.get(PROJECT_INFO.getProjectId())).andReturn(null); replay(resourceManager); Project reloadedProject = @@ -209,7 +209,7 @@ public void testResourceManager() { @Test public void testDelete() { initializeExpectedProject(1); - expect(resourceManager.options()).andReturn(mockOptions); + expect(resourceManager.getOptions()).andReturn(mockOptions); resourceManager.delete(PROJECT_INFO.getProjectId()); replay(resourceManager); initializeProject(); @@ -219,7 +219,7 @@ public void testDelete() { @Test public void testUndelete() { initializeExpectedProject(1); - expect(resourceManager.options()).andReturn(mockOptions); + expect(resourceManager.getOptions()).andReturn(mockOptions); resourceManager.undelete(PROJECT_INFO.getProjectId()); replay(resourceManager); initializeProject(); @@ -230,7 +230,7 @@ public void testUndelete() { public void testReplace() { initializeExpectedProject(2); Project expectedReplacedProject = expectedProject.toBuilder().addLabel("k3", "v3").build(); - expect(resourceManager.options()).andReturn(mockOptions).times(2); + expect(resourceManager.getOptions()).andReturn(mockOptions).times(2); expect(resourceManager.replace(anyObject(Project.class))).andReturn(expectedReplacedProject); replay(resourceManager); initializeProject(); @@ -242,7 +242,7 @@ public void testReplace() { @Test public void testGetPolicy() { - expect(resourceManager.options()).andReturn(mockOptions).times(1); + expect(resourceManager.getOptions()).andReturn(mockOptions).times(1); expect(resourceManager.getPolicy(PROJECT_ID)).andReturn(POLICY); replay(resourceManager); initializeProject(); @@ -251,7 +251,7 @@ public void testGetPolicy() { @Test public void testReplacePolicy() { - expect(resourceManager.options()).andReturn(mockOptions).times(1); + expect(resourceManager.getOptions()).andReturn(mockOptions).times(1); expect(resourceManager.replacePolicy(PROJECT_ID, POLICY)).andReturn(POLICY); replay(resourceManager); initializeProject(); @@ -263,7 +263,7 @@ public void testTestPermissions() { List response = ImmutableList.of(true, true); String getPermission = "resourcemanager.projects.get"; String deletePermission = "resourcemanager.projects.delete"; - expect(resourceManager.options()).andReturn(mockOptions).times(1); + expect(resourceManager.getOptions()).andReturn(mockOptions).times(1); expect(resourceManager.testPermissions( PROJECT_ID, ImmutableList.of(getPermission, deletePermission))) .andReturn(response); @@ -276,7 +276,8 @@ public void testTestPermissions() { private void compareProjects(Project expected, Project value) { assertEquals(expected, value); compareProjectInfos(expected, value); - assertEquals(expected.getResourceManager().options(), value.getResourceManager().options()); + assertEquals(expected.getResourceManager().getOptions(), + value.getResourceManager().getOptions()); } private void compareProjectInfos(ProjectInfo expected, ProjectInfo value) { diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ResourceManagerExceptionTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ResourceManagerExceptionTest.java index 8e725b366a6b..2f32c3b03ed5 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ResourceManagerExceptionTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ResourceManagerExceptionTest.java @@ -39,47 +39,47 @@ public class ResourceManagerExceptionTest { @Test public void testResourceManagerException() { ResourceManagerException exception = new ResourceManagerException(500, "message"); - assertEquals(500, exception.code()); + assertEquals(500, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new ResourceManagerException(503, "message"); - assertEquals(503, exception.code()); + assertEquals(503, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new ResourceManagerException(429, "message"); - assertEquals(429, exception.code()); + assertEquals(429, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new ResourceManagerException(403, "message"); - assertEquals(403, exception.code()); + assertEquals(403, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertFalse(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertFalse(exception.isRetryable()); + assertTrue(exception.isIdempotent()); IOException cause = new SocketTimeoutException(); exception = new ResourceManagerException(cause); - assertNull(exception.reason()); + assertNull(exception.getReason()); assertNull(exception.getMessage()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); exception = new ResourceManagerException(404, "message", cause); - assertEquals(404, exception.code()); + assertEquals(404, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertFalse(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertFalse(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); } @@ -92,10 +92,10 @@ public void testTranslateAndThrow() throws Exception { try { ResourceManagerException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(503, ex.code()); + assertEquals(503, ex.getCode()); assertEquals("message", ex.getMessage()); - assertTrue(ex.retryable()); - assertTrue(ex.idempotent()); + assertTrue(ex.isRetryable()); + assertTrue(ex.isIdempotent()); } finally { verify(exceptionMock); } @@ -107,10 +107,10 @@ public void testTranslateAndThrow() throws Exception { try { ResourceManagerException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(ResourceManagerException.UNKNOWN_CODE, ex.code()); + assertEquals(ResourceManagerException.UNKNOWN_CODE, ex.getCode()); assertEquals("message", ex.getMessage()); - assertFalse(ex.retryable()); - assertTrue(ex.idempotent()); + assertFalse(ex.isRetryable()); + assertTrue(ex.isIdempotent()); assertSame(cause, ex.getCause()); } finally { verify(exceptionMock); diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ResourceManagerImplTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ResourceManagerImplTest.java index 58ea3a2f63f3..f903cbeccca6 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ResourceManagerImplTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/ResourceManagerImplTest.java @@ -56,14 +56,15 @@ public class ResourceManagerImplTest { private static final LocalResourceManagerHelper RESOURCE_MANAGER_HELPER = LocalResourceManagerHelper.create(); private static final ResourceManager RESOURCE_MANAGER = - RESOURCE_MANAGER_HELPER.getOptions().service(); + RESOURCE_MANAGER_HELPER.getOptions().getService(); private static final ProjectGetOption GET_FIELDS = ProjectGetOption.fields(ProjectField.NAME, ProjectField.CREATE_TIME); private static final ProjectListOption LIST_FIELDS = ProjectListOption.fields(ProjectField.NAME, ProjectField.LABELS); private static final ProjectListOption LIST_FILTER = ProjectListOption.filter("id:* name:myProject labels.color:blue LABELS.SIZE:*"); - private static final ProjectInfo PARTIAL_PROJECT = ProjectInfo.newBuilder("partial-project").build(); + private static final ProjectInfo PARTIAL_PROJECT = + ProjectInfo.newBuilder("partial-project").build(); private static final ResourceId PARENT = new ResourceId("id", "type"); private static final ProjectInfo COMPLETE_PROJECT = ProjectInfo.newBuilder("complete-project") .setName("name") @@ -71,7 +72,7 @@ public class ResourceManagerImplTest { .setParent(PARENT) .build(); private static final Map EMPTY_RPC_OPTIONS = ImmutableMap.of(); - private static final Policy POLICY = Policy.builder() + private static final Policy POLICY = Policy.newBuilder() .addIdentity(Role.owner(), Identity.user("me@gmail.com")) .addIdentity(Role.editor(), Identity.serviceAccount("serviceaccount@gmail.com")) .build(); @@ -90,7 +91,7 @@ public void setUp() { } private void clearProjects() { - for (Project project : RESOURCE_MANAGER.list().values()) { + for (Project project : RESOURCE_MANAGER.list().getValues()) { RESOURCE_MANAGER_HELPER.removeProject(project.getProjectId()); } } @@ -121,7 +122,7 @@ public void testCreate() { RESOURCE_MANAGER.create(PARTIAL_PROJECT); fail("Should fail, project already exists."); } catch (ResourceManagerException e) { - assertEquals(409, e.code()); + assertEquals(409, e.getCode()); assertTrue(e.getMessage().startsWith("A project with the same project ID") && e.getMessage().endsWith("already exists.")); } @@ -143,7 +144,7 @@ public void testDelete() { RESOURCE_MANAGER.delete("some-nonexistant-project-id"); fail("Should fail because the project doesn't exist."); } catch (ResourceManagerException e) { - assertEquals(403, e.code()); + assertEquals(403, e.getCode()); assertTrue(e.getMessage().contains("not found.")); } } @@ -177,10 +178,10 @@ public void testGetWithOptions() { @Test public void testList() { Page projects = RESOURCE_MANAGER.list(); - assertFalse(projects.values().iterator().hasNext()); + assertFalse(projects.getValues().iterator().hasNext()); RESOURCE_MANAGER.create(PARTIAL_PROJECT); RESOURCE_MANAGER.create(COMPLETE_PROJECT); - for (Project p : RESOURCE_MANAGER.list().values()) { + for (Project p : RESOURCE_MANAGER.list().getValues()) { if (p.getProjectId().equals(PARTIAL_PROJECT.getProjectId())) { compareReadWriteFields(PARTIAL_PROJECT, p); } else if (p.getProjectId().equals(COMPLETE_PROJECT.getProjectId())) { @@ -197,15 +198,15 @@ public void testListPaging() { RESOURCE_MANAGER.create(PARTIAL_PROJECT); RESOURCE_MANAGER.create(COMPLETE_PROJECT); Page page = RESOURCE_MANAGER.list(ProjectListOption.pageSize(1)); - assertNotNull(page.nextPageCursor()); - Iterator iterator = page.values().iterator(); + assertNotNull(page.getNextPageCursor()); + Iterator iterator = page.getValues().iterator(); compareReadWriteFields(COMPLETE_PROJECT, iterator.next()); assertFalse(iterator.hasNext()); - page = page.nextPage(); - iterator = page.values().iterator(); + page = page.getNextPage(); + iterator = page.getValues().iterator(); compareReadWriteFields(PARTIAL_PROJECT, iterator.next()); assertFalse(iterator.hasNext()); - assertNull(page.nextPageCursor()); + assertNull(page.getNextPageCursor()); } @Test @@ -228,8 +229,8 @@ public void testListPagingWithFieldOptions() { RESOURCE_MANAGER.create(PARTIAL_PROJECT); RESOURCE_MANAGER.create(COMPLETE_PROJECT); Page projects = RESOURCE_MANAGER.list(LIST_FIELDS, ProjectListOption.pageSize(1)); - assertNotNull(projects.nextPageCursor()); - Iterator iterator = projects.values().iterator(); + assertNotNull(projects.getNextPageCursor()); + Iterator iterator = projects.getValues().iterator(); Project returnedProject = iterator.next(); assertEquals(COMPLETE_PROJECT.getProjectId(), returnedProject.getProjectId()); assertEquals(COMPLETE_PROJECT.getName(), returnedProject.getName()); @@ -240,8 +241,8 @@ public void testListPagingWithFieldOptions() { assertNull(returnedProject.getCreateTimeMillis()); assertSame(RESOURCE_MANAGER, returnedProject.getResourceManager()); assertFalse(iterator.hasNext()); - projects = projects.nextPage(); - iterator = projects.values().iterator(); + projects = projects.getNextPage(); + iterator = projects.getValues().iterator(); returnedProject = iterator.next(); assertEquals(PARTIAL_PROJECT.getProjectId(), returnedProject.getProjectId()); assertEquals(PARTIAL_PROJECT.getName(), returnedProject.getName()); @@ -252,7 +253,7 @@ public void testListPagingWithFieldOptions() { assertNull(returnedProject.getCreateTimeMillis()); assertSame(RESOURCE_MANAGER, returnedProject.getResourceManager()); assertFalse(iterator.hasNext()); - assertNull(projects.nextPageCursor()); + assertNull(projects.getNextPageCursor()); } @Test @@ -274,7 +275,7 @@ public void testListFilterOptions() { RESOURCE_MANAGER.create(nonMatchingProject1); RESOURCE_MANAGER.create(nonMatchingProject2); RESOURCE_MANAGER.create(nonMatchingProject3); - for (Project p : RESOURCE_MANAGER.list(LIST_FILTER).values()) { + for (Project p : RESOURCE_MANAGER.list(LIST_FILTER).getValues()) { assertFalse(p.equals(nonMatchingProject1)); assertFalse(p.equals(nonMatchingProject2)); compareReadWriteFields(matchingProject, p); @@ -305,7 +306,7 @@ public void testReplace() { RESOURCE_MANAGER.replace(nonexistantProject); fail("Should fail because the project doesn't exist."); } catch (ResourceManagerException e) { - assertEquals(403, e.code()); + assertEquals(403, e.getCode()); assertTrue(e.getMessage().contains("the project was not found")); } } @@ -325,7 +326,7 @@ public void testUndelete() { RESOURCE_MANAGER.undelete("invalid-project-id"); fail("Should fail because the project doesn't exist."); } catch (ResourceManagerException e) { - assertEquals(403, e.code()); + assertEquals(403, e.getCode()); assertTrue(e.getMessage().contains("the project was not found")); } } @@ -336,9 +337,9 @@ public void testGetPolicy() { RESOURCE_MANAGER.create(COMPLETE_PROJECT); RESOURCE_MANAGER.replacePolicy(COMPLETE_PROJECT.getProjectId(), POLICY); Policy retrieved = RESOURCE_MANAGER.getPolicy(COMPLETE_PROJECT.getProjectId()); - assertEquals(POLICY.bindings(), retrieved.bindings()); - assertNotNull(retrieved.etag()); - assertEquals(0, retrieved.version()); + assertEquals(POLICY.getBindings(), retrieved.getBindings()); + assertNotNull(retrieved.getEtag()); + assertEquals(0, retrieved.getVersion()); } @Test @@ -347,7 +348,7 @@ public void testReplacePolicy() { RESOURCE_MANAGER.replacePolicy("nonexistent-project", POLICY); fail("Project doesn't exist."); } catch (ResourceManagerException e) { - assertEquals(403, e.code()); + assertEquals(403, e.getCode()); assertTrue(e.getMessage().endsWith("project was not found.")); } RESOURCE_MANAGER.create(PARTIAL_PROJECT); @@ -357,14 +358,14 @@ public void testReplacePolicy() { RESOURCE_MANAGER.replacePolicy(PARTIAL_PROJECT.getProjectId(), oldPolicy); fail("Policy with an invalid etag didn't cause error."); } catch (ResourceManagerException e) { - assertEquals(409, e.code()); + assertEquals(409, e.getCode()); assertTrue(e.getMessage().contains("Policy etag mismatch")); } - String originalEtag = RESOURCE_MANAGER.getPolicy(PARTIAL_PROJECT.getProjectId()).etag(); + String originalEtag = RESOURCE_MANAGER.getPolicy(PARTIAL_PROJECT.getProjectId()).getEtag(); Policy newPolicy = RESOURCE_MANAGER.replacePolicy(PARTIAL_PROJECT.getProjectId(), POLICY); - assertEquals(POLICY.bindings(), newPolicy.bindings()); - assertNotNull(newPolicy.etag()); - assertNotEquals(originalEtag, newPolicy.etag()); + assertEquals(POLICY.getBindings(), newPolicy.getBindings()); + assertNotNull(newPolicy.getEtag()); + assertNotEquals(originalEtag, newPolicy.getEtag()); } @Test @@ -374,7 +375,7 @@ public void testTestPermissions() { RESOURCE_MANAGER.testPermissions("nonexistent-project", permissions); fail("Nonexistent project"); } catch (ResourceManagerException e) { - assertEquals(403, e.code()); + assertEquals(403, e.getCode()); assertEquals("Project nonexistent-project not found.", e.getMessage()); } RESOURCE_MANAGER.create(PARTIAL_PROJECT); @@ -389,10 +390,10 @@ public void testRetryableException() { EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(ResourceManagerOptions.class))) .andReturn(resourceManagerRpcMock); EasyMock.replay(rpcFactoryMock); - ResourceManager resourceManagerMock = ResourceManagerOptions.builder() - .serviceRpcFactory(rpcFactoryMock) + ResourceManager resourceManagerMock = ResourceManagerOptions.newBuilder() + .setServiceRpcFactory(rpcFactoryMock) .build() - .service(); + .getService(); EasyMock.expect(resourceManagerRpcMock.get(PARTIAL_PROJECT.getProjectId(), EMPTY_RPC_OPTIONS)) .andThrow(new ResourceManagerException(500, "Internal Error")) .andReturn(PARTIAL_PROJECT.toPb()); @@ -410,10 +411,10 @@ public void testNonRetryableException() { EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(ResourceManagerOptions.class))) .andReturn(resourceManagerRpcMock); EasyMock.replay(rpcFactoryMock); - ResourceManager resourceManagerMock = ResourceManagerOptions.builder() - .serviceRpcFactory(rpcFactoryMock) + ResourceManager resourceManagerMock = ResourceManagerOptions.newBuilder() + .setServiceRpcFactory(rpcFactoryMock) .build() - .service(); + .getService(); EasyMock.expect(resourceManagerRpcMock.get(PARTIAL_PROJECT.getProjectId(), EMPTY_RPC_OPTIONS)) .andThrow(new ResourceManagerException( 403, "Project " + PARTIAL_PROJECT.getProjectId() + " not found.")) @@ -431,8 +432,10 @@ public void testRuntimeException() { EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(ResourceManagerOptions.class))) .andReturn(resourceManagerRpcMock); EasyMock.replay(rpcFactoryMock); - ResourceManager resourceManagerMock = - ResourceManagerOptions.builder().serviceRpcFactory(rpcFactoryMock).build().service(); + ResourceManager resourceManagerMock = ResourceManagerOptions.newBuilder() + .setServiceRpcFactory(rpcFactoryMock) + .build() + .getService(); String exceptionMessage = "Artificial runtime exception"; EasyMock.expect(resourceManagerRpcMock.get(PARTIAL_PROJECT.getProjectId(), EMPTY_RPC_OPTIONS)) .andThrow(new RuntimeException(exceptionMessage)); diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/SerializationTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/SerializationTest.java index 60f312c81813..381e1ad77830 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/SerializationTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/SerializationTest.java @@ -27,7 +27,7 @@ public class SerializationTest extends BaseSerializationTest { private static final ResourceManager RESOURCE_MANAGER = - ResourceManagerOptions.defaultInstance().service(); + ResourceManagerOptions.getDefaultInstance().getService(); private static final ProjectInfo PARTIAL_PROJECT_INFO = ProjectInfo.newBuilder("id1").build(); private static final ProjectInfo FULL_PROJECT_INFO = ProjectInfo.newBuilder("id") .setName("name") @@ -49,9 +49,9 @@ public class SerializationTest extends BaseSerializationTest { @Override protected Serializable[] serializableObjects() { - ResourceManagerOptions options = ResourceManagerOptions.builder().build(); + ResourceManagerOptions options = ResourceManagerOptions.newBuilder().build(); ResourceManagerOptions otherOptions = options.toBuilder() - .projectId("some-unnecessary-project-ID") + .setProjectId("some-unnecessary-project-ID") .build(); return new Serializable[]{PARTIAL_PROJECT_INFO, FULL_PROJECT_INFO, PROJECT, PAGE_RESULT, PROJECT_GET_OPTION, PROJECT_LIST_OPTION, RESOURCE_MANAGER_EXCEPTION, options, otherOptions}; diff --git a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelperTest.java b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelperTest.java index 9089a093082e..ec47a5bf021d 100644 --- a/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelperTest.java +++ b/google-cloud-resourcemanager/src/test/java/com/google/cloud/resourcemanager/testing/LocalResourceManagerHelperTest.java @@ -129,7 +129,7 @@ public void testCreate() { rpc.create(PARTIAL_PROJECT); fail("Should fail, project already exists."); } catch (ResourceManagerException e) { - assertEquals(409, e.code()); + assertEquals(409, e.getCode()); assertTrue(e.getMessage().startsWith("A project with the same project ID") && e.getMessage().endsWith("already exists.")); assertEquals( @@ -170,7 +170,7 @@ private void expectInvalidArgumentException( rpc.create(project); fail("Should fail because of an invalid argument."); } catch (ResourceManagerException e) { - assertEquals(400, e.code()); + assertEquals(400, e.getCode()); assertTrue(e.getMessage().contains(errorMessageSubstring)); } } @@ -192,7 +192,7 @@ public void testIsInvalidProjectName() { rpc.create(project); fail("Should fail because of invalid project name."); } catch (ResourceManagerException e) { - assertEquals(400, e.code()); + assertEquals(400, e.getCode()); assertTrue(e.getMessage().contains("invalid name")); } } @@ -249,7 +249,7 @@ public void testDelete() { rpc.delete("some-nonexistant-project-id"); fail("Should fail because the project doesn't exist."); } catch (ResourceManagerException e) { - assertEquals(403, e.code()); + assertEquals(403, e.getCode()); assertTrue(e.getMessage().contains("not found.")); } } @@ -263,7 +263,7 @@ public void testDeleteWhenDeleteInProgress() { rpc.delete(COMPLETE_PROJECT.getProjectId()); fail("Should fail because the project is not ACTIVE."); } catch (ResourceManagerException e) { - assertEquals(400, e.code()); + assertEquals(400, e.getCode()); assertTrue(e.getMessage().contains("the lifecycle state was not ACTIVE")); } } @@ -277,7 +277,7 @@ public void testDeleteWhenDeleteRequested() { rpc.delete(COMPLETE_PROJECT.getProjectId()); fail("Should fail because the project is not ACTIVE."); } catch (ResourceManagerException e) { - assertEquals(400, e.code()); + assertEquals(400, e.getCode()); assertTrue(e.getMessage().contains("the lifecycle state was not ACTIVE")); } } @@ -522,7 +522,7 @@ public void testReplace() { rpc.replace(nonexistantProject); fail("Should fail because the project doesn't exist."); } catch (ResourceManagerException e) { - assertEquals(403, e.code()); + assertEquals(403, e.getCode()); assertTrue(e.getMessage().contains("the project was not found")); } } @@ -538,7 +538,7 @@ public void testReplaceWhenDeleteRequested() { rpc.replace(anotherProject); fail("Should fail because the project is not ACTIVE."); } catch (ResourceManagerException e) { - assertEquals(400, e.code()); + assertEquals(400, e.getCode()); assertTrue(e.getMessage().contains("the lifecycle state was not ACTIVE")); } } @@ -555,7 +555,7 @@ public void testReplaceWhenDeleteInProgress() { rpc.replace(anotherProject); fail("Should fail because the project is not ACTIVE."); } catch (ResourceManagerException e) { - assertEquals(400, e.code()); + assertEquals(400, e.getCode()); assertTrue(e.getMessage().contains("the lifecycle state was not ACTIVE")); } } @@ -571,7 +571,7 @@ public void testReplaceAddingParent() { rpc.replace(anotherProject); fail("Should fail because the project's parent was modified after creation."); } catch (ResourceManagerException e) { - assertEquals(400, e.code()); + assertEquals(400, e.getCode()); assertEquals( "The server currently only supports setting the parent once " + "and does not allow unsetting it.", @@ -589,7 +589,7 @@ public void testReplaceRemovingParent() { rpc.replace(anotherProject); fail("Should fail because the project's parent was unset."); } catch (ResourceManagerException e) { - assertEquals(400, e.code()); + assertEquals(400, e.getCode()); assertEquals( "The server currently only supports setting the parent once " + "and does not allow unsetting it.", @@ -613,7 +613,7 @@ public void testUndelete() { rpc.undelete("invalid-project-id"); fail("Should fail because the project doesn't exist."); } catch (ResourceManagerException e) { - assertEquals(403, e.code()); + assertEquals(403, e.getCode()); assertTrue(e.getMessage().contains("the project was not found")); } } @@ -625,7 +625,7 @@ public void testUndeleteWhenActive() { rpc.undelete(COMPLETE_PROJECT.getProjectId()); fail("Should fail because the project is not deleted."); } catch (ResourceManagerException e) { - assertEquals(400, e.code()); + assertEquals(400, e.getCode()); assertTrue(e.getMessage().contains("lifecycle state was not DELETE_REQUESTED")); } } @@ -639,7 +639,7 @@ public void testUndeleteWhenDeleteInProgress() { rpc.undelete(COMPLETE_PROJECT.getProjectId()); fail("Should fail because the project is in the process of being deleted."); } catch (ResourceManagerException e) { - assertEquals(400, e.code()); + assertEquals(400, e.getCode()); assertTrue(e.getMessage().contains("lifecycle state was not DELETE_REQUESTED")); } } @@ -660,7 +660,7 @@ public void testReplacePolicy() { rpc.replacePolicy("nonexistent-project", POLICY); fail("Project doesn't exist."); } catch (ResourceManagerException e) { - assertEquals(403, e.code()); + assertEquals(403, e.getCode()); assertTrue(e.getMessage().contains("project was not found")); } rpc.create(PARTIAL_PROJECT); @@ -670,7 +670,7 @@ public void testReplacePolicy() { rpc.replacePolicy(PARTIAL_PROJECT.getProjectId(), invalidPolicy); fail("Invalid etag."); } catch (ResourceManagerException e) { - assertEquals(409, e.code()); + assertEquals(409, e.getCode()); assertTrue(e.getMessage().startsWith("Policy etag mismatch")); } String originalEtag = rpc.getPolicy(PARTIAL_PROJECT.getProjectId()).getEtag(); @@ -688,7 +688,7 @@ public void testTestPermissions() { rpc.testPermissions("nonexistent-project", permissions); fail("Nonexistent project."); } catch (ResourceManagerException e) { - assertEquals(403, e.code()); + assertEquals(403, e.getCode()); assertEquals("Project nonexistent-project not found.", e.getMessage()); } rpc.create(PARTIAL_PROJECT); diff --git a/google-cloud-storage/README.md b/google-cloud-storage/README.md index 223ee4d34a14..57c2d37e29e8 100644 --- a/google-cloud-storage/README.md +++ b/google-cloud-storage/README.md @@ -73,7 +73,7 @@ To make authenticated requests to Google Cloud Storage, you must create a servic import com.google.cloud.storage.Storage; import com.google.cloud.storage.StorageOptions; -Storage storage = StorageOptions.defaultInstance().service(); +Storage storage = StorageOptions.getDefaultInstance().getService(); ``` For other authentication options, see the [Authentication](https://github.com/GoogleCloudPlatform/google-cloud-java#authentication) page. diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/Blob.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/Blob.java index ebc38d6c24d9..6eac48c23093 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/Blob.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/Blob.java @@ -409,7 +409,7 @@ public Blob build() { Blob(Storage storage, BlobInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.storage = checkNotNull(storage); - this.options = storage.options(); + this.options = storage.getOptions(); } /** @@ -658,8 +658,8 @@ public WriteChannel writer(BlobWriteOption... options) { * want to require users to explicitly log in. Signing a URL requires * a service account signer. If a {@link ServiceAccountAuthCredentials} or an * {@link AppEngineAuthCredentials} was passed to - * {@link StorageOptions.Builder#authCredentials(AuthCredentials)} or the default credentials are - * being used and the environment variable {@code GOOGLE_APPLICATION_CREDENTIALS} is set, then + * {@link StorageOptions.Builder#setAuthCredentials(AuthCredentials)} or the default credentials + * are being used and the environment variable {@code GOOGLE_APPLICATION_CREDENTIALS} is set, then * {@code signUrl} will use that credentials to sign the URL. If the credentials passed to * {@link StorageOptions} do not implement {@link ServiceAccountSigner} (this is the case for * Compute Engine credentials and Google Cloud SDK credentials) then {@code signUrl} will throw an @@ -669,7 +669,8 @@ public WriteChannel writer(BlobWriteOption... options) { *

    A service account signer is looked for in the following order: *

      *
    1. The signer passed with the option {@link SignUrlOption#signWith(ServiceAccountSigner)} - *
    2. The credentials passed to {@link StorageOptions.Builder#authCredentials(AuthCredentials)} + *
    3. The credentials passed to + * {@link StorageOptions.Builder#setAuthCredentials(AuthCredentials)} *
    4. The default credentials, if no credentials were passed to {@link StorageOptions} *
    * @@ -825,7 +826,7 @@ public final int hashCode() { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); - this.storage = options.service(); + this.storage = options.getService(); } static Blob fromPb(Storage storage, StorageObject storageObject) { diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobReadChannel.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobReadChannel.java index 04b085574844..2b9019701644 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobReadChannel.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobReadChannel.java @@ -61,20 +61,20 @@ class BlobReadChannel implements ReadChannel { this.blob = blob; this.requestOptions = requestOptions; isOpen = true; - storageRpc = serviceOptions.rpc(); + storageRpc = serviceOptions.getRpc(); storageObject = blob.toPb(); } @Override public RestorableState capture() { StateImpl.Builder builder = StateImpl.builder(serviceOptions, blob, requestOptions) - .position(position) - .isOpen(isOpen) - .endOfStream(endOfStream) - .chunkSize(chunkSize); + .setPosition(position) + .setIsOpen(isOpen) + .setEndOfStream(endOfStream) + .setChunkSize(chunkSize); if (buffer != null) { - builder.position(position + bufferPos); - builder.endOfStream(false); + builder.setPosition(position + bufferPos); + builder.setEndOfStream(false); } return builder.build(); } @@ -108,7 +108,13 @@ public void seek(long position) throws IOException { } @Override + @Deprecated public void chunkSize(int chunkSize) { + setChunkSize(chunkSize); + } + + @Override + public void setChunkSize(int chunkSize) { this.chunkSize = chunkSize <= 0 ? DEFAULT_CHUNK_SIZE : chunkSize; } @@ -126,7 +132,8 @@ public int read(ByteBuffer byteBuffer) throws IOException { public Tuple call() { return storageRpc.read(storageObject, requestOptions, position, toRead); } - }, serviceOptions.retryParams(), StorageImpl.EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), StorageImpl.EXCEPTION_HANDLER, + serviceOptions.getClock()); if (result.y().length > 0 && lastEtag != null && !Objects.equals(result.x(), lastEtag)) { StringBuilder messageBuilder = new StringBuilder(); messageBuilder.append("Blob ").append(blob).append(" was updated while reading"); @@ -196,27 +203,27 @@ private Builder(StorageOptions options, BlobId blob, Map r this.requestOptions = reqOptions; } - Builder lastEtag(String lastEtag) { + Builder setLastEtag(String lastEtag) { this.lastEtag = lastEtag; return this; } - Builder position(long position) { + Builder setPosition(long position) { this.position = position; return this; } - Builder isOpen(boolean isOpen) { + Builder setIsOpen(boolean isOpen) { this.isOpen = isOpen; return this; } - Builder endOfStream(boolean endOfStream) { + Builder setEndOfStream(boolean endOfStream) { this.endOfStream = endOfStream; return this; } - Builder chunkSize(int chunkSize) { + Builder setChunkSize(int chunkSize) { this.chunkSize = chunkSize; return this; } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobWriteChannel.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobWriteChannel.java index b6687037f0b9..18cf3a559833 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobWriteChannel.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/BlobWriteChannel.java @@ -47,16 +47,16 @@ protected void flushBuffer(final int length, final boolean last) { runWithRetries(callable(new Runnable() { @Override public void run() { - options().rpc().write(uploadId(), buffer(), 0, position(), length, last); + getOptions().getRpc().write(getUploadId(), getBuffer(), 0, getPosition(), length, last); } - }), options().retryParams(), StorageImpl.EXCEPTION_HANDLER, options().clock()); + }), getOptions().getRetryParams(), StorageImpl.EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelper.RetryHelperException e) { throw StorageException.translateAndThrow(e); } } protected StateImpl.Builder stateBuilder() { - return StateImpl.builder(options(), entity(), uploadId()); + return StateImpl.builder(getOptions(), getEntity(), getUploadId()); } private static String open(final StorageOptions options, final BlobInfo blob, @@ -65,9 +65,9 @@ private static String open(final StorageOptions options, final BlobInfo blob, return runWithRetries(new Callable() { @Override public String call() { - return options.rpc().open(blob.toPb(), optionsMap); + return options.getRpc().open(blob.toPb(), optionsMap); } - }, options.retryParams(), StorageImpl.EXCEPTION_HANDLER, options.clock()); + }, options.getRetryParams(), StorageImpl.EXCEPTION_HANDLER, options.getClock()); } catch (RetryHelper.RetryHelperException e) { throw StorageException.translateAndThrow(e); } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/Bucket.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/Bucket.java index 19a6034b5e2c..ffde1389fab8 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/Bucket.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/Bucket.java @@ -634,7 +634,7 @@ public Bucket build() { Bucket(Storage storage, BucketInfo.BuilderImpl infoBuilder) { super(infoBuilder); this.storage = checkNotNull(storage); - this.options = storage.options(); + this.options = storage.getOptions(); } /** @@ -1141,7 +1141,7 @@ public final int hashCode() { private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); - this.storage = options.service(); + this.storage = options.getService(); } static Bucket fromPb(Storage storage, com.google.api.services.storage.model.Bucket bucketPb) { diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/CopyWriter.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/CopyWriter.java index ec08bca60b91..962f4d05f69e 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/CopyWriter.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/CopyWriter.java @@ -55,7 +55,7 @@ public class CopyWriter implements Restorable { CopyWriter(StorageOptions serviceOptions, RewriteResponse rewriteResponse) { this.serviceOptions = serviceOptions; this.rewriteResponse = rewriteResponse; - this.storageRpc = serviceOptions.rpc(); + this.storageRpc = serviceOptions.getRpc(); } /** @@ -93,7 +93,7 @@ public Blob getResult() { while (!isDone()) { copyChunk(); } - return Blob.fromPb(serviceOptions.service(), rewriteResponse.result); + return Blob.fromPb(serviceOptions.getService(), rewriteResponse.result); } /** @@ -147,7 +147,8 @@ public void copyChunk() { public RewriteResponse call() { return storageRpc.continueRewrite(rewriteResponse); } - }, serviceOptions.retryParams(), StorageImpl.EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), StorageImpl.EXCEPTION_HANDLER, + serviceOptions.getClock()); } catch (RetryHelper.RetryHelperException e) { throw StorageException.translateAndThrow(e); } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/Cors.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/Cors.java index 8f8766adbaa0..29840f5079de 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/Cors.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/Cors.java @@ -118,10 +118,15 @@ public boolean equals(Object obj) { @Override public String toString() { - return value(); + return getValue(); } + @Deprecated public String value() { + return getValue(); + } + + public String getValue() { return value; } } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/Storage.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/Storage.java index 01dfdc5cd654..d08de6114920 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/Storage.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/Storage.java @@ -104,7 +104,13 @@ enum BucketField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -144,7 +150,13 @@ enum BlobField implements FieldSelector { } @Override + @Deprecated public String selector() { + return getSelector(); + } + + @Override + public String getSelector() { return selector; } } @@ -2026,8 +2038,8 @@ public static Builder newBuilder() { * but also don't want to require users to explicitly log in. Signing a URL requires * a service account signer. If a {@link ServiceAccountAuthCredentials} or an * {@link AppEngineAuthCredentials} was passed to - * {@link StorageOptions.Builder#authCredentials(AuthCredentials)} or the default credentials are - * being used and the environment variable {@code GOOGLE_APPLICATION_CREDENTIALS} is set, then + * {@link StorageOptions.Builder#setAuthCredentials(AuthCredentials)} or the default credentials + * are being used and the environment variable {@code GOOGLE_APPLICATION_CREDENTIALS} is set, then * {@code signUrl} will use that credentials to sign the URL. If the credentials passed to * {@link StorageOptions} do not implement {@link ServiceAccountSigner} (this is the case for * Compute Engine credentials and Google Cloud SDK credentials) then {@code signUrl} will throw an @@ -2037,7 +2049,8 @@ public static Builder newBuilder() { *

    A service account signer is looked for in the following order: *

      *
    1. The signer passed with the option {@link SignUrlOption#signWith(ServiceAccountSigner)} - *
    2. The credentials passed to {@link StorageOptions.Builder#authCredentials(AuthCredentials)} + *
    3. The credentials passed to + * {@link StorageOptions.Builder#setAuthCredentials(AuthCredentials)} *
    4. The default credentials, if no credentials were passed to {@link StorageOptions} *
    * diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageBatch.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageBatch.java index 1153d8015453..bb23aa98bd38 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageBatch.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageBatch.java @@ -60,22 +60,22 @@ public class StorageBatch { StorageBatch(StorageOptions options) { this.options = options; - this.storageRpc = options.rpc(); + this.storageRpc = options.getRpc(); this.batch = storageRpc.createBatch(); } @VisibleForTesting - Object batch() { + Object getBatch() { return batch; } @VisibleForTesting - StorageRpc storageRpc() { + StorageRpc getStorageRpc() { return storageRpc; } @VisibleForTesting - StorageOptions options() { + StorageOptions getOptions() { return options; } @@ -161,7 +161,7 @@ public void onSuccess(Void response) { @Override public void onFailure(GoogleJsonError googleJsonError) { StorageException serviceException = new StorageException(googleJsonError); - if (serviceException.code() == HTTP_NOT_FOUND) { + if (serviceException.getCode() == HTTP_NOT_FOUND) { result.success(false); } else { result.error(serviceException); @@ -175,13 +175,14 @@ private RpcBatch.Callback createGetCallback(final StorageOptions return new RpcBatch.Callback() { @Override public void onSuccess(StorageObject response) { - result.success(response == null ? null : Blob.fromPb(serviceOptions.service(), response)); + result.success( + response == null ? null : Blob.fromPb(serviceOptions.getService(), response)); } @Override public void onFailure(GoogleJsonError googleJsonError) { StorageException serviceException = new StorageException(googleJsonError); - if (serviceException.code() == HTTP_NOT_FOUND) { + if (serviceException.getCode() == HTTP_NOT_FOUND) { result.success(null); } else { result.error(serviceException); @@ -195,7 +196,8 @@ private RpcBatch.Callback createUpdateCallback(final StorageOptio return new RpcBatch.Callback() { @Override public void onSuccess(StorageObject response) { - result.success(response == null ? null : Blob.fromPb(serviceOptions.service(), response)); + result.success( + response == null ? null : Blob.fromPb(serviceOptions.getService(), response)); } @Override diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageException.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageException.java index e0dcd8df0946..16b2332b1b5c 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageException.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageException.java @@ -62,7 +62,7 @@ public StorageException(GoogleJsonError error) { } @Override - protected Set retryableErrors() { + protected Set getRetryableErrors() { return RETRYABLE_ERRORS; } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java index 49cf62baca71..a96cde57d09d 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageImpl.java @@ -90,7 +90,7 @@ public Boolean apply(Tuple tuple) { StorageImpl(StorageOptions options) { super(options); - storageRpc = options.rpc(); + storageRpc = options.getRpc(); } @Override @@ -104,7 +104,7 @@ public Bucket create(BucketInfo bucketInfo, BucketTargetOption... options) { public com.google.api.services.storage.model.Bucket call() { return storageRpc.create(bucketPb, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -146,7 +146,7 @@ public StorageObject call() { return storageRpc.create(blobPb, firstNonNull(content, new ByteArrayInputStream(EMPTY_BYTE_ARRAY)), optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -163,7 +163,7 @@ public Bucket get(String bucket, BucketGetOption... options) { public com.google.api.services.storage.model.Bucket call() { return storageRpc.get(bucketPb, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Bucket.fromPb(this, answer); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); @@ -185,7 +185,7 @@ public Blob get(BlobId blob, BlobGetOption... options) { public StorageObject call() { return storageRpc.get(storedObject, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return storageObject == null ? null : Blob.fromPb(this, storageObject); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); @@ -212,7 +212,13 @@ private static class BucketPageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listBuckets(serviceOptions, requestOptions); } } @@ -233,19 +239,25 @@ private static class BlobPageFetcher implements NextPageFetcher { } @Override + @Deprecated public Page nextPage() { + return getNextPage(); + } + + @Override + public Page getNextPage() { return listBlobs(bucket, serviceOptions, requestOptions); } } @Override public Page list(BucketListOption... options) { - return listBuckets(options(), optionMap(options)); + return listBuckets(getOptions(), optionMap(options)); } @Override public Page list(final String bucket, BlobListOption... options) { - return listBlobs(bucket, options(), optionMap(options)); + return listBlobs(bucket, getOptions(), optionMap(options)); } private static Page listBuckets(final StorageOptions serviceOptions, @@ -255,16 +267,16 @@ private static Page listBuckets(final StorageOptions serviceOptions, new Callable>>() { @Override public Tuple> call() { - return serviceOptions.rpc().list(optionsMap); + return serviceOptions.getRpc().list(optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable buckets = result.y() == null ? ImmutableList.of() : Iterables.transform(result.y(), new Function() { @Override public Bucket apply(com.google.api.services.storage.model.Bucket bucketPb) { - return Bucket.fromPb(serviceOptions.service(), bucketPb); + return Bucket.fromPb(serviceOptions.getService(), bucketPb); } }); return new PageImpl<>( @@ -282,9 +294,9 @@ private static Page listBlobs(final String bucket, new Callable>>() { @Override public Tuple> call() { - return serviceOptions.rpc().list(bucket, optionsMap); + return serviceOptions.getRpc().list(bucket, optionsMap); } - }, serviceOptions.retryParams(), EXCEPTION_HANDLER, serviceOptions.clock()); + }, serviceOptions.getRetryParams(), EXCEPTION_HANDLER, serviceOptions.getClock()); String cursor = result.x(); Iterable blobs = result.y() == null @@ -292,7 +304,7 @@ public Tuple> call() { : Iterables.transform(result.y(), new Function() { @Override public Blob apply(StorageObject storageObject) { - return Blob.fromPb(serviceOptions.service(), storageObject); + return Blob.fromPb(serviceOptions.getService(), storageObject); } }); return new PageImpl<>( @@ -315,7 +327,7 @@ public Bucket update(BucketInfo bucketInfo, BucketTargetOption... options) { public com.google.api.services.storage.model.Bucket call() { return storageRpc.patch(bucketPb, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -331,7 +343,7 @@ public Blob update(BlobInfo blobInfo, BlobTargetOption... options) { public StorageObject call() { return storageRpc.patch(storageObject, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -352,7 +364,7 @@ public boolean delete(String bucket, BucketSourceOption... options) { public Boolean call() { return storageRpc.delete(bucketPb, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -373,7 +385,7 @@ public boolean delete(BlobId blob, BlobSourceOption... options) { public Boolean call() { return storageRpc.delete(storageObject, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -404,7 +416,7 @@ public Blob compose(final ComposeRequest composeRequest) { public StorageObject call() { return storageRpc.compose(sources, target, targetOptions); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -427,8 +439,8 @@ public RewriteResponse call() { copyRequest.overrideInfo(), targetObject, targetOptions, copyRequest.getMegabytesCopiedPerChunk())); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); - return new CopyWriter(options(), rewriteResponse); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); + return new CopyWriter(getOptions(), rewriteResponse); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -449,7 +461,7 @@ public byte[] readAllBytes(BlobId blob, BlobSourceOption... options) { public byte[] call() { return storageRpc.load(storageObject, optionsMap); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -457,19 +469,19 @@ public byte[] call() { @Override public StorageBatch batch() { - return new StorageBatch(this.options()); + return new StorageBatch(this.getOptions()); } @Override public ReadChannel reader(String bucket, String blob, BlobSourceOption... options) { Map optionsMap = optionMap(options); - return new BlobReadChannel(options(), BlobId.of(bucket, blob), optionsMap); + return new BlobReadChannel(getOptions(), BlobId.of(bucket, blob), optionsMap); } @Override public ReadChannel reader(BlobId blob, BlobSourceOption... options) { Map optionsMap = optionMap(blob, options); - return new BlobReadChannel(options(), blob, optionsMap); + return new BlobReadChannel(getOptions(), blob, optionsMap); } @Override @@ -480,7 +492,7 @@ public BlobWriteChannel writer(BlobInfo blobInfo, BlobWriteOption... options) { private BlobWriteChannel writer(BlobInfo blobInfo, BlobTargetOption... options) { final Map optionsMap = optionMap(blobInfo, options); - return new BlobWriteChannel(options(), blobInfo, optionsMap); + return new BlobWriteChannel(getOptions(), blobInfo, optionsMap); } @Override @@ -492,9 +504,9 @@ public URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, SignUrlOptio ServiceAccountSigner authCredentials = (ServiceAccountSigner) optionMap.get(SignUrlOption.Option.SERVICE_ACCOUNT_CRED); if (authCredentials == null) { - checkState(this.options().authCredentials() instanceof ServiceAccountSigner, + checkState(this.getOptions().getAuthCredentials() instanceof ServiceAccountSigner, "Signing key was not provided and could not be derived"); - authCredentials = (ServiceAccountSigner) this.options().authCredentials(); + authCredentials = (ServiceAccountSigner) this.getOptions().getAuthCredentials(); } // construct signature - see https://cloud.google.com/storage/docs/access-control#Signed-URLs StringBuilder stBuilder = new StringBuilder(); @@ -515,7 +527,7 @@ public URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, SignUrlOptio } stBuilder.append('\n'); long expiration = TimeUnit.SECONDS.convert( - options().clock().millis() + unit.toMillis(duration), TimeUnit.MILLISECONDS); + getOptions().getClock().millis() + unit.toMillis(duration), TimeUnit.MILLISECONDS); stBuilder.append(expiration).append('\n'); StringBuilder path = new StringBuilder(); if (!blobInfo.getBucket().startsWith("/")) { @@ -536,7 +548,7 @@ public URL signUrl(BlobInfo blobInfo, long duration, TimeUnit unit, SignUrlOptio stBuilder = new StringBuilder("https://storage.googleapis.com").append(path); String signature = URLEncoder.encode(BaseEncoding.base64().encode(signatureBytes), UTF_8.name()); - stBuilder.append("?GoogleAccessId=").append(authCredentials.account()); + stBuilder.append("?GoogleAccessId=").append(authCredentials.getAccount()); stBuilder.append("&Expires=").append(expiration); stBuilder.append("&Signature=").append(signature); return new URL(stBuilder.toString()); @@ -631,7 +643,7 @@ public Acl getAcl(final String bucket, final Entity entity) { public BucketAccessControl call() { return storageRpc.getAcl(bucket, entity.toPb()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Acl.fromPb(answer); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); @@ -646,7 +658,7 @@ public boolean deleteAcl(final String bucket, final Entity entity) { public Boolean call() { return storageRpc.deleteAcl(bucket, entity.toPb()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -661,7 +673,7 @@ public Acl createAcl(String bucket, Acl acl) { public BucketAccessControl call() { return storageRpc.createAcl(aclPb); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -676,7 +688,7 @@ public Acl updateAcl(String bucket, Acl acl) { public BucketAccessControl call() { return storageRpc.patchAcl(aclPb); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -690,7 +702,7 @@ public List listAcls(final String bucket) { public List call() { return storageRpc.listAcls(bucket); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return Lists.transform(answer, Acl.FROM_BUCKET_PB_FUNCTION); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); @@ -705,7 +717,7 @@ public Acl getDefaultAcl(final String bucket, final Entity entity) { public ObjectAccessControl call() { return storageRpc.getDefaultAcl(bucket, entity.toPb()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Acl.fromPb(answer); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); @@ -720,7 +732,7 @@ public boolean deleteDefaultAcl(final String bucket, final Entity entity) { public Boolean call() { return storageRpc.deleteDefaultAcl(bucket, entity.toPb()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -735,7 +747,7 @@ public Acl createDefaultAcl(String bucket, Acl acl) { public ObjectAccessControl call() { return storageRpc.createDefaultAcl(aclPb); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -750,7 +762,7 @@ public Acl updateDefaultAcl(String bucket, Acl acl) { public ObjectAccessControl call() { return storageRpc.patchDefaultAcl(aclPb); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -764,7 +776,7 @@ public List listDefaultAcls(final String bucket) { public List call() { return storageRpc.listDefaultAcls(bucket); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return Lists.transform(answer, Acl.FROM_OBJECT_PB_FUNCTION); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); @@ -780,7 +792,7 @@ public ObjectAccessControl call() { return storageRpc.getAcl( blob.getBucket(), blob.getName(), blob.getGeneration(), entity.toPb()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return answer == null ? null : Acl.fromPb(answer); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); @@ -796,7 +808,7 @@ public Boolean call() { return storageRpc.deleteAcl( blob.getBucket(), blob.getName(), blob.getGeneration(), entity.toPb()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -814,7 +826,7 @@ public Acl createAcl(final BlobId blob, final Acl acl) { public ObjectAccessControl call() { return storageRpc.createAcl(aclPb); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -832,7 +844,7 @@ public Acl updateAcl(BlobId blob, Acl acl) { public ObjectAccessControl call() { return storageRpc.patchAcl(aclPb); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock())); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock())); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); } @@ -846,7 +858,7 @@ public List listAcls(final BlobId blob) { public List call() { return storageRpc.listAcls(blob.getBucket(), blob.getName(), blob.getGeneration()); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); return Lists.transform(answer, Acl.FROM_OBJECT_PB_FUNCTION); } catch (RetryHelperException e) { throw StorageException.translateAndThrow(e); diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageOptions.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageOptions.java index 8d9bcb748b5f..37630e2ace42 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageOptions.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/StorageOptions.java @@ -70,25 +70,33 @@ private StorageOptions(Builder builder) { } @Override - protected StorageFactory defaultServiceFactory() { + protected StorageFactory getDefaultServiceFactory() { return DefaultStorageFactory.INSTANCE; } @Override - protected StorageRpcFactory defaultRpcFactory() { + protected StorageRpcFactory getDefaultRpcFactory() { return DefaultStorageRpcFactory.INSTANCE; } @Override - protected Set scopes() { + protected Set getScopes() { return SCOPES; } /** * Returns a default {@code StorageOptions} instance. */ + @Deprecated public static StorageOptions defaultInstance() { - return builder().build(); + return getDefaultInstance(); + } + + /** + * Returns a default {@code StorageOptions} instance. + */ + public static StorageOptions getDefaultInstance() { + return newBuilder().build(); } @SuppressWarnings("unchecked") @@ -107,7 +115,12 @@ public boolean equals(Object obj) { return obj instanceof StorageOptions && baseEquals((StorageOptions) obj); } + @Deprecated public static Builder builder() { + return newBuilder(); + } + + public static Builder newBuilder() { return new Builder(); } } diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/package-info.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/package-info.java index 7c0cc3f588c7..9a705ba1a51e 100644 --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/package-info.java +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/package-info.java @@ -22,7 +22,7 @@ * * CreateBlob.java. *
     {@code
    - * Storage storage = StorageOptions.defaultInstance().service();
    + * Storage storage = StorageOptions.getDefaultInstance().getService();
      * BlobId blobId = BlobId.of("bucket", "blob_name");
      * BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
      * Blob blob = storage.create(blobInfo, "Hello, Cloud Storage!".getBytes(UTF_8));
    @@ -33,7 +33,7 @@
      * 
      * UpdateBlob.java.
      * 
     {@code
    - * Storage storage = StorageOptions.defaultInstance().service();
    + * Storage storage = StorageOptions.getDefaultInstance().getService();
      * BlobId blobId = BlobId.of("bucket", "blob_name");
      * Blob blob = storage.get(blobId);
      * if (blob != null) {
    diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/spi/DefaultStorageRpc.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/spi/DefaultStorageRpc.java
    index 14271274bf23..91563610bbdd 100644
    --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/spi/DefaultStorageRpc.java
    +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/spi/DefaultStorageRpc.java
    @@ -99,12 +99,12 @@ public class DefaultStorageRpc implements StorageRpc {
       private static final long MEGABYTE = 1024L * 1024L;
     
       public DefaultStorageRpc(StorageOptions options) {
    -    HttpTransport transport = options.httpTransportFactory().create();
    -    HttpRequestInitializer initializer = options.httpRequestInitializer();
    +    HttpTransport transport = options.getHttpTransportFactory().create();
    +    HttpRequestInitializer initializer = options.getHttpRequestInitializer();
         this.options = options;
         storage = new Storage.Builder(transport, new JacksonFactory(), initializer)
    -        .setRootUrl(options.host())
    -        .setApplicationName(options.applicationName())
    +        .setRootUrl(options.getHost())
    +        .setApplicationName(options.getApplicationName())
             .build();
       }
     
    @@ -223,7 +223,7 @@ private static void setEncryptionHeaders(HttpHeaders headers, String headerPrefi
       public Bucket create(Bucket bucket, Map options) {
         try {
           return storage.buckets()
    -          .insert(this.options.projectId(), bucket)
    +          .insert(this.options.getProjectId(), bucket)
               .setProjection(DEFAULT_PROJECTION)
               .setPredefinedAcl(PREDEFINED_ACL.getString(options))
               .setPredefinedDefaultObjectAcl(PREDEFINED_DEFAULT_OBJECT_ACL.getString(options))
    @@ -258,7 +258,7 @@ public StorageObject create(StorageObject storageObject, final InputStream conte
       public Tuple> list(Map options) {
         try {
           Buckets buckets = storage.buckets()
    -          .list(this.options.projectId())
    +          .list(this.options.getProjectId())
               .setProjection(DEFAULT_PROJECTION)
               .setPrefix(PREFIX.getString(options))
               .setMaxResults(MAX_RESULTS.getLong(options))
    @@ -320,7 +320,7 @@ public Bucket get(Bucket bucket, Map options) {
               .execute();
         } catch (IOException ex) {
           StorageException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return null;
           }
           throw serviceException;
    @@ -346,7 +346,7 @@ public StorageObject get(StorageObject object, Map options) {
           return getCall(object, options).execute();
         } catch (IOException ex) {
           StorageException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return null;
           }
           throw serviceException;
    @@ -401,7 +401,7 @@ public boolean delete(Bucket bucket, Map options) {
           return true;
         } catch (IOException ex) {
           StorageException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return false;
           }
           throw serviceException;
    @@ -426,7 +426,7 @@ public boolean delete(StorageObject blob, Map options) {
           return true;
         } catch (IOException ex) {
           StorageException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return false;
           }
           throw serviceException;
    @@ -526,7 +526,7 @@ public Tuple read(StorageObject from, Map options, lo
           return Tuple.of(etag, output.toByteArray());
         } catch (IOException ex) {
           StorageException serviceException = translate(ex);
    -      if (serviceException.code() == SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
    +      if (serviceException.getCode() == SC_REQUESTED_RANGE_NOT_SATISFIABLE) {
             return Tuple.of(null, new byte[0]);
           }
           throw serviceException;
    @@ -681,7 +681,7 @@ public BucketAccessControl getAcl(String bucket, String entity) {
           return storage.bucketAccessControls().get(bucket, entity).execute();
         } catch (IOException ex) {
           StorageException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return null;
           }
           throw serviceException;
    @@ -695,7 +695,7 @@ public boolean deleteAcl(String bucket, String entity) {
           return true;
         } catch (IOException ex) {
           StorageException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return false;
           }
           throw serviceException;
    @@ -736,7 +736,7 @@ public ObjectAccessControl getDefaultAcl(String bucket, String entity) {
           return storage.defaultObjectAccessControls().get(bucket, entity).execute();
         } catch (IOException ex) {
           StorageException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return null;
           }
           throw serviceException;
    @@ -750,7 +750,7 @@ public boolean deleteDefaultAcl(String bucket, String entity) {
           return true;
         } catch (IOException ex) {
           StorageException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return false;
           }
           throw serviceException;
    @@ -794,7 +794,7 @@ public ObjectAccessControl getAcl(String bucket, String object, Long generation,
               .execute();
         } catch (IOException ex) {
           StorageException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return null;
           }
           throw serviceException;
    @@ -810,7 +810,7 @@ public boolean deleteAcl(String bucket, String object, Long generation, String e
           return true;
         } catch (IOException ex) {
           StorageException serviceException = translate(ex);
    -      if (serviceException.code() == HTTP_NOT_FOUND) {
    +      if (serviceException.getCode() == HTTP_NOT_FOUND) {
             return false;
           }
           throw serviceException;
    diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/RemoteStorageHelper.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/RemoteStorageHelper.java
    index c24b5b75a4a6..19df39e2c0a9 100644
    --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/RemoteStorageHelper.java
    +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/RemoteStorageHelper.java
    @@ -40,12 +40,13 @@
     /**
      * Utility to create a remote storage configuration for testing. Storage options can be obtained via
      * the {@link #getOptions()} ()} method. Returned options have custom
    - * {@link StorageOptions#retryParams()}: {@link RetryParams#retryMaxAttempts()} is {@code 10},
    - * {@link RetryParams#retryMinAttempts()} is {@code 6}, {@link RetryParams#maxRetryDelayMillis()} is
    - * {@code 30000}, {@link RetryParams#totalRetryPeriodMillis()} is {@code 120000} and
    - * {@link RetryParams#initialRetryDelayMillis()} is {@code 250}.
    - * {@link StorageOptions#connectTimeout()} and {@link StorageOptions#readTimeout()} are both set
    - * to {@code 60000}.
    + * {@link StorageOptions#getRetryParams()}: {@link RetryParams#getRetryMaxAttempts()} is {@code 10},
    + * {@link RetryParams#getRetryMinAttempts()} is {@code 6},
    + * {@link RetryParams#getMaxRetryDelayMillis()} is {@code 30000},
    + * {@link RetryParams#getTotalRetryPeriodMillis()} is {@code 120000} and
    + * {@link RetryParams#getInitialRetryDelayMillis()} is {@code 250}.
    + * {@link StorageOptions#getConnectTimeout()} and {@link StorageOptions#getReadTimeout()} are both
    + * set to {@code 60000}.
      */
     public class RemoteStorageHelper {
     
    @@ -131,12 +132,12 @@ public static String generateBucketName() {
       public static RemoteStorageHelper create(String projectId, InputStream keyStream)
           throws StorageHelperException {
         try {
    -      StorageOptions storageOptions = StorageOptions.builder()
    -          .authCredentials(AuthCredentials.createForJson(keyStream))
    -          .projectId(projectId)
    -          .retryParams(retryParams())
    -          .connectTimeout(60000)
    -          .readTimeout(60000)
    +      StorageOptions storageOptions = StorageOptions.newBuilder()
    +          .setAuthCredentials(AuthCredentials.createForJson(keyStream))
    +          .setProjectId(projectId)
    +          .setRetryParams(retryParams())
    +          .setConnectTimeout(60000)
    +          .setReadTimeout(60000)
               .build();
           return new RemoteStorageHelper(storageOptions);
         } catch (IOException ex) {
    @@ -152,21 +153,21 @@ public static RemoteStorageHelper create(String projectId, InputStream keyStream
        * credentials.
        */
       public static RemoteStorageHelper create() throws StorageHelperException {
    -    StorageOptions storageOptions = StorageOptions.builder()
    -        .retryParams(retryParams())
    -        .connectTimeout(60000)
    -        .readTimeout(60000)
    +    StorageOptions storageOptions = StorageOptions.newBuilder()
    +        .setRetryParams(retryParams())
    +        .setConnectTimeout(60000)
    +        .setReadTimeout(60000)
             .build();
         return new RemoteStorageHelper(storageOptions);
       }
     
       private static RetryParams retryParams() {
    -    return RetryParams.builder()
    -        .retryMaxAttempts(10)
    -        .retryMinAttempts(6)
    -        .maxRetryDelayMillis(30000)
    -        .totalRetryPeriodMillis(120000)
    -        .initialRetryDelayMillis(250)
    +    return RetryParams.newBuilder()
    +        .setRetryMaxAttempts(10)
    +        .setRetryMinAttempts(6)
    +        .setMaxRetryDelayMillis(30000)
    +        .setTotalRetryPeriodMillis(120000)
    +        .setInitialRetryDelayMillis(250)
             .build();
       }
     
    @@ -183,14 +184,14 @@ public DeleteBucketTask(Storage storage, String bucket) {
         @Override
         public Boolean call() {
           while (true) {
    -        for (BlobInfo info : storage.list(bucket, BlobListOption.versions(true)).values()) {
    +        for (BlobInfo info : storage.list(bucket, BlobListOption.versions(true)).getValues()) {
               storage.delete(info.getBlobId());
             }
             try {
               storage.delete(bucket);
               return true;
             } catch (StorageException e) {
    -          if (e.code() == 409) {
    +          if (e.getCode() == 409) {
                 try {
                   Thread.sleep(500);
                 } catch (InterruptedException interruptedException) {
    diff --git a/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/package-info.java b/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/package-info.java
    index 160add370e62..f3528bb13166 100644
    --- a/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/package-info.java
    +++ b/google-cloud-storage/src/main/java/com/google/cloud/storage/testing/package-info.java
    @@ -22,7 +22,7 @@
      * 

    Before the test: *

     {@code
      * RemoteStorageHelper helper = RemoteStorageHelper.create();
    - * Storage storage = helper.getOptions().service();
    + * Storage storage = helper.getOptions().getService();
      * String bucket = RemoteStorageHelper.generateBucketName();
      * storage.create(BucketInfo.of(bucket));
      * } 
    diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobReadChannelTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobReadChannelTest.java index a108e5f167ce..e8980a8c2626 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobReadChannelTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobReadChannelTest.java @@ -65,10 +65,10 @@ public void setUp() { storageRpcMock = createMock(StorageRpc.class); expect(rpcFactoryMock.create(anyObject(StorageOptions.class))).andReturn(storageRpcMock); replay(rpcFactoryMock); - options = StorageOptions.builder() - .projectId("projectId") - .serviceRpcFactory(rpcFactoryMock) - .retryParams(RetryParams.noRetries()) + options = StorageOptions.newBuilder() + .setProjectId("projectId") + .setServiceRpcFactory(rpcFactoryMock) + .setRetryParams(RetryParams.noRetries()) .build(); } @@ -105,7 +105,7 @@ public void testReadBuffered() throws IOException { @Test public void testReadBig() throws IOException { reader = new BlobReadChannel(options, BLOB_ID, EMPTY_RPC_OPTIONS); - reader.chunkSize(CUSTOM_CHUNK_SIZE); + reader.setChunkSize(CUSTOM_CHUNK_SIZE); byte[] firstResult = randomByteArray(DEFAULT_CHUNK_SIZE); byte[] secondResult = randomByteArray(DEFAULT_CHUNK_SIZE); ByteBuffer firstReadBuffer = ByteBuffer.allocate(DEFAULT_CHUNK_SIZE); diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobTest.java index b070ebb0b1c4..718e9edfc635 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobTest.java @@ -135,7 +135,7 @@ public void tearDown() throws Exception { } private void initializeExpectedBlob(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(BLOB_INFO)); } @@ -148,7 +148,7 @@ private void initializeBlob() { public void testExists_True() throws Exception { initializeExpectedBlob(1); Storage.BlobGetOption[] expectedOptions = {Storage.BlobGetOption.fields()}; - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.get(expectedBlob.getBlobId(), expectedOptions)).andReturn(expectedBlob); replay(storage); initializeBlob(); @@ -158,7 +158,7 @@ public void testExists_True() throws Exception { @Test public void testExists_False() throws Exception { Storage.BlobGetOption[] expectedOptions = {Storage.BlobGetOption.fields()}; - expect(storage.options()).andReturn(null); + expect(storage.getOptions()).andReturn(null); expect(storage.get(BLOB_INFO.getBlobId(), expectedOptions)).andReturn(null); replay(storage); initializeBlob(); @@ -169,7 +169,7 @@ public void testExists_False() throws Exception { public void testContent() throws Exception { initializeExpectedBlob(2); byte[] content = {1, 2}; - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.readAllBytes(BLOB_INFO.getBlobId())).andReturn(content); replay(storage); initializeBlob(); @@ -180,7 +180,7 @@ public void testContent() throws Exception { public void testContentWithDecryptionKey() throws Exception { initializeExpectedBlob(2); byte[] content = {1, 2}; - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.readAllBytes(BLOB_INFO.getBlobId(), Storage.BlobSourceOption.decryptionKey(BASE64_KEY))) .andReturn(content).times(2); @@ -194,7 +194,7 @@ public void testContentWithDecryptionKey() throws Exception { public void testReload() throws Exception { initializeExpectedBlob(2); Blob expectedReloadedBlob = expectedBlob.toBuilder().setCacheControl("c").build(); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.get(BLOB_INFO.getBlobId(), new Storage.BlobGetOption[0])) .andReturn(expectedReloadedBlob); replay(storage); @@ -206,7 +206,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedBlob(1); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.get(BLOB_INFO.getBlobId(), new Storage.BlobGetOption[0])).andReturn(null); replay(storage); initializeBlob(); @@ -219,7 +219,7 @@ public void testReloadWithOptions() throws Exception { initializeExpectedBlob(2); Blob expectedReloadedBlob = expectedBlob.toBuilder().setCacheControl("c").build(); Storage.BlobGetOption[] options = {Storage.BlobGetOption.metagenerationMatch(42L)}; - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.get(BLOB_INFO.getBlobId(), options)).andReturn(expectedReloadedBlob); replay(storage); initializeBlob(); @@ -231,7 +231,7 @@ public void testReloadWithOptions() throws Exception { public void testUpdate() throws Exception { initializeExpectedBlob(2); Blob expectedUpdatedBlob = expectedBlob.toBuilder().setCacheControl("c").build(); - expect(storage.options()).andReturn(mockOptions).times(2); + expect(storage.getOptions()).andReturn(mockOptions).times(2); expect(storage.update(eq(expectedUpdatedBlob), new Storage.BlobTargetOption[0])) .andReturn(expectedUpdatedBlob); replay(storage); @@ -244,7 +244,7 @@ public void testUpdate() throws Exception { @Test public void testDelete() throws Exception { initializeExpectedBlob(2); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.delete(BLOB_INFO.getBlobId(), new Storage.BlobSourceOption[0])).andReturn(true); replay(storage); initializeBlob(); @@ -257,7 +257,7 @@ public void testCopyToBucket() throws Exception { BlobInfo target = BlobInfo.newBuilder(BlobId.of("bt", "n")).build(); CopyWriter copyWriter = createMock(CopyWriter.class); Capture capturedCopyRequest = Capture.newInstance(); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.copy(capture(capturedCopyRequest))).andReturn(copyWriter); replay(storage); initializeBlob(); @@ -276,7 +276,7 @@ public void testCopyTo() throws Exception { BlobInfo target = BlobInfo.newBuilder(BlobId.of("bt", "nt")).build(); CopyWriter copyWriter = createMock(CopyWriter.class); Capture capturedCopyRequest = Capture.newInstance(); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.copy(capture(capturedCopyRequest))).andReturn(copyWriter); replay(storage); initializeBlob(); @@ -296,7 +296,7 @@ public void testCopyToBlobId() throws Exception { BlobId targetId = BlobId.of("bt", "nt"); CopyWriter copyWriter = createMock(CopyWriter.class); Capture capturedCopyRequest = Capture.newInstance(); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.copy(capture(capturedCopyRequest))).andReturn(copyWriter); replay(storage); initializeBlob(); @@ -313,7 +313,7 @@ public void testCopyToBlobId() throws Exception { public void testReader() throws Exception { initializeExpectedBlob(2); ReadChannel channel = createMock(ReadChannel.class); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.reader(BLOB_INFO.getBlobId())).andReturn(channel); replay(storage); initializeBlob(); @@ -324,8 +324,9 @@ public void testReader() throws Exception { public void testReaderWithDecryptionKey() throws Exception { initializeExpectedBlob(2); ReadChannel channel = createMock(ReadChannel.class); - expect(storage.options()).andReturn(mockOptions); - expect(storage.reader(BLOB_INFO.getBlobId(), Storage.BlobSourceOption.decryptionKey(BASE64_KEY))) + expect(storage.getOptions()).andReturn(mockOptions); + expect(storage.reader(BLOB_INFO.getBlobId(), + Storage.BlobSourceOption.decryptionKey(BASE64_KEY))) .andReturn(channel).times(2); replay(storage); initializeBlob(); @@ -337,7 +338,7 @@ public void testReaderWithDecryptionKey() throws Exception { public void testWriter() throws Exception { initializeExpectedBlob(2); BlobWriteChannel channel = createMock(BlobWriteChannel.class); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.writer(eq(expectedBlob))).andReturn(channel); replay(storage); initializeBlob(); @@ -348,7 +349,7 @@ public void testWriter() throws Exception { public void testWriterWithEncryptionKey() throws Exception { initializeExpectedBlob(2); BlobWriteChannel channel = createMock(BlobWriteChannel.class); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.writer(eq(expectedBlob), eq(BlobWriteOption.encryptionKey(BASE64_KEY)))) .andReturn(channel).times(2); replay(storage); @@ -361,7 +362,7 @@ public void testWriterWithEncryptionKey() throws Exception { public void testSignUrl() throws Exception { initializeExpectedBlob(2); URL url = new URL("http://localhost:123/bla"); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.signUrl(expectedBlob, 100, TimeUnit.SECONDS)).andReturn(url); replay(storage); initializeBlob(); @@ -371,7 +372,7 @@ public void testSignUrl() throws Exception { @Test public void testGetAcl() throws Exception { initializeExpectedBlob(1); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.getAcl(BLOB_INFO.getBlobId(), User.ofAllAuthenticatedUsers())).andReturn(ACL); replay(storage); initializeBlob(); @@ -381,8 +382,9 @@ public void testGetAcl() throws Exception { @Test public void testDeleteAcl() throws Exception { initializeExpectedBlob(1); - expect(storage.options()).andReturn(mockOptions); - expect(storage.deleteAcl(BLOB_INFO.getBlobId(), User.ofAllAuthenticatedUsers())).andReturn(true); + expect(storage.getOptions()).andReturn(mockOptions); + expect(storage.deleteAcl(BLOB_INFO.getBlobId(), + User.ofAllAuthenticatedUsers())).andReturn(true); replay(storage); initializeBlob(); assertTrue(blob.deleteAcl(User.ofAllAuthenticatedUsers())); @@ -391,7 +393,7 @@ public void testDeleteAcl() throws Exception { @Test public void testCreateAcl() throws Exception { initializeExpectedBlob(1); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); expect(storage.createAcl(BLOB_INFO.getBlobId(), ACL)).andReturn(returnedAcl); replay(storage); @@ -402,7 +404,7 @@ public void testCreateAcl() throws Exception { @Test public void testUpdateAcl() throws Exception { initializeExpectedBlob(1); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); expect(storage.updateAcl(BLOB_INFO.getBlobId(), ACL)).andReturn(returnedAcl); replay(storage); @@ -413,7 +415,7 @@ public void testUpdateAcl() throws Exception { @Test public void testListAcls() throws Exception { initializeExpectedBlob(1); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.listAcls(BLOB_INFO.getBlobId())).andReturn(ACLS); replay(storage); initializeBlob(); @@ -422,7 +424,7 @@ public void testListAcls() throws Exception { @Test public void testToBuilder() { - expect(storage.options()).andReturn(mockOptions).times(6); + expect(storage.getOptions()).andReturn(mockOptions).times(6); replay(storage); Blob fullBlob = new Blob(storage, new BlobInfo.BuilderImpl(FULL_BLOB_INFO)); assertEquals(fullBlob, fullBlob.toBuilder().build()); @@ -435,7 +437,7 @@ public void testToBuilder() { @Test public void testBuilder() { initializeExpectedBlob(4); - expect(storage.options()).andReturn(mockOptions).times(6); + expect(storage.getOptions()).andReturn(mockOptions).times(6); replay(storage); Blob.Builder builder = new Blob.Builder(new Blob(storage, new BlobInfo.BuilderImpl(BLOB_INFO))); Blob blob = builder.setAcl(ACLS) @@ -483,7 +485,7 @@ public void testBuilder() { assertEquals(SELF_LINK, blob.getSelfLink()); assertEquals(SIZE, blob.getSize()); assertEquals(UPDATE_TIME, blob.getUpdateTime()); - assertEquals(storage.options(), blob.getStorage().options()); + assertEquals(storage.getOptions(), blob.getStorage().getOptions()); assertFalse(blob.isDirectory()); builder = new Blob.Builder(new Blob(storage, new BlobInfo.BuilderImpl(DIRECTORY_INFO))); blob = builder.setBlobId(BlobId.of("b", "n/")) @@ -519,7 +521,7 @@ public void testBuilder() { @Test public void testBuilderDeprecated() { initializeExpectedBlob(4); - expect(storage.options()).andReturn(mockOptions).times(6); + expect(storage.getOptions()).andReturn(mockOptions).times(6); replay(storage); Blob.Builder builder = new Blob.Builder(new Blob(storage, new BlobInfo.BuilderImpl(BLOB_INFO))); Blob blob = builder.acl(ACLS) @@ -567,7 +569,7 @@ public void testBuilderDeprecated() { assertEquals(SELF_LINK, blob.selfLink()); assertEquals(SIZE, blob.size()); assertEquals(UPDATE_TIME, blob.updateTime()); - assertEquals(storage.options(), blob.storage().options()); + assertEquals(storage.getOptions(), blob.storage().getOptions()); assertFalse(blob.isDirectory()); builder = new Blob.Builder(new Blob(storage, new BlobInfo.BuilderImpl(DIRECTORY_INFO))); blob = builder.blobId(BlobId.of("b", "n/")) diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobWriteChannelTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobWriteChannelTest.java index e341a3e4f067..2598e3b4978c 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobWriteChannelTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/BlobWriteChannelTest.java @@ -56,7 +56,7 @@ public class BlobWriteChannelTest { private static final String BUCKET_NAME = "b"; private static final String BLOB_NAME = "n"; private static final String UPLOAD_ID = "uploadid"; - private static final BlobInfo BLOB_INFO = BlobInfo.builder(BUCKET_NAME, BLOB_NAME).build(); + private static final BlobInfo BLOB_INFO = BlobInfo.newBuilder(BUCKET_NAME, BLOB_NAME).build(); private static final Map EMPTY_RPC_OPTIONS = ImmutableMap.of(); private static final int MIN_CHUNK_SIZE = 256 * 1024; private static final int DEFAULT_CHUNK_SIZE = 8 * MIN_CHUNK_SIZE; @@ -77,9 +77,9 @@ public void setUp() { storageRpcMock = createMock(StorageRpc.class); expect(rpcFactoryMock.create(anyObject(StorageOptions.class))).andReturn(storageRpcMock); replay(rpcFactoryMock); - options = StorageOptions.builder() - .projectId("projectid") - .serviceRpcFactory(rpcFactoryMock) + options = StorageOptions.newBuilder() + .setProjectId("projectid") + .setServiceRpcFactory(rpcFactoryMock) .build(); } @@ -131,7 +131,7 @@ public void testWriteWithFlush() throws IOException { eq(CUSTOM_CHUNK_SIZE), eq(false)); replay(storageRpcMock); writer = new BlobWriteChannel(options, BLOB_INFO, EMPTY_RPC_OPTIONS); - writer.chunkSize(CUSTOM_CHUNK_SIZE); + writer.setChunkSize(CUSTOM_CHUNK_SIZE); ByteBuffer buffer = randomBuffer(CUSTOM_CHUNK_SIZE); assertEquals(CUSTOM_CHUNK_SIZE, writer.write(buffer)); assertArrayEquals(buffer.array(), capturedBuffer.getValue()); @@ -237,10 +237,10 @@ public void testSaveAndRestoreClosed() throws IOException { RestorableState writerState = writer.capture(); RestorableState expectedWriterState = BlobWriteChannel.StateImpl.builder(options, BLOB_INFO, UPLOAD_ID) - .buffer(null) - .chunkSize(DEFAULT_CHUNK_SIZE) - .isOpen(false) - .position(0) + .setBuffer(null) + .setChunkSize(DEFAULT_CHUNK_SIZE) + .setIsOpen(false) + .setPosition(0) .build(); WriteChannel restoredWriter = writerState.restore(); assertArrayEquals(new byte[0], capturedBuffer.getValue()); diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/BucketTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/BucketTest.java index e80339e36f52..15886adb2e95 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/BucketTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/BucketTest.java @@ -121,7 +121,7 @@ public void tearDown() throws Exception { } private void initializeExpectedBucket(int optionsCalls) { - expect(serviceMockReturnsOptions.options()).andReturn(mockOptions).times(optionsCalls); + expect(serviceMockReturnsOptions.getOptions()).andReturn(mockOptions).times(optionsCalls); replay(serviceMockReturnsOptions); expectedBucket = new Bucket(serviceMockReturnsOptions, new BucketInfo.BuilderImpl(BUCKET_INFO)); blobResults = ImmutableList.of( @@ -141,7 +141,7 @@ private void initializeBucket() { public void testExists_True() throws Exception { initializeExpectedBucket(4); Storage.BucketGetOption[] expectedOptions = {Storage.BucketGetOption.fields()}; - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.get(BUCKET_INFO.getName(), expectedOptions)).andReturn(expectedBucket); replay(storage); initializeBucket(); @@ -152,7 +152,7 @@ public void testExists_True() throws Exception { public void testExists_False() throws Exception { initializeExpectedBucket(4); Storage.BucketGetOption[] expectedOptions = {Storage.BucketGetOption.fields()}; - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.get(BUCKET_INFO.getName(), expectedOptions)).andReturn(null); replay(storage); initializeBucket(); @@ -165,7 +165,7 @@ public void testReload() throws Exception { BucketInfo updatedInfo = BUCKET_INFO.toBuilder().setNotFoundPage("p").build(); Bucket expectedUpdatedBucket = new Bucket(serviceMockReturnsOptions, new BucketInfo.BuilderImpl(updatedInfo)); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.get(updatedInfo.getName())).andReturn(expectedUpdatedBucket); replay(storage); initializeBucket(); @@ -176,7 +176,7 @@ public void testReload() throws Exception { @Test public void testReloadNull() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.get(BUCKET_INFO.getName())).andReturn(null); replay(storage); initializeBucket(); @@ -189,7 +189,7 @@ public void testReloadWithOptions() throws Exception { BucketInfo updatedInfo = BUCKET_INFO.toBuilder().setNotFoundPage("p").build(); Bucket expectedUpdatedBucket = new Bucket(serviceMockReturnsOptions, new BucketInfo.BuilderImpl(updatedInfo)); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.get(updatedInfo.getName(), Storage.BucketGetOption.metagenerationMatch(42L))) .andReturn(expectedUpdatedBucket); replay(storage); @@ -202,7 +202,7 @@ public void testReloadWithOptions() throws Exception { public void testUpdate() throws Exception { initializeExpectedBucket(5); Bucket expectedUpdatedBucket = expectedBucket.toBuilder().setNotFoundPage("p").build(); - expect(storage.options()).andReturn(mockOptions).times(2); + expect(storage.getOptions()).andReturn(mockOptions).times(2); expect(storage.update(expectedUpdatedBucket)).andReturn(expectedUpdatedBucket); replay(storage); initializeBucket(); @@ -214,7 +214,7 @@ public void testUpdate() throws Exception { @Test public void testDelete() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.delete(BUCKET_INFO.getName())).andReturn(true); replay(storage); initializeBucket(); @@ -225,19 +225,19 @@ public void testDelete() throws Exception { public void testList() throws Exception { initializeExpectedBucket(4); PageImpl expectedBlobPage = new PageImpl<>(null, "c", blobResults); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.list(BUCKET_INFO.getName())).andReturn(expectedBlobPage); replay(storage); initializeBucket(); Page blobPage = bucket.list(); - Iterator blobInfoIterator = blobPage.values().iterator(); - Iterator blobIterator = blobPage.values().iterator(); + Iterator blobInfoIterator = blobPage.getValues().iterator(); + Iterator blobIterator = blobPage.getValues().iterator(); while (blobInfoIterator.hasNext() && blobIterator.hasNext()) { assertEquals(blobInfoIterator.next(), blobIterator.next()); } assertFalse(blobInfoIterator.hasNext()); assertFalse(blobIterator.hasNext()); - assertEquals(expectedBlobPage.nextPageCursor(), blobPage.nextPageCursor()); + assertEquals(expectedBlobPage.getNextPageCursor(), blobPage.getNextPageCursor()); } @Test @@ -245,7 +245,7 @@ public void testGet() throws Exception { initializeExpectedBucket(5); Blob expectedBlob = new Blob( serviceMockReturnsOptions, new BlobInfo.BuilderImpl(BlobInfo.newBuilder("b", "n").build())); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.get(BlobId.of(expectedBucket.getName(), "n"), new Storage.BlobGetOption[0])) .andReturn(expectedBlob); replay(storage); @@ -257,7 +257,7 @@ public void testGet() throws Exception { @Test public void testGetAllArray() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); List blobIds = Lists.transform(blobResults, new Function() { @Override public BlobId apply(Blob blob) { @@ -273,7 +273,7 @@ public BlobId apply(Blob blob) { @Test public void testGetAllIterable() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); List blobIds = Lists.transform(blobResults, new Function() { @Override public BlobId apply(Blob blob) { @@ -292,7 +292,7 @@ public void testCreate() throws Exception { BlobInfo info = BlobInfo.newBuilder("b", "n").setContentType(CONTENT_TYPE).build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.create(info, content)).andReturn(expectedBlob); replay(storage); initializeBucket(); @@ -306,7 +306,7 @@ public void testCreateNoContentType() throws Exception { BlobInfo info = BlobInfo.newBuilder("b", "n").build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.create(info, content)).andReturn(expectedBlob); replay(storage); initializeBucket(); @@ -324,7 +324,7 @@ public void testCreateWithOptions() throws Exception { Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; Storage.PredefinedAcl acl = Storage.PredefinedAcl.ALL_AUTHENTICATED_USERS; - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.create(info, content, Storage.BlobTargetOption.generationMatch(), Storage.BlobTargetOption.metagenerationMatch(), Storage.BlobTargetOption.predefinedAcl(acl), @@ -345,7 +345,7 @@ public void testCreateWithEncryptionKey() throws Exception { BlobInfo info = BlobInfo.newBuilder(BlobId.of("b", "n")).setContentType(CONTENT_TYPE).build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.create(info, content, Storage.BlobTargetOption.encryptionKey(KEY))) .andReturn(expectedBlob); replay(storage); @@ -358,10 +358,11 @@ public void testCreateWithEncryptionKey() throws Exception { @Test public void testCreateNotExists() throws Exception { initializeExpectedBucket(5); - BlobInfo info = BlobInfo.newBuilder(BlobId.of("b", "n", 0L)).setContentType(CONTENT_TYPE).build(); + BlobInfo info = + BlobInfo.newBuilder(BlobId.of("b", "n", 0L)).setContentType(CONTENT_TYPE).build(); Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.create(info, content, Storage.BlobTargetOption.generationMatch())) .andReturn(expectedBlob); replay(storage); @@ -373,7 +374,7 @@ public void testCreateNotExists() throws Exception { @Test public void testCreateWithWrongGenerationOptions() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); replay(storage); initializeBucket(); byte[] content = {0xD, 0xE, 0xA, 0xD}; @@ -387,7 +388,7 @@ public void testCreateWithWrongGenerationOptions() throws Exception { @Test public void testCreateWithWrongMetagenerationOptions() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); replay(storage); initializeBucket(); byte[] content = {0xD, 0xE, 0xA, 0xD}; @@ -405,7 +406,7 @@ public void testCreateFromStream() throws Exception { Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; InputStream streamContent = new ByteArrayInputStream(content); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.create(info, streamContent)).andReturn(expectedBlob); replay(storage); initializeBucket(); @@ -420,7 +421,7 @@ public void testCreateFromStreamNoContentType() throws Exception { Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; InputStream streamContent = new ByteArrayInputStream(content); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.create(info, streamContent)).andReturn(expectedBlob); replay(storage); initializeBucket(); @@ -441,7 +442,7 @@ public void testCreateFromStreamWithOptions() throws Exception { byte[] content = {0xD, 0xE, 0xA, 0xD}; Storage.PredefinedAcl acl = Storage.PredefinedAcl.ALL_AUTHENTICATED_USERS; InputStream streamContent = new ByteArrayInputStream(content); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.create(info, streamContent, Storage.BlobWriteOption.generationMatch(), Storage.BlobWriteOption.metagenerationMatch(), Storage.BlobWriteOption.predefinedAcl(acl), Storage.BlobWriteOption.crc32cMatch(), Storage.BlobWriteOption.md5Match(), @@ -464,7 +465,7 @@ public void testCreateFromStreamWithEncryptionKey() throws Exception { Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; InputStream streamContent = new ByteArrayInputStream(content); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.create(info, streamContent, Storage.BlobWriteOption.encryptionKey(KEY))) .andReturn(expectedBlob); replay(storage); @@ -482,7 +483,7 @@ public void testCreateFromStreamNotExists() throws Exception { Blob expectedBlob = new Blob(serviceMockReturnsOptions, new BlobInfo.BuilderImpl(info)); byte[] content = {0xD, 0xE, 0xA, 0xD}; InputStream streamContent = new ByteArrayInputStream(content); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.create(info, streamContent, Storage.BlobWriteOption.generationMatch())) .andReturn(expectedBlob); replay(storage); @@ -495,7 +496,7 @@ public void testCreateFromStreamNotExists() throws Exception { @Test public void testCreateFromStreamWithWrongGenerationOptions() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); replay(storage); initializeBucket(); byte[] content = {0xD, 0xE, 0xA, 0xD}; @@ -510,7 +511,7 @@ public void testCreateFromStreamWithWrongGenerationOptions() throws Exception { @Test public void testCreateFromStreamWithWrongMetagenerationOptions() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); replay(storage); initializeBucket(); byte[] content = {0xD, 0xE, 0xA, 0xD}; @@ -525,7 +526,7 @@ public void testCreateFromStreamWithWrongMetagenerationOptions() throws Exceptio @Test public void testGetAcl() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.getAcl(BUCKET_INFO.getName(), User.ofAllAuthenticatedUsers())).andReturn(ACL); replay(storage); initializeBucket(); @@ -535,8 +536,9 @@ public void testGetAcl() throws Exception { @Test public void testDeleteAcl() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); - expect(storage.deleteAcl(BUCKET_INFO.getName(), User.ofAllAuthenticatedUsers())).andReturn(true); + expect(storage.getOptions()).andReturn(mockOptions); + expect(storage.deleteAcl(BUCKET_INFO.getName(), + User.ofAllAuthenticatedUsers())).andReturn(true); replay(storage); initializeBucket(); assertTrue(bucket.deleteAcl(User.ofAllAuthenticatedUsers())); @@ -545,7 +547,7 @@ public void testDeleteAcl() throws Exception { @Test public void testCreateAcl() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); expect(storage.createAcl(BUCKET_INFO.getName(), ACL)).andReturn(returnedAcl); replay(storage); @@ -556,7 +558,7 @@ public void testCreateAcl() throws Exception { @Test public void testUpdateAcl() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); expect(storage.updateAcl(BUCKET_INFO.getName(), ACL)).andReturn(returnedAcl); replay(storage); @@ -567,7 +569,7 @@ public void testUpdateAcl() throws Exception { @Test public void testListAcls() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.listAcls(BUCKET_INFO.getName())).andReturn(ACLS); replay(storage); initializeBucket(); @@ -577,7 +579,7 @@ public void testListAcls() throws Exception { @Test public void testGetDefaultAcl() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.getDefaultAcl(BUCKET_INFO.getName(), User.ofAllAuthenticatedUsers())) .andReturn(ACL); replay(storage); @@ -588,7 +590,7 @@ public void testGetDefaultAcl() throws Exception { @Test public void testDeleteDefaultAcl() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.deleteDefaultAcl(BUCKET_INFO.getName(), User.ofAllAuthenticatedUsers())) .andReturn(true); replay(storage); @@ -599,7 +601,7 @@ public void testDeleteDefaultAcl() throws Exception { @Test public void testCreateDefaultAcl() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); expect(storage.createDefaultAcl(BUCKET_INFO.getName(), ACL)).andReturn(returnedAcl); replay(storage); @@ -610,7 +612,7 @@ public void testCreateDefaultAcl() throws Exception { @Test public void testUpdateDefaultAcl() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); Acl returnedAcl = ACL.toBuilder().setEtag("ETAG").setId("ID").build(); expect(storage.updateDefaultAcl(BUCKET_INFO.getName(), ACL)).andReturn(returnedAcl); replay(storage); @@ -621,7 +623,7 @@ public void testUpdateDefaultAcl() throws Exception { @Test public void testListDefaultAcls() throws Exception { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions); + expect(storage.getOptions()).andReturn(mockOptions); expect(storage.listDefaultAcls(BUCKET_INFO.getName())).andReturn(ACLS); replay(storage); initializeBucket(); @@ -630,7 +632,7 @@ public void testListDefaultAcls() throws Exception { @Test public void testToBuilder() { - expect(storage.options()).andReturn(mockOptions).times(4); + expect(storage.getOptions()).andReturn(mockOptions).times(4); replay(storage); Bucket fullBucket = new Bucket(storage, new BucketInfo.BuilderImpl(FULL_BUCKET_INFO)); assertEquals(fullBucket, fullBucket.toBuilder().build()); @@ -641,7 +643,7 @@ public void testToBuilder() { @Test public void testBuilder() { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions).times(4); + expect(storage.getOptions()).andReturn(mockOptions).times(4); replay(storage); Bucket.Builder builder = new Bucket.Builder(new Bucket(storage, new BucketInfo.BuilderImpl(BUCKET_INFO))); @@ -677,13 +679,13 @@ public void testBuilder() { assertEquals(LOCATION, bucket.getLocation()); assertEquals(STORAGE_CLASS, bucket.getStorageClass()); assertEquals(VERSIONING_ENABLED, bucket.versioningEnabled()); - assertEquals(storage.options(), bucket.getStorage().options()); + assertEquals(storage.getOptions(), bucket.getStorage().getOptions()); } @Test public void testBuilderDeprecated() { initializeExpectedBucket(4); - expect(storage.options()).andReturn(mockOptions).times(4); + expect(storage.getOptions()).andReturn(mockOptions).times(4); replay(storage); Bucket.Builder builder = new Bucket.Builder(new Bucket(storage, new BucketInfo.BuilderImpl(BUCKET_INFO))); @@ -719,6 +721,6 @@ public void testBuilderDeprecated() { assertEquals(LOCATION, bucket.location()); assertEquals(STORAGE_CLASS, bucket.storageClass()); assertEquals(VERSIONING_ENABLED, bucket.versioningEnabled()); - assertEquals(storage.options(), bucket.storage().options()); + assertEquals(storage.getOptions(), bucket.storage().getOptions()); } } diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/CopyWriterTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/CopyWriterTest.java index fe5e42a5abd1..604a4a4c6b8f 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/CopyWriterTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/CopyWriterTest.java @@ -80,12 +80,12 @@ public void setUp() { expect(rpcFactoryMock.create(anyObject(StorageOptions.class))) .andReturn(storageRpcMock); replay(rpcFactoryMock); - options = StorageOptions.builder() - .projectId("projectid") - .serviceRpcFactory(rpcFactoryMock) - .retryParams(RetryParams.noRetries()) + options = StorageOptions.newBuilder() + .setProjectId("projectid") + .setServiceRpcFactory(rpcFactoryMock) + .setRetryParams(RetryParams.noRetries()) .build(); - result = new Blob(options.service(), new BlobInfo.BuilderImpl(RESULT_INFO)); + result = new Blob(options.getService(), new BlobInfo.BuilderImpl(RESULT_INFO)); } @After diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/CorsTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/CorsTest.java index 8507c4bd6bf8..a7223aff4100 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/CorsTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/CorsTest.java @@ -29,7 +29,7 @@ public class CorsTest { @Test public void testOrigin() { - assertEquals("bla", Origin.of("bla").value()); + assertEquals("bla", Origin.of("bla").getValue()); assertEquals("http://host:8080", Origin.of("http", "host", 8080).toString()); assertEquals(Origin.of("*"), Origin.any()); } diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java index 8addc5c3a147..3b1e5284aeee 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/SerializationTest.java @@ -31,7 +31,7 @@ public class SerializationTest extends BaseSerializationTest { - private static final Storage STORAGE = StorageOptions.builder().projectId("p").build().service(); + private static final Storage STORAGE = StorageOptions.newBuilder().setProjectId("p").build().getService(); private static final Acl.Domain ACL_DOMAIN = new Acl.Domain("domain"); private static final Acl.Group ACL_GROUP = new Acl.Group("group"); private static final Acl.Project ACL_PROJECT_ = new Acl.Project(ProjectRole.VIEWERS, "pid"); @@ -64,13 +64,13 @@ public class SerializationTest extends BaseSerializationTest { @Override protected Serializable[] serializableObjects() { - StorageOptions options = StorageOptions.builder() - .projectId("p1") - .authCredentials(AuthCredentials.createForAppEngine()) + StorageOptions options = StorageOptions.newBuilder() + .setProjectId("p1") + .setAuthCredentials(AuthCredentials.createForAppEngine()) .build(); StorageOptions otherOptions = options.toBuilder() - .projectId("p2") - .authCredentials(null) + .setProjectId("p2") + .setAuthCredentials(null) .build(); return new Serializable[]{ACL_DOMAIN, ACL_GROUP, ACL_PROJECT_, ACL_USER, ACL_RAW, ACL, BLOB_INFO, BLOB, BUCKET_INFO, BUCKET, ORIGIN, CORS, PAGE_RESULT, BLOB_LIST_OPTIONS, @@ -80,7 +80,7 @@ protected Serializable[] serializableObjects() { @Override protected Restorable[] restorableObjects() { - StorageOptions options = StorageOptions.builder().projectId("p2").build(); + StorageOptions options = StorageOptions.newBuilder().setProjectId("p2").build(); ReadChannel reader = new BlobReadChannel(options, BlobId.of("b", "n"), EMPTY_RPC_OPTIONS); // avoid closing when you don't want partial writes to GCS upon failure diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageBatchTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageBatchTest.java index 48658b116468..37914e6306cd 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageBatchTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageBatchTest.java @@ -66,7 +66,7 @@ public void setUp() { optionsMock = EasyMock.createMock(StorageOptions.class); dnsRpcMock = EasyMock.createMock(StorageRpc.class); batchMock = EasyMock.createMock(RpcBatch.class); - EasyMock.expect(optionsMock.rpc()).andReturn(dnsRpcMock); + EasyMock.expect(optionsMock.getRpc()).andReturn(dnsRpcMock); EasyMock.expect(dnsRpcMock.createBatch()).andReturn(batchMock); EasyMock.replay(optionsMock, dnsRpcMock, batchMock, storage); dnsBatch = new StorageBatch(optionsMock); @@ -79,9 +79,9 @@ public void tearDown() { @Test public void testConstructor() { - assertSame(batchMock, dnsBatch.batch()); - assertSame(optionsMock, dnsBatch.options()); - assertSame(dnsRpcMock, dnsBatch.storageRpc()); + assertSame(batchMock, dnsBatch.getBatch()); + assertSame(optionsMock, dnsBatch.getOptions()); + assertSame(dnsRpcMock, dnsBatch.getStorageRpc()); } @Test @@ -159,8 +159,8 @@ public void testUpdate() { @Test public void testUpdateWithOptions() { EasyMock.reset(storage, batchMock, optionsMock); - EasyMock.expect(storage.options()).andReturn(optionsMock).times(2); - EasyMock.expect(optionsMock.service()).andReturn(storage); + EasyMock.expect(storage.getOptions()).andReturn(optionsMock).times(2); + EasyMock.expect(optionsMock.getService()).andReturn(storage); Capture> callback = Capture.newInstance(); Capture> capturedOptions = Capture.newInstance(); batchMock.addPatch(EasyMock.eq(BLOB_INFO_COMPLETE.toPb()), EasyMock.capture(callback), @@ -205,8 +205,8 @@ public void testGet() { @Test public void testGetWithOptions() { EasyMock.reset(storage, batchMock, optionsMock); - EasyMock.expect(storage.options()).andReturn(optionsMock).times(2); - EasyMock.expect(optionsMock.service()).andReturn(storage); + EasyMock.expect(storage.getOptions()).andReturn(optionsMock).times(2); + EasyMock.expect(optionsMock.getService()).andReturn(storage); Capture> callback = Capture.newInstance(); Capture> capturedOptions = Capture.newInstance(); batchMock.addGet(EasyMock.eq(BLOB_INFO.toPb()), EasyMock.capture(callback), diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageExceptionTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageExceptionTest.java index 1f16ff04cee3..234332c5c4d8 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageExceptionTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageExceptionTest.java @@ -40,77 +40,77 @@ public class StorageExceptionTest { @Test public void testStorageException() { StorageException exception = new StorageException(500, "message"); - assertEquals(500, exception.code()); + assertEquals(500, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new StorageException(502, "message"); - assertEquals(502, exception.code()); + assertEquals(502, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new StorageException(503, "message"); - assertEquals(503, exception.code()); + assertEquals(503, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new StorageException(504, "message"); - assertEquals(504, exception.code()); + assertEquals(504, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new StorageException(429, "message"); - assertEquals(429, exception.code()); + assertEquals(429, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new StorageException(408, "message"); - assertEquals(408, exception.code()); + assertEquals(408, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new StorageException(400, "message"); - assertEquals(400, exception.code()); + assertEquals(400, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertFalse(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertFalse(exception.isRetryable()); + assertTrue(exception.isIdempotent()); IOException cause = new SocketTimeoutException(); exception = new StorageException(cause); - assertNull(exception.reason()); + assertNull(exception.getReason()); assertNull(exception.getMessage()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); GoogleJsonError error = new GoogleJsonError(); error.setCode(503); error.setMessage("message"); exception = new StorageException(error); - assertEquals(503, exception.code()); + assertEquals(503, exception.getCode()); assertEquals("message", exception.getMessage()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new StorageException(400, "message", cause); - assertEquals(400, exception.code()); + assertEquals(400, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertFalse(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertFalse(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); } @@ -123,10 +123,10 @@ public void testTranslateAndThrow() throws Exception { try { StorageException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(503, ex.code()); + assertEquals(503, ex.getCode()); assertEquals("message", ex.getMessage()); - assertTrue(ex.retryable()); - assertTrue(ex.idempotent()); + assertTrue(ex.isRetryable()); + assertTrue(ex.isIdempotent()); } finally { verify(exceptionMock); } @@ -138,10 +138,10 @@ public void testTranslateAndThrow() throws Exception { try { StorageException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(StorageException.UNKNOWN_CODE, ex.code()); + assertEquals(StorageException.UNKNOWN_CODE, ex.getCode()); assertEquals("message", ex.getMessage()); - assertFalse(ex.retryable()); - assertTrue(ex.idempotent()); + assertFalse(ex.isRetryable()); + assertTrue(ex.isIdempotent()); assertSame(cause, ex.getCause()); } finally { verify(exceptionMock); diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java index 7a64a1021ced..d44dfe2402e6 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/StorageImplTest.java @@ -284,11 +284,11 @@ public void setUp() { EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(StorageOptions.class))) .andReturn(storageRpcMock); EasyMock.replay(rpcFactoryMock); - options = StorageOptions.builder() - .projectId("projectId") - .clock(TIME_SOURCE) - .serviceRpcFactory(rpcFactoryMock) - .retryParams(RetryParams.noRetries()) + options = StorageOptions.newBuilder() + .setProjectId("projectId") + .setClock(TIME_SOURCE) + .setServiceRpcFactory(rpcFactoryMock) + .setRetryParams(RetryParams.noRetries()) .build(); } @@ -298,7 +298,7 @@ public void tearDown() throws Exception { } private void initializeService() { - storage = options.service(); + storage = options.getService(); initializeServiceDependentObjects(); } @@ -314,7 +314,7 @@ private void initializeServiceDependentObjects() { public void testGetOptions() { EasyMock.replay(storageRpcMock); initializeService(); - assertSame(options, storage.options()); + assertSame(options, storage.getOptions()); } @Test @@ -611,8 +611,8 @@ public void testListBuckets() { initializeService(); ImmutableList bucketList = ImmutableList.of(expectedBucket1, expectedBucket2); Page page = storage.list(); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(bucketList.toArray(), Iterables.toArray(page.values(), Bucket.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(bucketList.toArray(), Iterables.toArray(page.getValues(), Bucket.class)); } @Test @@ -622,8 +622,9 @@ public void testListBucketsEmpty() { EasyMock.replay(storageRpcMock); initializeService(); Page page = storage.list(); - assertNull(page.nextPageCursor()); - assertArrayEquals(ImmutableList.of().toArray(), Iterables.toArray(page.values(), Bucket.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(ImmutableList.of().toArray(), + Iterables.toArray(page.getValues(), Bucket.class)); } @Test @@ -637,8 +638,8 @@ public void testListBucketsWithOptions() { initializeService(); ImmutableList bucketList = ImmutableList.of(expectedBucket1, expectedBucket2); Page page = storage.list(BUCKET_LIST_PAGE_SIZE, BUCKET_LIST_PREFIX); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(bucketList.toArray(), Iterables.toArray(page.values(), Bucket.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(bucketList.toArray(), Iterables.toArray(page.getValues(), Bucket.class)); } @Test @@ -661,8 +662,8 @@ public void testListBucketsWithSelectedFields() { assertTrue(selector.contains("nextPageToken")); assertTrue(selector.endsWith(")")); assertEquals(38, selector.length()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(bucketList.toArray(), Iterables.toArray(page.values(), Bucket.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(bucketList.toArray(), Iterables.toArray(page.getValues(), Bucket.class)); } @Test @@ -677,14 +678,15 @@ public void testListBucketsWithEmptyFields() { initializeService(); ImmutableList bucketList = ImmutableList.of(expectedBucket1, expectedBucket2); Page page = storage.list(BUCKET_LIST_EMPTY_FIELDS); - String selector = (String) capturedOptions.getValue().get(BUCKET_LIST_EMPTY_FIELDS.getRpcOption()); + String selector = + (String) capturedOptions.getValue().get(BUCKET_LIST_EMPTY_FIELDS.getRpcOption()); assertTrue(selector.contains("items(")); assertTrue(selector.contains("name")); assertTrue(selector.contains("nextPageToken")); assertTrue(selector.endsWith(")")); assertEquals(25, selector.length()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(bucketList.toArray(), Iterables.toArray(page.values(), Bucket.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(bucketList.toArray(), Iterables.toArray(page.getValues(), Bucket.class)); } @Test @@ -698,8 +700,8 @@ public void testListBlobs() { initializeService(); ImmutableList blobList = ImmutableList.of(expectedBlob1, expectedBlob2); Page page = storage.list(BUCKET_NAME1); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(blobList.toArray(), Iterables.toArray(page.values(), Blob.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(blobList.toArray(), Iterables.toArray(page.getValues(), Blob.class)); } @Test @@ -710,8 +712,9 @@ public void testListBlobsEmpty() { EasyMock.replay(storageRpcMock); initializeService(); Page page = storage.list(BUCKET_NAME1); - assertNull(page.nextPageCursor()); - assertArrayEquals(ImmutableList.of().toArray(), Iterables.toArray(page.values(), Blob.class)); + assertNull(page.getNextPageCursor()); + assertArrayEquals(ImmutableList.of().toArray(), + Iterables.toArray(page.getValues(), Blob.class)); } @Test @@ -726,8 +729,8 @@ public void testListBlobsWithOptions() { ImmutableList blobList = ImmutableList.of(expectedBlob1, expectedBlob2); Page page = storage.list(BUCKET_NAME1, BLOB_LIST_PAGE_SIZE, BLOB_LIST_PREFIX, BLOB_LIST_VERSIONS); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(blobList.toArray(), Iterables.toArray(page.values(), Blob.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(blobList.toArray(), Iterables.toArray(page.getValues(), Blob.class)); } @Test @@ -759,8 +762,8 @@ public void testListBlobsWithSelectedFields() { assertTrue(selector.contains("nextPageToken")); assertTrue(selector.endsWith(")")); assertEquals(61, selector.length()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(blobList.toArray(), Iterables.toArray(page.values(), Blob.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(blobList.toArray(), Iterables.toArray(page.getValues(), Blob.class)); } @Test @@ -782,7 +785,8 @@ public void testListBlobsWithEmptyFields() { capturedOptions.getValue().get(BLOB_LIST_PAGE_SIZE.getRpcOption())); assertEquals(BLOB_LIST_PREFIX.getValue(), capturedOptions.getValue().get(BLOB_LIST_PREFIX.getRpcOption())); - String selector = (String) capturedOptions.getValue().get(BLOB_LIST_EMPTY_FIELDS.getRpcOption()); + String selector = + (String) capturedOptions.getValue().get(BLOB_LIST_EMPTY_FIELDS.getRpcOption()); assertTrue(selector.contains("prefixes")); assertTrue(selector.contains("items(")); assertTrue(selector.contains("bucket")); @@ -790,8 +794,8 @@ public void testListBlobsWithEmptyFields() { assertTrue(selector.contains("nextPageToken")); assertTrue(selector.endsWith(")")); assertEquals(41, selector.length()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(blobList.toArray(), Iterables.toArray(page.values(), Blob.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(blobList.toArray(), Iterables.toArray(page.getValues(), Blob.class)); } @Test @@ -806,8 +810,8 @@ public void testListBlobsCurrentDirectory() { initializeService(); ImmutableList blobList = ImmutableList.of(expectedBlob1, expectedBlob2); Page page = storage.list(BUCKET_NAME1, Storage.BlobListOption.currentDirectory()); - assertEquals(cursor, page.nextPageCursor()); - assertArrayEquals(blobList.toArray(), Iterables.toArray(page.values(), Blob.class)); + assertEquals(cursor, page.getNextPageCursor()); + assertArrayEquals(blobList.toArray(), Iterables.toArray(page.getValues(), Blob.class)); } @Test @@ -1118,9 +1122,9 @@ public void testBatch() { EasyMock.replay(batchMock, storageRpcMock); initializeService(); StorageBatch batch = storage.batch(); - assertSame(options, batch.options()); - assertSame(storageRpcMock, batch.storageRpc()); - assertSame(batchMock, batch.batch()); + assertSame(options, batch.getOptions()); + assertSame(storageRpcMock, batch.getStorageRpc()); + assertSame(batchMock, batch.getBatch()); EasyMock.verify(batchMock); } @@ -1229,7 +1233,7 @@ public void testSignUrl() throws NoSuchAlgorithmException, InvalidKeyException, EasyMock.replay(storageRpcMock); ServiceAccountAuthCredentials authCredentials = ServiceAccountAuthCredentials.createFor(ACCOUNT, privateKey); - storage = options.toBuilder().authCredentials(authCredentials).build().service(); + storage = options.toBuilder().setAuthCredentials(authCredentials).build().getService(); URL url = storage.signUrl(BLOB_INFO1, 14, TimeUnit.DAYS); String stringUrl = url.toString(); String expectedUrl = new StringBuilder("https://storage.googleapis.com/").append(BUCKET_NAME1) @@ -1256,7 +1260,7 @@ public void testSignUrlLeadingSlash() throws NoSuchAlgorithmException, InvalidKe EasyMock.replay(storageRpcMock); ServiceAccountAuthCredentials authCredentials = ServiceAccountAuthCredentials.createFor(ACCOUNT, privateKey); - storage = options.toBuilder().authCredentials(authCredentials).build().service(); + storage = options.toBuilder().setAuthCredentials(authCredentials).build().getService(); URL url = storage.signUrl(BlobInfo.newBuilder(BUCKET_NAME1, blobName).build(), 14, TimeUnit.DAYS); String escapedBlobName = UrlEscapers.urlFragmentEscaper().escape(blobName); @@ -1284,7 +1288,7 @@ public void testSignUrlWithOptions() throws NoSuchAlgorithmException, InvalidKey EasyMock.replay(storageRpcMock); ServiceAccountAuthCredentials authCredentials = ServiceAccountAuthCredentials.createFor(ACCOUNT, privateKey); - storage = options.toBuilder().authCredentials(authCredentials).build().service(); + storage = options.toBuilder().setAuthCredentials(authCredentials).build().getService(); URL url = storage.signUrl(BLOB_INFO1, 14, TimeUnit.DAYS, Storage.SignUrlOption.httpMethod(HttpMethod.POST), Storage.SignUrlOption.withContentType(), Storage.SignUrlOption.withMd5()); @@ -1317,7 +1321,7 @@ public void testSignUrlForBlobWithSpecialChars() throws NoSuchAlgorithmException EasyMock.replay(storageRpcMock); ServiceAccountAuthCredentials authCredentials = ServiceAccountAuthCredentials.createFor(ACCOUNT, privateKey); - storage = options.toBuilder().authCredentials(authCredentials).build().service(); + storage = options.toBuilder().setAuthCredentials(authCredentials).build().getService(); for (char specialChar : specialChars) { String blobName = "/a" + specialChar + "b"; @@ -1713,7 +1717,8 @@ public void testRetryableException() { .andThrow(new StorageException(500, "internalError")) .andReturn(BLOB_INFO1.toPb()); EasyMock.replay(storageRpcMock); - storage = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); + storage = + options.toBuilder().setRetryParams(RetryParams.getDefaultInstance()).build().getService(); initializeServiceDependentObjects(); Blob readBlob = storage.get(blob); assertEquals(expectedBlob1, readBlob); @@ -1726,7 +1731,8 @@ public void testNonRetryableException() { EasyMock.expect(storageRpcMock.get(blob.toPb(), EMPTY_RPC_OPTIONS)) .andThrow(new StorageException(501, exceptionMessage)); EasyMock.replay(storageRpcMock); - storage = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); + storage = + options.toBuilder().setRetryParams(RetryParams.getDefaultInstance()).build().getService(); initializeServiceDependentObjects(); thrown.expect(StorageException.class); thrown.expectMessage(exceptionMessage); @@ -1740,7 +1746,8 @@ public void testRuntimeException() { EasyMock.expect(storageRpcMock.get(blob.toPb(), EMPTY_RPC_OPTIONS)) .andThrow(new RuntimeException(exceptionMessage)); EasyMock.replay(storageRpcMock); - storage = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); + storage = + options.toBuilder().setRetryParams(RetryParams.getDefaultInstance()).build().getService(); thrown.expect(StorageException.class); thrown.expectMessage(exceptionMessage); storage.get(blob); diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java index 6a06b3abcd77..a3d754323e65 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/it/ITStorageTest.java @@ -104,7 +104,7 @@ public class ITStorageTest { @BeforeClass public static void beforeClass() throws NoSuchAlgorithmException, InvalidKeySpecException { RemoteStorageHelper helper = RemoteStorageHelper.create(); - storage = helper.getOptions().service(); + storage = helper.getOptions().getService(); storage.create(BucketInfo.of(BUCKET)); } @@ -816,7 +816,8 @@ public void testCopyBlobFail() { Blob remoteSourceBlob = storage.create(BlobInfo.newBuilder(source).build(), BLOB_BYTE_CONTENT); assertNotNull(remoteSourceBlob); String targetBlobName = "test-copy-blob-target-fail"; - BlobInfo target = BlobInfo.newBuilder(BUCKET, targetBlobName).setContentType(CONTENT_TYPE).build(); + BlobInfo target = + BlobInfo.newBuilder(BUCKET, targetBlobName).setContentType(CONTENT_TYPE).build(); Storage.CopyRequest req = Storage.CopyRequest.newBuilder() .setSource(BUCKET, sourceBlobName) .setSourceOptions(Storage.BlobSourceOption.generationMatch(-1L)) @@ -1083,7 +1084,7 @@ public void testReadAndWriteCaptureChannels() throws IOException { ByteBuffer readBytes; ByteBuffer readStringBytes; ReadChannel reader = storage.reader(blob.getBlobId()); - reader.chunkSize(BLOB_BYTE_CONTENT.length); + reader.setChunkSize(BLOB_BYTE_CONTENT.length); readBytes = ByteBuffer.allocate(BLOB_BYTE_CONTENT.length); reader.read(readBytes); RestorableState readerState = reader.capture(); @@ -1141,7 +1142,7 @@ public void testReadChannelFailUpdatedGeneration() throws IOException { assertNotNull(remoteBlob); assertEquals(blobSize, (long) remoteBlob.getSize()); try (ReadChannel reader = storage.reader(blob.getBlobId())) { - reader.chunkSize(chunkSize); + reader.setChunkSize(chunkSize); ByteBuffer readBytes = ByteBuffer.allocate(chunkSize); int numReadBytes = reader.read(readBytes); assertEquals(chunkSize, numReadBytes); @@ -1390,14 +1391,14 @@ public void testBlobAcl() { @Test public void testReadCompressedBlob() throws IOException { String blobName = "test-read-compressed-blob"; - BlobInfo blobInfo = BlobInfo.builder(BlobId.of(BUCKET, blobName)) - .contentType("text/plain") - .contentEncoding("gzip") + BlobInfo blobInfo = BlobInfo.newBuilder(BlobId.of(BUCKET, blobName)) + .setContentType("text/plain") + .setContentEncoding("gzip") .build(); Blob blob = storage.create(blobInfo, COMPRESSED_CONTENT); try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { try (ReadChannel reader = storage.reader(BlobId.of(BUCKET, blobName))) { - reader.chunkSize(8); + reader.setChunkSize(8); ByteBuffer buffer = ByteBuffer.allocate(8); while (reader.read(buffer) != -1) { buffer.flip(); diff --git a/google-cloud-storage/src/test/java/com/google/cloud/storage/testing/RemoteStorageHelperTest.java b/google-cloud-storage/src/test/java/com/google/cloud/storage/testing/RemoteStorageHelperTest.java index 158cbcac9988..c4bc103edb33 100644 --- a/google-cloud-storage/src/test/java/com/google/cloud/storage/testing/RemoteStorageHelperTest.java +++ b/google-cloud-storage/src/test/java/com/google/cloud/storage/testing/RemoteStorageHelperTest.java @@ -93,20 +93,38 @@ public void setUp() { blobList = ImmutableList.of(blob1, blob2); blobPage = new Page() { @Override + @Deprecated public String nextPageCursor() { return "nextPageCursor"; } @Override + public String getNextPageCursor() { + return "nextPageCursor"; + } + + @Override + @Deprecated public Page nextPage() { return null; } @Override + public Page getNextPage() { + return null; + } + + @Override + @Deprecated public Iterable values() { return blobList; } + @Override + public Iterable getValues() { + return blobList; + } + @Override public Iterator iterateAll() { return blobList.iterator(); @@ -203,13 +221,13 @@ public void testCreateFromStream() { RemoteStorageHelper helper = RemoteStorageHelper.create(PROJECT_ID, JSON_KEY_STREAM); StorageOptions options = helper.getOptions(); assertEquals(options, helper.options()); - assertEquals(PROJECT_ID, options.projectId()); - assertEquals(60000, options.connectTimeout()); - assertEquals(60000, options.readTimeout()); - assertEquals(10, options.retryParams().retryMaxAttempts()); - assertEquals(6, options.retryParams().retryMinAttempts()); - assertEquals(30000, options.retryParams().maxRetryDelayMillis()); - assertEquals(120000, options.retryParams().totalRetryPeriodMillis()); - assertEquals(250, options.retryParams().initialRetryDelayMillis()); + assertEquals(PROJECT_ID, options.getProjectId()); + assertEquals(60000, options.getConnectTimeout()); + assertEquals(60000, options.getReadTimeout()); + assertEquals(10, options.getRetryParams().getRetryMaxAttempts()); + assertEquals(6, options.getRetryParams().getRetryMinAttempts()); + assertEquals(30000, options.getRetryParams().getMaxRetryDelayMillis()); + assertEquals(120000, options.getRetryParams().getTotalRetryPeriodMillis()); + assertEquals(250, options.getRetryParams().getInitialRetryDelayMillis()); } } diff --git a/google-cloud-translate/README.md b/google-cloud-translate/README.md index 1d51871eb550..1d57a2727e41 100644 --- a/google-cloud-translate/README.md +++ b/google-cloud-translate/README.md @@ -83,12 +83,12 @@ service object, given that `GOOGLE_API_KEY` is set, use the following code: import com.google.cloud.translate.Translate; import com.google.cloud.translate.TranslateOptions; -Translate translate = TranslateOptions.defaultInstance().service(); +Translate translate = TranslateOptions.getDefaultInstance().getService(); ``` Or you can explicitly set the API key as follows: ```java -Translate translate = TranslateOptions.builder().apiKey("myKey").service(); +Translate translate = TranslateOptions.newBuilder().setApiKey("myKey").getService(); ``` #### Detecting language diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/Translate.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/Translate.java index 0bad2b22e1a9..c56c879c8123 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/Translate.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/Translate.java @@ -41,7 +41,7 @@ private LanguageListOption(TranslateRpc.Option rpcOption, String value) { /** * Returns an option for setting the target language. If this option is not provided, the value - * returned by {@link TranslateOptions#targetLanguage()} is used. When provided, the returned + * returned by {@link TranslateOptions#getTargetLanguage()} is used. When provided, the returned * {@link Language#name()} will be in the language specified by the {@code targetLanguage} code. * * @param targetLanguage the target language code @@ -74,7 +74,7 @@ public static TranslateOption sourceLanguage(String sourceLanguage) { /** * Returns an option for setting the target language. If this option is not provided, the value - * returned by {@link TranslateOptions#targetLanguage()} is used. + * returned by {@link TranslateOptions#getTargetLanguage()} is used. * * @param targetLanguage the target language code */ @@ -88,10 +88,10 @@ public static TranslateOption targetLanguage(String targetLanguage) { * {@link LanguageListOption#targetLanguage(String)} is provided, {@link Language#getName()} * values are localized according to the provided target language. If no such option is passed, * {@link Language#getName()} values are localized according to - * {@link TranslateOptions#targetLanguage()}. + * {@link TranslateOptions#getTargetLanguage()}. * *

    Example of listing supported languages, localized according to - * {@link TranslateOptions#targetLanguage()}. + * {@link TranslateOptions#getTargetLanguage()}. *

     {@code
        * List languages = translate.listSupportedLanguages();
        * }
    diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateException.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateException.java index f1d3c18fed8e..b3e2a49880fe 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateException.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateException.java @@ -45,7 +45,7 @@ public TranslateException(IOException exception) { } @Override - protected Set retryableErrors() { + protected Set getRetryableErrors() { return RETRYABLE_ERRORS; } diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateImpl.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateImpl.java index da49b20da3f6..b35293e9234d 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateImpl.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateImpl.java @@ -51,7 +51,7 @@ public Detection apply(List detectionPb) { TranslateImpl(TranslateOptions options) { super(options); - translateRpc = options.rpc(); + translateRpc = options.getRpc(); } @Override @@ -62,7 +62,8 @@ public List listSupportedLanguages(final LanguageListOption... options public List call() { return translateRpc.listSupportedLanguages(optionMap(options)); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()), Language.FROM_PB_FUNCTION); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()), + Language.FROM_PB_FUNCTION); } catch (RetryHelperException e) { throw TranslateException.translateAndThrow(e); } @@ -77,7 +78,7 @@ public List detect(final List texts) { public List> call() { return translateRpc.detect(texts); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()); + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()); Iterator> detectionIterator = detectionsPb.iterator(); Iterator textIterator = texts.iterator(); while (detectionIterator.hasNext() && textIterator.hasNext()) { @@ -111,7 +112,7 @@ public List translate(final List texts, final TranslateOpti public List call() { return translateRpc.translate(texts, optionMap(options)); } - }, options().retryParams(), EXCEPTION_HANDLER, options().clock()), + }, getOptions().getRetryParams(), EXCEPTION_HANDLER, getOptions().getClock()), Translation.FROM_PB_FUNCTION); } catch (RetryHelperException e) { throw TranslateException.translateAndThrow(e); diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java index 86f3507aed01..508dde26d0c6 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/TranslateOptions.java @@ -80,8 +80,19 @@ private Builder(TranslateOptions options) { * @return the builder */ @Override + @Deprecated public Builder projectId(String projectId) { - super.projectId(projectId); + return setProjectId(projectId); + } + + /** + * Sets project id. Setting a project id has no impact on the {@link Translate} service. + * + * @return the builder + */ + @Override + public Builder setProjectId(String projectId) { + super.setProjectId(projectId); return self(); } @@ -91,8 +102,19 @@ public Builder projectId(String projectId) { * * @return the builder */ + @Deprecated public Builder authCredentials(AuthCredentials authCredentials) { - super.authCredentials(authCredentials); + return setAuthCredentials(authCredentials); + } + + /** + * Sets the service authentication credentials. Setting credentials has no impact on the + * {@link Translate} service. + * + * @return the builder + */ + public Builder setAuthCredentials(AuthCredentials authCredentials) { + super.setAuthCredentials(authCredentials); return self(); } @@ -101,7 +123,17 @@ public Builder authCredentials(AuthCredentials authCredentials) { * {@code GOOGLE_API_KEY} environment variable. For instructions on how to get an API key see * Translate quickstart. */ + @Deprecated public Builder apiKey(String apiKey) { + return setApiKey(apiKey); + } + + /** + * Sets the API key used to issue requets. If not set, the API key is looked for in the + * {@code GOOGLE_API_KEY} environment variable. For instructions on how to get an API key see + * Translate quickstart. + */ + public Builder setApiKey(String apiKey) { this.apiKey = apiKey; return this; } @@ -115,7 +147,21 @@ public Builder apiKey(String apiKey) { * * @return the builder */ + @Deprecated public Builder targetLanguage(String targetLanguage) { + return setTargetLanguage(targetLanguage); + } + + /** + * Sets the code for the default target language. If not set, english ({@code en}) is used. + * {@link Translate#translate(List, TranslateOption...)} and + * {@link Translate#translate(String, TranslateOption...)} calls will use this + * value unless a {@link TranslateOption#targetLanguage(String)} option is explicitly + * provided. + * + * @return the builder + */ + public Builder setTargetLanguage(String targetLanguage) { this.targetLanguage = targetLanguage; return self(); } @@ -123,14 +169,14 @@ public Builder targetLanguage(String targetLanguage) { @Override public TranslateOptions build() { // Auth credentials are not used by Translate - authCredentials(AuthCredentials.noAuth()); + setAuthCredentials(AuthCredentials.noAuth()); return new TranslateOptions(this); } } private TranslateOptions(Builder builder) { super(TranslateFactory.class, TranslateRpcFactory.class, builder); - this.apiKey = builder.apiKey != null ? builder.apiKey : defaultApiKey(); + this.apiKey = builder.apiKey != null ? builder.apiKey : getDefaultApiKey(); checkArgument(this.apiKey != null, "An API key is required for this service but could not be determined from the builder " + "or the environment. Please set an API key using the builder."); @@ -138,12 +184,12 @@ private TranslateOptions(Builder builder) { } @Override - protected TranslateFactory defaultServiceFactory() { + protected TranslateFactory getDefaultServiceFactory() { return DefaultTranslateFactory.INSTANCE; } @Override - protected TranslateRpcFactory defaultRpcFactory() { + protected TranslateRpcFactory getDefaultRpcFactory() { return DefaultTranslateRpcFactory.INSTANCE; } @@ -153,25 +199,46 @@ protected boolean projectIdRequired() { } @Override - protected Set scopes() { + protected Set getScopes() { return SCOPES; } + @Deprecated protected String defaultApiKey() { + return getDefaultApiKey(); + } + + protected String getDefaultApiKey() { return System.getProperty(API_KEY_ENV_NAME, System.getenv(API_KEY_ENV_NAME)); } /** * Returns the API key, to be used used to send requests. */ + @Deprecated public String apiKey() { + return getApiKey(); + } + + /** + * Returns the API key, to be used used to send requests. + */ + public String getApiKey() { return apiKey; } /** * Returns the code for the default target language. */ + @Deprecated public String targetLanguage() { + return getTargetLanguage(); + } + + /** + * Returns the code for the default target language. + */ + public String getTargetLanguage() { return targetLanguage; } @@ -200,14 +267,30 @@ public boolean equals(Object obj) { /** * Returns a default {@code TranslateOptions} instance. */ + @Deprecated public static TranslateOptions defaultInstance() { - return builder().build(); + return getDefaultInstance(); + } + + /** + * Returns a default {@code TranslateOptions} instance. + */ + public static TranslateOptions getDefaultInstance() { + return newBuilder().build(); } /** * Returns a builder for {@code TranslateOptions} objects. */ + @Deprecated public static Builder builder() { + return newBuilder(); + } + + /** + * Returns a builder for {@code TranslateOptions} objects. + */ + public static Builder newBuilder() { return new Builder(); } } diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/package-info.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/package-info.java index cb022c5cb53e..3fe371993708 100644 --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/package-info.java +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/package-info.java @@ -20,12 +20,12 @@ *

    Here's a simple usage example for using google-cloud. This example shows how to detect the * language of some text and how to translate some text. The example assumes that the * {@code GOOGLE_API_KEY} is set and contains a valid API key. Alternatively, you can use - * {@link com.google.cloud.translate.TranslateOptions.Builder#apiKey(java.lang.String)} to set the - * API key. For the complete source code see + * {@link com.google.cloud.translate.TranslateOptions.Builder#setApiKey(java.lang.String)} to set + * the API key. For the complete source code see * * DetectLanguageAndTranslate.java. *

     {@code
    - * Translate translate = TranslateOptions.defaultInstance().service();
    + * Translate translate = TranslateOptions.getDefaultInstance().getService();
      *
      * Detection detection = translate.detect("Hola");
      * String detectedLanguage = detection.getLanguage();
    diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/spi/DefaultTranslateRpc.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/spi/DefaultTranslateRpc.java
    index 1af329a0be47..a5a7b4bc4763 100644
    --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/spi/DefaultTranslateRpc.java
    +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/spi/DefaultTranslateRpc.java
    @@ -43,12 +43,12 @@ public class DefaultTranslateRpc implements TranslateRpc {
       private final Translate translate;
     
       public DefaultTranslateRpc(TranslateOptions options) {
    -    HttpTransport transport = options.httpTransportFactory().create();
    -    HttpRequestInitializer initializer = options.httpRequestInitializer();
    +    HttpTransport transport = options.getHttpTransportFactory().create();
    +    HttpRequestInitializer initializer = options.getHttpRequestInitializer();
         this.options = options;
         translate = new Translate.Builder(transport, new JacksonFactory(), initializer)
    -        .setRootUrl(options.host())
    -        .setApplicationName(options.applicationName())
    +        .setRootUrl(options.getHost())
    +        .setApplicationName(options.getApplicationName())
             .build();
       }
     
    @@ -60,7 +60,7 @@ private static TranslateException translate(IOException exception) {
       public List> detect(List texts) {
         try {
           List> detections =
    -          translate.detections().list(texts).setKey(options.apiKey()).execute().getDetections();
    +          translate.detections().list(texts).setKey(options.getApiKey()).execute().getDetections();
           return detections != null ? detections : ImmutableList.>of();
         } catch (IOException ex) {
           throw translate(ex);
    @@ -72,8 +72,9 @@ public List listSupportedLanguages(Map optionMap)
         try {
           List languages = translate.languages()
               .list()
    -          .setKey(options.apiKey())
    -          .setTarget(firstNonNull(TARGET_LANGUAGE.getString(optionMap), options.targetLanguage()))
    +          .setKey(options.getApiKey())
    +          .setTarget(
    +              firstNonNull(TARGET_LANGUAGE.getString(optionMap), options.getTargetLanguage()))
               .execute().getLanguages();
           return languages != null ? languages : ImmutableList.of();
         } catch (IOException ex) {
    @@ -85,13 +86,13 @@ public List listSupportedLanguages(Map optionMap)
       public List translate(List texts, Map optionMap) {
         try {
           String targetLanguage =
    -          firstNonNull(TARGET_LANGUAGE.getString(optionMap), options.targetLanguage());
    +          firstNonNull(TARGET_LANGUAGE.getString(optionMap), options.getTargetLanguage());
           final String sourceLanguage = SOURCE_LANGUAGE.getString(optionMap);
           List translations =
               translate.translations()
                   .list(texts, targetLanguage)
                   .setSource(sourceLanguage)
    -              .setKey(options.apiKey())
    +              .setKey(options.getApiKey())
                   .execute()
                   .getTranslations();
           return Lists.transform(
    diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java
    index 6afe5c58d615..4819d9dd4be6 100644
    --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java
    +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/RemoteTranslateHelper.java
    @@ -21,13 +21,14 @@
     
     /**
      * Utility to create a remote translate configuration for testing. Translate options can be obtained
    - * via the {@link #getOptions()} method. Returned options have custom
    - * {@link TranslateOptions#retryParams()}: {@link RetryParams#retryMaxAttempts()} is {@code 10},
    - * {@link RetryParams#retryMinAttempts()} is {@code 6}, {@link RetryParams#maxRetryDelayMillis()}
    - * is {@code 30000}, {@link RetryParams#totalRetryPeriodMillis()} is {@code 120000} and
    - * {@link RetryParams#initialRetryDelayMillis()} is {@code 250}.
    - * {@link TranslateOptions#connectTimeout()} and {@link TranslateOptions#readTimeout()} are both set
    - * to {@code 60000}.
    + * via the {@link #getOptions()} ()} method. Returned options have custom
    + * {@link TranslateOptions#getRetryParams()}: {@link RetryParams#getRetryMaxAttempts()} is
    + * {@code 10}, {@link RetryParams#getRetryMinAttempts()} is {@code 6},
    + * {@link RetryParams#getMaxRetryDelayMillis()} is {@code 30000},
    + * {@link RetryParams#getTotalRetryPeriodMillis()} is {@code 120000} and
    + * {@link RetryParams#getInitialRetryDelayMillis()} is {@code 250}.
    + * {@link TranslateOptions#getConnectTimeout()} and {@link TranslateOptions#getReadTimeout()} are
    + * both set to {@code 60000}.
      */
     public class RemoteTranslateHelper {
     
    @@ -58,11 +59,11 @@ public TranslateOptions getOptions() {
        * @param apiKey API key used to issue requests to Google Translate.
        */
       public static RemoteTranslateHelper create(String apiKey) {
    -    TranslateOptions translateOptions = TranslateOptions.builder()
    -        .apiKey(apiKey)
    -        .retryParams(retryParams())
    -        .connectTimeout(60000)
    -        .readTimeout(60000)
    +    TranslateOptions translateOptions = TranslateOptions.newBuilder()
    +        .setApiKey(apiKey)
    +        .setRetryParams(retryParams())
    +        .setConnectTimeout(60000)
    +        .setReadTimeout(60000)
             .build();
         return new RemoteTranslateHelper(translateOptions);
       }
    @@ -71,21 +72,21 @@ public static RemoteTranslateHelper create(String apiKey) {
        * Creates a {@code RemoteStorageHelper} object.
        */
       public static RemoteTranslateHelper create() {
    -    TranslateOptions translateOption = TranslateOptions.builder()
    -        .retryParams(retryParams())
    -        .connectTimeout(60000)
    -        .readTimeout(60000)
    +    TranslateOptions translateOption = TranslateOptions.newBuilder()
    +        .setRetryParams(retryParams())
    +        .setConnectTimeout(60000)
    +        .setReadTimeout(60000)
             .build();
         return new RemoteTranslateHelper(translateOption);
       }
     
       private static RetryParams retryParams() {
    -    return RetryParams.builder()
    -        .retryMaxAttempts(10)
    -        .retryMinAttempts(6)
    -        .maxRetryDelayMillis(30000)
    -        .totalRetryPeriodMillis(120000)
    -        .initialRetryDelayMillis(250)
    +    return RetryParams.newBuilder()
    +        .setRetryMaxAttempts(10)
    +        .setRetryMinAttempts(6)
    +        .setMaxRetryDelayMillis(30000)
    +        .setTotalRetryPeriodMillis(120000)
    +        .setInitialRetryDelayMillis(250)
             .build();
       }
     }
    diff --git a/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/package-info.java b/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/package-info.java
    index d919feb87335..ff798c563896 100644
    --- a/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/package-info.java
    +++ b/google-cloud-translate/src/main/java/com/google/cloud/translate/testing/package-info.java
    @@ -21,7 +21,7 @@
      * 

    Before the test: *

     {@code
      * RemoteTranslateHelper helper = RemoteTranslateHelper.create();
    - * Translate translate = helper.getOptions().service();
    + * Translate translate = helper.getOptions().getService();
      * } 
    * * @see diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java index adc597a56301..b9b7a36d0201 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/SerializationTest.java @@ -46,12 +46,12 @@ public class SerializationTest extends BaseSerializationTest { @Override protected Serializable[] serializableObjects() { - TranslateOptions options = TranslateOptions.builder() - .apiKey(API_KEY) - .authCredentials(AuthCredentials.createForAppEngine()) + TranslateOptions options = TranslateOptions.newBuilder() + .setApiKey(API_KEY) + .setAuthCredentials(AuthCredentials.createForAppEngine()) .build(); TranslateOptions otherOptions = options.toBuilder() - .authCredentials(null) + .setAuthCredentials(null) .build(); return new Serializable[]{DETECTION, TRANSLATION, TRANSLATE_EXCEPTION, LANGUAGE_LIST_OPTION, TRANSLATE_OPTION, options, otherOptions}; diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateExceptionTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateExceptionTest.java index 13e2786ffe92..c7ac69fd2dac 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateExceptionTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateExceptionTest.java @@ -39,33 +39,33 @@ public class TranslateExceptionTest { @Test public void testTranslateException() { TranslateException exception = new TranslateException(500, "message"); - assertEquals(500, exception.code()); + assertEquals(500, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); exception = new TranslateException(400, "message"); - assertEquals(400, exception.code()); + assertEquals(400, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertFalse(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertFalse(exception.isRetryable()); + assertTrue(exception.isIdempotent()); IOException cause = new SocketTimeoutException(); exception = new TranslateException(cause); - assertNull(exception.reason()); + assertNull(exception.getReason()); assertNull(exception.getMessage()); - assertTrue(exception.retryable()); - assertTrue(exception.idempotent()); + assertTrue(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); exception = new TranslateException(400, "message", cause); - assertEquals(400, exception.code()); + assertEquals(400, exception.getCode()); assertEquals("message", exception.getMessage()); - assertNull(exception.reason()); - assertFalse(exception.retryable()); - assertTrue(exception.idempotent()); + assertNull(exception.getReason()); + assertFalse(exception.isRetryable()); + assertTrue(exception.isIdempotent()); assertSame(cause, exception.getCause()); } @@ -78,10 +78,10 @@ public void testTranslateAndThrow() throws Exception { try { TranslateException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(500, ex.code()); + assertEquals(500, ex.getCode()); assertEquals("message", ex.getMessage()); - assertTrue(ex.retryable()); - assertTrue(ex.idempotent()); + assertTrue(ex.isRetryable()); + assertTrue(ex.isIdempotent()); } finally { verify(exceptionMock); } @@ -93,10 +93,10 @@ public void testTranslateAndThrow() throws Exception { try { TranslateException.translateAndThrow(exceptionMock); } catch (BaseServiceException ex) { - assertEquals(TranslateException.UNKNOWN_CODE, ex.code()); + assertEquals(TranslateException.UNKNOWN_CODE, ex.getCode()); assertEquals("message", ex.getMessage()); - assertFalse(ex.retryable()); - assertTrue(ex.idempotent()); + assertFalse(ex.isRetryable()); + assertTrue(ex.isIdempotent()); assertSame(cause, ex.getCause()); } finally { verify(exceptionMock); diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateImplTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateImplTest.java index f3eb4b04bf92..cbf12dd6a03c 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateImplTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/TranslateImplTest.java @@ -105,10 +105,10 @@ public void setUp() { EasyMock.expect(rpcFactoryMock.create(EasyMock.anyObject(TranslateOptions.class))) .andReturn(translateRpcMock); EasyMock.replay(rpcFactoryMock); - options = TranslateOptions.builder() - .apiKey(API_KEY) - .serviceRpcFactory(rpcFactoryMock) - .retryParams(RetryParams.noRetries()) + options = TranslateOptions.newBuilder() + .setApiKey(API_KEY) + .setServiceRpcFactory(rpcFactoryMock) + .setRetryParams(RetryParams.noRetries()) .build(); } @@ -118,14 +118,14 @@ public void tearDown() throws Exception { } private void initializeService() { - translate = options.service(); + translate = options.getService(); } @Test public void testGetOptions() { EasyMock.replay(translateRpcMock); initializeService(); - assertSame(options, translate.options()); + assertSame(options, translate.getOptions()); } @Test @@ -318,7 +318,8 @@ public void testRetryableException() { .andThrow(new TranslateException(500, "internalError")) .andReturn(ImmutableList.of(LANGUAGE1_PB, LANGUAGE2_PB)); EasyMock.replay(translateRpcMock); - translate = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); + translate = + options.toBuilder().setRetryParams(RetryParams.getDefaultInstance()).build().getService(); assertEquals(LANGUAGES1, translate.listSupportedLanguages()); } @@ -328,7 +329,8 @@ public void testNonRetryableException() { EasyMock.expect(translateRpcMock.listSupportedLanguages(EMPTY_RPC_OPTIONS)) .andThrow(new TranslateException(501, exceptionMessage)); EasyMock.replay(translateRpcMock); - translate = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); + translate = + options.toBuilder().setRetryParams(RetryParams.getDefaultInstance()).build().getService(); thrown.expect(TranslateException.class); thrown.expectMessage(exceptionMessage); translate.listSupportedLanguages(); @@ -340,7 +342,8 @@ public void testRuntimeException() { EasyMock.expect(translateRpcMock.listSupportedLanguages(EMPTY_RPC_OPTIONS)) .andThrow(new RuntimeException(exceptionMessage)); EasyMock.replay(translateRpcMock); - translate = options.toBuilder().retryParams(RetryParams.defaultInstance()).build().service(); + translate = + options.toBuilder().setRetryParams(RetryParams.getDefaultInstance()).build().getService(); thrown.expect(TranslateException.class); thrown.expectMessage(exceptionMessage); translate.listSupportedLanguages(); diff --git a/google-cloud-translate/src/test/java/com/google/cloud/translate/it/ITTranslateTest.java b/google-cloud-translate/src/test/java/com/google/cloud/translate/it/ITTranslateTest.java index 78e7fd11793e..29931cd3c016 100644 --- a/google-cloud-translate/src/test/java/com/google/cloud/translate/it/ITTranslateTest.java +++ b/google-cloud-translate/src/test/java/com/google/cloud/translate/it/ITTranslateTest.java @@ -37,7 +37,8 @@ public class ITTranslateTest { - private static final Translate TRANSLATE = RemoteTranslateHelper.create().getOptions().service(); + private static final Translate TRANSLATE = + RemoteTranslateHelper.create().getOptions().getService(); private static final String[] LANGUAGES = {"af", "sq", "ar", "hy", "az", "eu", "be", "bn", "bs", "bg", "ca", "ceb", "ny", "zh-TW", "hr", "cs", "da", "nl", "en", "eo", "et", "tl", "fi", "fr", "gl", "ka", "de", "el", "gu", "ht", "ha", "iw", "hi", "hmn", "hu", "is", "ig", "id", "ga", diff --git a/src/site/resources/index.html b/src/site/resources/index.html index e1475a02293a..fc12b63af004 100644 --- a/src/site/resources/index.html +++ b/src/site/resources/index.html @@ -162,8 +162,9 @@

    Example: Retrieve Datastore Entries

    // Authentication is automatic inside Google Compute Engine // and Google App Engine. -Datastore datastore = DatastoreOptions.defaultInstance().service(); -KeyFactory keyFactory = datastore.newKeyFactory().kind(KIND); +Datastore datastore = + DatastoreOptions.getDefaultInstance().getService(); +KeyFactory keyFactory = datastore.newKeyFactory().setKind(KIND); Key key = keyFactory.newKey(keyName); Entity entity = datastore.get(key); @@ -178,12 +179,12 @@

    Example: Retrieve Datastore Entries

    import com.google.cloud.datastore.Key; import com.google.cloud.datastore.KeyFactory; -DatastoreOptions options = DatastoreOptions.builder() - .projectId(PROJECT_ID) - .authCredentials(AuthCredentials.createForJson( +DatastoreOptions options = DatastoreOptions.newBuilder() + .setProjectId(PROJECT_ID) + .setAuthCredentials(AuthCredentials.createForJson( new FileInputStream(PATH_TO_JSON_KEY))).build(); -Datastore datastore = options.service(); -KeyFactory keyFactory = datastore.newKeyFactory().kind(KIND); +Datastore datastore = options.getService(); +KeyFactory keyFactory = datastore.newKeyFactory().setKind(KIND); Key key = keyFactory.newKey(keyName); Entity entity = datastore.get(key);
    From b26ce38365d69dd92af2a3fdd8bb875cccf8e363 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Sat, 29 Oct 2016 16:25:42 +0200 Subject: [PATCH 29/32] Release 0.5.0 --- google-cloud-bigquery/pom.xml | 2 +- google-cloud-compute/pom.xml | 2 +- google-cloud-contrib/google-cloud-nio-examples/pom.xml | 2 +- google-cloud-contrib/google-cloud-nio/pom.xml | 2 +- google-cloud-contrib/pom.xml | 2 +- google-cloud-core/pom.xml | 2 +- google-cloud-datastore/pom.xml | 2 +- google-cloud-dns/pom.xml | 2 +- google-cloud-errorreporting/pom.xml | 2 +- google-cloud-examples/pom.xml | 2 +- google-cloud-language/pom.xml | 2 +- google-cloud-logging/pom.xml | 2 +- google-cloud-monitoring/pom.xml | 2 +- google-cloud-pubsub/pom.xml | 2 +- google-cloud-resourcemanager/pom.xml | 2 +- google-cloud-speech/pom.xml | 2 +- google-cloud-storage/pom.xml | 2 +- google-cloud-trace/pom.xml | 2 +- google-cloud-translate/pom.xml | 2 +- google-cloud-vision/pom.xml | 2 +- google-cloud/pom.xml | 2 +- pom.xml | 2 +- 22 files changed, 22 insertions(+), 22 deletions(-) diff --git a/google-cloud-bigquery/pom.xml b/google-cloud-bigquery/pom.xml index f623dd7ca343..225c8be66b83 100644 --- a/google-cloud-bigquery/pom.xml +++ b/google-cloud-bigquery/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-bigquery diff --git a/google-cloud-compute/pom.xml b/google-cloud-compute/pom.xml index 5c8d0efe528a..c42c7e1e7b29 100644 --- a/google-cloud-compute/pom.xml +++ b/google-cloud-compute/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-compute diff --git a/google-cloud-contrib/google-cloud-nio-examples/pom.xml b/google-cloud-contrib/google-cloud-nio-examples/pom.xml index 799ec387710b..d0b4e27bac7a 100644 --- a/google-cloud-contrib/google-cloud-nio-examples/pom.xml +++ b/google-cloud-contrib/google-cloud-nio-examples/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-contrib - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-nio-examples diff --git a/google-cloud-contrib/google-cloud-nio/pom.xml b/google-cloud-contrib/google-cloud-nio/pom.xml index c4fe132764f5..1ed2df9becd4 100644 --- a/google-cloud-contrib/google-cloud-nio/pom.xml +++ b/google-cloud-contrib/google-cloud-nio/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-contrib - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-nio diff --git a/google-cloud-contrib/pom.xml b/google-cloud-contrib/pom.xml index 45a4fce5072b..1b6803322572 100644 --- a/google-cloud-contrib/pom.xml +++ b/google-cloud-contrib/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-contrib diff --git a/google-cloud-core/pom.xml b/google-cloud-core/pom.xml index 1ea4eb6cceb8..ec6c284be56b 100644 --- a/google-cloud-core/pom.xml +++ b/google-cloud-core/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-core diff --git a/google-cloud-datastore/pom.xml b/google-cloud-datastore/pom.xml index 67aff1bd2ef3..25ea5a2fa87c 100644 --- a/google-cloud-datastore/pom.xml +++ b/google-cloud-datastore/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-datastore diff --git a/google-cloud-dns/pom.xml b/google-cloud-dns/pom.xml index 91ce85326766..fad39b1b6029 100644 --- a/google-cloud-dns/pom.xml +++ b/google-cloud-dns/pom.xml @@ -13,7 +13,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-dns diff --git a/google-cloud-errorreporting/pom.xml b/google-cloud-errorreporting/pom.xml index 31e9d3d9727a..962bdb5f6b1a 100644 --- a/google-cloud-errorreporting/pom.xml +++ b/google-cloud-errorreporting/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-errorreporting diff --git a/google-cloud-examples/pom.xml b/google-cloud-examples/pom.xml index 45d3218ea6cd..1bd1995c5d6f 100644 --- a/google-cloud-examples/pom.xml +++ b/google-cloud-examples/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-examples diff --git a/google-cloud-language/pom.xml b/google-cloud-language/pom.xml index 90663b119546..060857a97ca9 100644 --- a/google-cloud-language/pom.xml +++ b/google-cloud-language/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-language diff --git a/google-cloud-logging/pom.xml b/google-cloud-logging/pom.xml index c277ef51017f..6d4b0cd71ceb 100644 --- a/google-cloud-logging/pom.xml +++ b/google-cloud-logging/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-logging diff --git a/google-cloud-monitoring/pom.xml b/google-cloud-monitoring/pom.xml index 7df6f00c2df9..9c07e5f013c7 100644 --- a/google-cloud-monitoring/pom.xml +++ b/google-cloud-monitoring/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-monitoring diff --git a/google-cloud-pubsub/pom.xml b/google-cloud-pubsub/pom.xml index 4f6d7b884d81..0a57376ae6b2 100644 --- a/google-cloud-pubsub/pom.xml +++ b/google-cloud-pubsub/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-pubsub diff --git a/google-cloud-resourcemanager/pom.xml b/google-cloud-resourcemanager/pom.xml index 1ef16075f131..ac6dbedf677a 100644 --- a/google-cloud-resourcemanager/pom.xml +++ b/google-cloud-resourcemanager/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-resourcemanager diff --git a/google-cloud-speech/pom.xml b/google-cloud-speech/pom.xml index 012c047afebf..627b64d9ba67 100644 --- a/google-cloud-speech/pom.xml +++ b/google-cloud-speech/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-speech diff --git a/google-cloud-storage/pom.xml b/google-cloud-storage/pom.xml index 219e4abfc1b3..ac7ad5b6c0e0 100644 --- a/google-cloud-storage/pom.xml +++ b/google-cloud-storage/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-storage diff --git a/google-cloud-trace/pom.xml b/google-cloud-trace/pom.xml index d2c241bc0c27..5d210f892d7b 100644 --- a/google-cloud-trace/pom.xml +++ b/google-cloud-trace/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-trace diff --git a/google-cloud-translate/pom.xml b/google-cloud-translate/pom.xml index 81d85e710d6a..75d24b46a9ef 100644 --- a/google-cloud-translate/pom.xml +++ b/google-cloud-translate/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-translate diff --git a/google-cloud-vision/pom.xml b/google-cloud-vision/pom.xml index 66a6cb76b2f2..9a6d5888cf23 100644 --- a/google-cloud-vision/pom.xml +++ b/google-cloud-vision/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 google-cloud-vision diff --git a/google-cloud/pom.xml b/google-cloud/pom.xml index d0ec54a3e311..41e8fa44ecdd 100644 --- a/google-cloud/pom.xml +++ b/google-cloud/pom.xml @@ -11,7 +11,7 @@ com.google.cloud google-cloud-pom - 0.4.1-SNAPSHOT + 0.5.0 diff --git a/pom.xml b/pom.xml index 1518b6bdcacc..25f8a37e6aba 100644 --- a/pom.xml +++ b/pom.xml @@ -4,7 +4,7 @@ com.google.cloud google-cloud-pom pom - 0.4.1-SNAPSHOT + 0.5.0 Google Cloud https://github.com/GoogleCloudPlatform/google-cloud-java From bad3e3e7c8bc76d640c7eb9720af09ee8cbcefd4 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Sat, 29 Oct 2016 16:26:55 +0200 Subject: [PATCH 30/32] Fix monitoring grouping in javadoc landing page --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 25f8a37e6aba..2c074852f247 100644 --- a/pom.xml +++ b/pom.xml @@ -416,7 +416,7 @@ SPI packages - com.google.cloud.spi:com.google.cloud.bigquery.spi:com.google.cloud.compute.spi:com.google.cloud.datastore.spi:com.google.cloud.dns.spi:com.google.cloud.errorreporting.spi:com.google.cloud.errorreporting.spi.*:com.google.cloud.language.spi:com.google.cloud.language.spi.*:com.google.cloud.logging.spi:com.google.cloud.logging.spi.*:com.google.cloud.pubsub.spi:com.google.cloud.pubsub.spi.*:com.google.cloud.resourcemanager.spi:com.google.cloud.speech.spi:com.google.cloud.speech.spi.*:com.google.cloud.storage.spi:com.google.cloud.trace.spi:com.google.cloud.trace.spi.*:com.google.cloud.translate.spi:com.google.cloud.vision.spi:com.google.cloud.vision.spi.* + com.google.cloud.spi:com.google.cloud.bigquery.spi:com.google.cloud.compute.spi:com.google.cloud.datastore.spi:com.google.cloud.dns.spi:com.google.cloud.errorreporting.spi:com.google.cloud.errorreporting.spi.*:com.google.cloud.language.spi:com.google.cloud.language.spi.*:com.google.cloud.logging.spi:com.google.cloud.monitoring.spi:com.google.cloud.monitoring.spi.*:com.google.cloud.logging.spi.*:com.google.cloud.pubsub.spi:com.google.cloud.pubsub.spi.*:com.google.cloud.resourcemanager.spi:com.google.cloud.speech.spi:com.google.cloud.speech.spi.*:com.google.cloud.storage.spi:com.google.cloud.trace.spi:com.google.cloud.trace.spi.*:com.google.cloud.translate.spi:com.google.cloud.vision.spi:com.google.cloud.vision.spi.* From 1446c919174be87fe5fe7667cf1522139b649ed9 Mon Sep 17 00:00:00 2001 From: Marco Ziccardi Date: Sat, 29 Oct 2016 16:28:16 +0200 Subject: [PATCH 31/32] Add travis_wait to avoid build timeout on mvn site --- utilities/after_success.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utilities/after_success.sh b/utilities/after_success.sh index aacbe20f451f..d434e282f5c2 100755 --- a/utilities/after_success.sh +++ b/utilities/after_success.sh @@ -33,7 +33,7 @@ if [ "${TRAVIS_JDK_VERSION}" == "oraclejdk7" ]; then git config --global user.email "travis@travis-ci.org" git clone --branch gh-pages --single-branch https://github.com/GoogleCloudPlatform/google-cloud-java/ tmp_gh-pages mkdir -p tmp_gh-pages/$SITE_VERSION - mvn site -DskipTests=true --quiet -Djava.util.logging.config.file=logging.properties + travis_wait mvn site -DskipTests=true --quiet -Djava.util.logging.config.file=logging.properties mvn site:stage --quiet -Djava.util.logging.config.file=logging.properties -DtopSiteURL=http://googlecloudplatform.github.io/google-cloud-java/site/${SITE_VERSION}/ cd tmp_gh-pages cp -r ../target/staging/$SITE_VERSION/* $SITE_VERSION/ From 798b774a37765cdf8446ed928c13bf8daaef8b70 Mon Sep 17 00:00:00 2001 From: travis-ci Date: Sat, 29 Oct 2016 17:20:07 +0000 Subject: [PATCH 32/32] Updating version in README files. [ci skip] --- README.md | 6 +++--- google-cloud-bigquery/README.md | 6 +++--- google-cloud-compute/README.md | 6 +++--- google-cloud-contrib/README.md | 6 +++--- google-cloud-contrib/google-cloud-nio-examples/README.md | 4 ++-- google-cloud-contrib/google-cloud-nio/README.md | 6 +++--- google-cloud-core/README.md | 6 +++--- google-cloud-datastore/README.md | 6 +++--- google-cloud-dns/README.md | 6 +++--- google-cloud-examples/README.md | 6 +++--- google-cloud-logging/README.md | 6 +++--- google-cloud-pubsub/README.md | 6 +++--- google-cloud-resourcemanager/README.md | 6 +++--- google-cloud-storage/README.md | 6 +++--- google-cloud-translate/README.md | 6 +++--- google-cloud/README.md | 6 +++--- 16 files changed, 47 insertions(+), 47 deletions(-) diff --git a/README.md b/README.md index fddbf051442a..b2d0f77344d0 100644 --- a/README.md +++ b/README.md @@ -40,16 +40,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud:0.4.0' +compile 'com.google.cloud:google-cloud:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud" % "0.5.0" ``` Example Applications diff --git a/google-cloud-bigquery/README.md b/google-cloud-bigquery/README.md index b31f8706666b..45df6046fb56 100644 --- a/google-cloud-bigquery/README.md +++ b/google-cloud-bigquery/README.md @@ -22,16 +22,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud-bigquery - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-bigquery:0.4.0' +compile 'com.google.cloud:google-cloud-bigquery:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-bigquery" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-bigquery" % "0.5.0" ``` Example Application diff --git a/google-cloud-compute/README.md b/google-cloud-compute/README.md index 72bff7504ba1..91a87e5c298c 100644 --- a/google-cloud-compute/README.md +++ b/google-cloud-compute/README.md @@ -22,16 +22,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud-compute - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-compute:0.4.0' +compile 'com.google.cloud:google-cloud-compute:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-compute" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-compute" % "0.5.0" ``` Example Application diff --git a/google-cloud-contrib/README.md b/google-cloud-contrib/README.md index 5ef284b1faea..571b58703627 100644 --- a/google-cloud-contrib/README.md +++ b/google-cloud-contrib/README.md @@ -25,16 +25,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud-contrib - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-contrib:0.4.0' +compile 'com.google.cloud:google-cloud-contrib:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-contrib" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-contrib" % "0.5.0" ``` ### google-cloud-nio-examples diff --git a/google-cloud-contrib/google-cloud-nio-examples/README.md b/google-cloud-contrib/google-cloud-nio-examples/README.md index 29cbf0978dbb..5f93fac3f8cc 100644 --- a/google-cloud-contrib/google-cloud-nio-examples/README.md +++ b/google-cloud-contrib/google-cloud-nio-examples/README.md @@ -22,12 +22,12 @@ To run this example: 4. Run the sample with: ``` - java -cp google-cloud-contrib/google-cloud-nio/target/google-cloud-nio-0.4.1-SNAPSHOT-shaded.jar:google-cloud-contrib/google-cloud-nio-examples/target/google-cloud-nio-examples-0.4.1-SNAPSHOT.jar com.google.cloud.nio.examples.ListFilesystems + java -cp google-cloud-contrib/google-cloud-nio/target/google-cloud-nio-0.5.1-SNAPSHOT-shaded.jar:google-cloud-contrib/google-cloud-nio-examples/target/google-cloud-nio-examples-0.5.1-SNAPSHOT.jar com.google.cloud.nio.examples.ListFilesystems ``` Notice that it lists Google Cloud Storage, which it wouldn't if you ran it without the NIO jar: ``` - java -cp google-cloud-contrib/google-cloud-nio-examples/target/google-cloud-nio-examples-0.4.1-SNAPSHOT.jar com.google.cloud.nio.examples.ListFilesystems + java -cp google-cloud-contrib/google-cloud-nio-examples/target/google-cloud-nio-examples-0.5.1-SNAPSHOT.jar com.google.cloud.nio.examples.ListFilesystems ``` The sample doesn't have anything about Google Cloud Storage in it. It gets that ability from the NIO diff --git a/google-cloud-contrib/google-cloud-nio/README.md b/google-cloud-contrib/google-cloud-nio/README.md index c3429dc19995..c10777e033e8 100644 --- a/google-cloud-contrib/google-cloud-nio/README.md +++ b/google-cloud-contrib/google-cloud-nio/README.md @@ -26,16 +26,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud-nio - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-nio:0.4.0' +compile 'com.google.cloud:google-cloud-nio:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-nio" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-nio" % "0.5.0" ``` Example Applications diff --git a/google-cloud-core/README.md b/google-cloud-core/README.md index aabe170ffe50..e727be8f5397 100644 --- a/google-cloud-core/README.md +++ b/google-cloud-core/README.md @@ -19,16 +19,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud-core - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-core:0.4.0' +compile 'com.google.cloud:google-cloud-core:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-core" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-core" % "0.5.0" ``` Troubleshooting diff --git a/google-cloud-datastore/README.md b/google-cloud-datastore/README.md index 4c979c88a10d..37d0532a1759 100644 --- a/google-cloud-datastore/README.md +++ b/google-cloud-datastore/README.md @@ -22,16 +22,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud-datastore - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-datastore:0.4.0' +compile 'com.google.cloud:google-cloud-datastore:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-datastore" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-datastore" % "0.5.0" ``` Example Application diff --git a/google-cloud-dns/README.md b/google-cloud-dns/README.md index 422bcaa447cc..c3d09c875e62 100644 --- a/google-cloud-dns/README.md +++ b/google-cloud-dns/README.md @@ -22,16 +22,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud-dns - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-dns:0.4.0' +compile 'com.google.cloud:google-cloud-dns:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-dns" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-dns" % "0.5.0" ``` Example Application diff --git a/google-cloud-examples/README.md b/google-cloud-examples/README.md index 101f6de6f936..238c33cdc797 100644 --- a/google-cloud-examples/README.md +++ b/google-cloud-examples/README.md @@ -19,16 +19,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud-examples - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-examples:0.4.0' +compile 'com.google.cloud:google-cloud-examples:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-examples" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-examples" % "0.5.0" ``` To run examples from your command line: diff --git a/google-cloud-logging/README.md b/google-cloud-logging/README.md index 52b7ade043d6..42986d817140 100644 --- a/google-cloud-logging/README.md +++ b/google-cloud-logging/README.md @@ -26,16 +26,16 @@ Add this to your pom.xml file com.google.cloud google-cloud-logging - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-logging:0.4.0' +compile 'com.google.cloud:google-cloud-logging:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-logging" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-logging" % "0.5.0" ``` Example Application diff --git a/google-cloud-pubsub/README.md b/google-cloud-pubsub/README.md index 446a3c148ba4..b1a1b11fe2bd 100644 --- a/google-cloud-pubsub/README.md +++ b/google-cloud-pubsub/README.md @@ -26,16 +26,16 @@ Add this to your pom.xml file com.google.cloud google-cloud-pubsub - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-pubsub:0.4.0' +compile 'com.google.cloud:google-cloud-pubsub:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-pubsub" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-pubsub" % "0.5.0" ``` Example Application diff --git a/google-cloud-resourcemanager/README.md b/google-cloud-resourcemanager/README.md index 8ebf987bbb74..dde2a051adf2 100644 --- a/google-cloud-resourcemanager/README.md +++ b/google-cloud-resourcemanager/README.md @@ -22,16 +22,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud-resourcemanager - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-resourcemanager:0.4.0' +compile 'com.google.cloud:google-cloud-resourcemanager:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-resourcemanager" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-resourcemanager" % "0.5.0" ``` Example Application diff --git a/google-cloud-storage/README.md b/google-cloud-storage/README.md index 57c2d37e29e8..4dee9eeac7ac 100644 --- a/google-cloud-storage/README.md +++ b/google-cloud-storage/README.md @@ -22,16 +22,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud-storage - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-storage:0.4.0' +compile 'com.google.cloud:google-cloud-storage:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-storage" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-storage" % "0.5.0" ``` Example Application diff --git a/google-cloud-translate/README.md b/google-cloud-translate/README.md index 1d57a2727e41..09b8df329bc7 100644 --- a/google-cloud-translate/README.md +++ b/google-cloud-translate/README.md @@ -22,16 +22,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud-translate - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud-translate:0.4.0' +compile 'com.google.cloud:google-cloud-translate:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud-translate" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud-translate" % "0.5.0" ``` Example Application diff --git a/google-cloud/README.md b/google-cloud/README.md index 40d24bf32177..8d8dd0d6b805 100644 --- a/google-cloud/README.md +++ b/google-cloud/README.md @@ -27,16 +27,16 @@ If you are using Maven, add this to your pom.xml file com.google.cloud google-cloud - 0.4.0 + 0.5.0 ``` If you are using Gradle, add this to your dependencies ```Groovy -compile 'com.google.cloud:google-cloud:0.4.0' +compile 'com.google.cloud:google-cloud:0.5.0' ``` If you are using SBT, add this to your dependencies ```Scala -libraryDependencies += "com.google.cloud" % "google-cloud" % "0.4.0" +libraryDependencies += "com.google.cloud" % "google-cloud" % "0.5.0" ``` Troubleshooting