google-cloud-core
diff --git a/google-cloud-core/src/main/java/com/google/cloud/GcpLaunchStage.java b/google-cloud-core/src/main/java/com/google/cloud/GcpLaunchStage.java
new file mode 100644
index 000000000000..af4b951f34b1
--- /dev/null
+++ b/google-cloud-core/src/main/java/com/google/cloud/GcpLaunchStage.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2017 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;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+/**
+ * A qualifier indicating what level of access and support can be expected of a particular Google
+ * Cloud Platform feature. The "GeneralAvailability" qualifier is not provided since the vast
+ * majority of features are in this category. Note that features may be in a later launch stage
+ * than the client library annotation indicates.
+ *
+ * See more at the Launch Stages Documentation .
+ */
+public class GcpLaunchStage {
+
+ /**
+ * Early Access features are limited to a closed group of testers. To use these features, you must
+ * sign up in advance and sign a Trusted Tester agreement (which includes confidentiality
+ * provisions). These features may be unstable, changed in backward-incompatible ways, and are not
+ * guaranteed to be released.
+ */
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface EarlyAccess {}
+
+ /**
+ * Alpha is a limited availability test for releases before they are cleared for widespread use.
+ * By Alpha, all significant design issues are resolved and we are in the process of verifying
+ * functionality. Alpha customers need to apply for access, agree to applicable terms, and have
+ * their projects whitelisted. Alpha releases don’t have to be feature complete, no SLAs are
+ * provided, and there are no technical support obligations, but they will be far enough along
+ * that customers can actually use them in test environments or for limited-use tests -- just like
+ * they would in normal production cases.
+ */
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface Alpha {}
+
+ /**
+ * Beta is the point at which we are ready to open a release for any customer to use. There are no
+ * SLA or technical support obligations in a Beta release, and charges may be waived in some
+ * cases. Products will be complete from a feature perspective, but may have some open outstanding
+ * issues. Beta releases are suitable for limited production use cases.
+ */
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface Beta {}
+
+ /**
+ * Deprecated features are scheduled to be shut down and removed. For more information, see the
+ * “Deprecation Policy” section of our Terms of Service
+ * and the Google Cloud Platform Subject to the Deprecation Policy
+ * documentation.
+ */
+ @Retention(RetentionPolicy.RUNTIME)
+ public @interface Deprecated {}
+
+ private GcpLaunchStage() {
+ // Intentionally left blank.
+ }
+}
diff --git a/google-cloud-core/src/main/java/com/google/cloud/GrpcTransportOptions.java b/google-cloud-core/src/main/java/com/google/cloud/GrpcTransportOptions.java
index 0295b00972c9..f27ace8b01b3 100644
--- a/google-cloud-core/src/main/java/com/google/cloud/GrpcTransportOptions.java
+++ b/google-cloud-core/src/main/java/com/google/cloud/GrpcTransportOptions.java
@@ -210,23 +210,21 @@ public UnaryCallSettings.Builder getApiCallSettings(RetrySettings retrySettings)
}
/**
- * Returns a channel provider.
+ * Returns a channel provider from the given default provider.
*/
- public static ChannelProvider getChannelProvider(
- ServiceOptions, ?> serviceOptions) {
- HostAndPort hostAndPort = HostAndPort.fromString(serviceOptions.getHost());
- InstantiatingChannelProvider.Builder builder = InstantiatingChannelProvider.newBuilder()
- .setServiceAddress(hostAndPort.getHostText())
- .setPort(hostAndPort.getPort())
- .setClientLibHeader(serviceOptions.getGoogApiClientLibName(),
- firstNonNull(serviceOptions.getLibraryVersion(), ""));
+ public static ChannelProvider setUpChannelProvider(
+ InstantiatingChannelProvider.Builder providerBuilder, ServiceOptions, ?> serviceOptions) {
+ providerBuilder.setEndpoint(serviceOptions.getHost())
+ .setClientLibHeader(ServiceOptions.getGoogApiClientLibName(),
+ firstNonNull(ServiceOptions.getLibraryVersion(), ""));
Credentials scopedCredentials = serviceOptions.getScopedCredentials();
if (scopedCredentials != null && scopedCredentials != NoCredentials.getInstance()) {
- builder.setCredentialsProvider(FixedCredentialsProvider.create(scopedCredentials));
+ providerBuilder.setCredentialsProvider(FixedCredentialsProvider.create(scopedCredentials));
}
- return builder.build();
+ return providerBuilder.build();
}
+
/**
* Returns the timeout for the initial RPC, in milliseconds. Subsequent calls will use this value
* adjusted according to {@link #getTimeoutMultiplier()}. Default value is 20000.
diff --git a/google-cloud-core/src/main/java/com/google/cloud/HttpTransportOptions.java b/google-cloud-core/src/main/java/com/google/cloud/HttpTransportOptions.java
index 970ca555fea6..9308704eb116 100644
--- a/google-cloud-core/src/main/java/com/google/cloud/HttpTransportOptions.java
+++ b/google-cloud-core/src/main/java/com/google/cloud/HttpTransportOptions.java
@@ -50,8 +50,9 @@ public static class DefaultHttpTransportFactory implements HttpTransportFactory
@Override
public HttpTransport create() {
- // Consider App Engine
- if (ServiceOptions.getAppEngineAppId() != null) {
+ // Consider App Engine Standard
+ if (System.getProperty("com.google.appengine.runtime.version") != null
+ && System.getenv("GAE_SERVICE") == null) {
try {
return new UrlFetchTransport();
} catch (Exception ignore) {
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 c8fc044086ea..0de5cdc9652c 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
@@ -202,7 +202,6 @@ public final Builder removeIdentity(Role role, Identity first, Identity... other
return this;
}
-
/**
* Sets the policy's etag.
*
@@ -214,7 +213,7 @@ 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.
*/
- protected final Builder setEtag(String etag) {
+ public final Builder setEtag(String etag) {
this.etag = etag;
return this;
}
diff --git a/google-cloud-datastore/README.md b/google-cloud-datastore/README.md
index a5257b775521..d4ef802f8442 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.10.0-beta
+ 0.12.0-beta
```
If you are using Gradle, add this to your dependencies
```Groovy
-compile 'com.google.cloud:google-cloud-datastore:0.10.0-beta'
+compile 'com.google.cloud:google-cloud-datastore:0.12.0-beta'
```
If you are using SBT, add this to your dependencies
```Scala
-libraryDependencies += "com.google.cloud" % "google-cloud-datastore" % "0.10.0-beta"
+libraryDependencies += "com.google.cloud" % "google-cloud-datastore" % "0.12.0-beta"
```
Example Application
diff --git a/google-cloud-datastore/pom.xml b/google-cloud-datastore/pom.xml
index 227f57035b78..6c70ce2b0778 100644
--- a/google-cloud-datastore/pom.xml
+++ b/google-cloud-datastore/pom.xml
@@ -12,7 +12,7 @@
com.google.cloud
google-cloud-pom
- 0.10.1-alpha-SNAPSHOT
+ 0.12.1-alpha-SNAPSHOT
google-cloud-datastore
diff --git a/google-cloud-dns/README.md b/google-cloud-dns/README.md
index 74955f6faa38..43667e82bcb9 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.10.0-alpha
+ 0.12.0-alpha
```
If you are using Gradle, add this to your dependencies
```Groovy
-compile 'com.google.cloud:google-cloud-dns:0.10.0-alpha'
+compile 'com.google.cloud:google-cloud-dns:0.12.0-alpha'
```
If you are using SBT, add this to your dependencies
```Scala
-libraryDependencies += "com.google.cloud" % "google-cloud-dns" % "0.10.0-alpha"
+libraryDependencies += "com.google.cloud" % "google-cloud-dns" % "0.12.0-alpha"
```
Example Application
diff --git a/google-cloud-dns/pom.xml b/google-cloud-dns/pom.xml
index c41bcb25883a..523b1ccb25da 100644
--- a/google-cloud-dns/pom.xml
+++ b/google-cloud-dns/pom.xml
@@ -13,7 +13,7 @@
com.google.cloud
google-cloud-pom
- 0.10.1-alpha-SNAPSHOT
+ 0.12.1-alpha-SNAPSHOT
google-cloud-dns
diff --git a/google-cloud-errorreporting/pom.xml b/google-cloud-errorreporting/pom.xml
index ea8a101eb06e..45ee768073d2 100644
--- a/google-cloud-errorreporting/pom.xml
+++ b/google-cloud-errorreporting/pom.xml
@@ -11,10 +11,11 @@
com.google.cloud
google-cloud-pom
- 0.10.1-alpha-SNAPSHOT
+ 0.12.1-alpha-SNAPSHOT
google-cloud-errorreporting
+ ${project.version}
@@ -87,6 +88,22 @@
+
+ org.codehaus.mojo
+ properties-maven-plugin
+ 1.0-alpha-2
+
+
+ generate-resources
+
+ write-project-properties
+
+
+ ${project.build.outputDirectory}/project.properties
+
+
+
+
org.codehaus.mojo
build-helper-maven-plugin
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 bcfd793f9908..ddb60e977e77 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,6 +16,7 @@
package com.google.cloud.errorreporting.spi.v1beta1;
import com.google.api.gax.core.GoogleCredentialsProvider;
+import com.google.api.gax.core.PropertiesProvider;
import com.google.api.gax.core.RetrySettings;
import com.google.api.gax.grpc.ChannelProvider;
import com.google.api.gax.grpc.ClientSettings;
@@ -69,12 +70,6 @@
@Generated("by GAPIC v0.0.5")
@ExperimentalApi
public class ErrorGroupServiceSettings extends ClientSettings {
- /** The default address of the service. */
- private static final String DEFAULT_SERVICE_ADDRESS = "clouderrorreporting.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().add("https://www.googleapis.com/auth/cloud-platform").build();
@@ -82,6 +77,11 @@ public class ErrorGroupServiceSettings extends ClientSettings {
private static final String DEFAULT_GAPIC_NAME = "gapic";
private static final String DEFAULT_GAPIC_VERSION = "";
+ private static final String PROPERTIES_FILE = "/project.properties";
+ private static final String META_VERSION_KEY = "artifact.version";
+
+ private static String gapicVersion;
+
private final SimpleCallSettings getGroupSettings;
private final SimpleCallSettings updateGroupSettings;
@@ -100,14 +100,9 @@ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuild
return InstantiatingExecutorProvider.newBuilder();
}
- /** 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 endpoint. */
+ public static String getDefaultEndpoint() {
+ return "clouderrorreporting.googleapis.com:443";
}
/** Returns the default service scopes. */
@@ -123,15 +118,19 @@ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilde
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingChannelProvider.Builder defaultChannelProviderBuilder() {
return InstantiatingChannelProvider.newBuilder()
- .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
- .setPort(DEFAULT_SERVICE_PORT)
+ .setEndpoint(getDefaultEndpoint())
.setGeneratorHeader(DEFAULT_GAPIC_NAME, getGapicVersion())
.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
}
private static String getGapicVersion() {
- String packageVersion = ErrorGroupServiceSettings.class.getPackage().getImplementationVersion();
- return packageVersion != null ? packageVersion : DEFAULT_GAPIC_VERSION;
+ if (gapicVersion == null) {
+ gapicVersion =
+ PropertiesProvider.loadProperty(
+ ErrorGroupServiceSettings.class, PROPERTIES_FILE, META_VERSION_KEY);
+ gapicVersion = gapicVersion == null ? DEFAULT_GAPIC_VERSION : gapicVersion;
+ }
+ return gapicVersion;
}
/** Returns a builder for this class with recommended defaults. */
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 7029ae4619de..694db283b3d2 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
@@ -19,6 +19,7 @@
import static com.google.cloud.errorreporting.spi.v1beta1.PagedResponseWrappers.ListGroupStatsPagedResponse;
import com.google.api.gax.core.GoogleCredentialsProvider;
+import com.google.api.gax.core.PropertiesProvider;
import com.google.api.gax.core.RetrySettings;
import com.google.api.gax.grpc.CallContext;
import com.google.api.gax.grpc.ChannelProvider;
@@ -82,12 +83,6 @@
@Generated("by GAPIC v0.0.5")
@ExperimentalApi
public class ErrorStatsServiceSettings extends ClientSettings {
- /** The default address of the service. */
- private static final String DEFAULT_SERVICE_ADDRESS = "clouderrorreporting.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().add("https://www.googleapis.com/auth/cloud-platform").build();
@@ -95,6 +90,11 @@ public class ErrorStatsServiceSettings extends ClientSettings {
private static final String DEFAULT_GAPIC_NAME = "gapic";
private static final String DEFAULT_GAPIC_VERSION = "";
+ private static final String PROPERTIES_FILE = "/project.properties";
+ private static final String META_VERSION_KEY = "artifact.version";
+
+ private static String gapicVersion;
+
private final PagedCallSettings<
ListGroupStatsRequest, ListGroupStatsResponse, ListGroupStatsPagedResponse>
listGroupStatsSettings;
@@ -125,14 +125,9 @@ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuild
return InstantiatingExecutorProvider.newBuilder();
}
- /** 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 endpoint. */
+ public static String getDefaultEndpoint() {
+ return "clouderrorreporting.googleapis.com:443";
}
/** Returns the default service scopes. */
@@ -148,15 +143,19 @@ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilde
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingChannelProvider.Builder defaultChannelProviderBuilder() {
return InstantiatingChannelProvider.newBuilder()
- .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
- .setPort(DEFAULT_SERVICE_PORT)
+ .setEndpoint(getDefaultEndpoint())
.setGeneratorHeader(DEFAULT_GAPIC_NAME, getGapicVersion())
.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
}
private static String getGapicVersion() {
- String packageVersion = ErrorStatsServiceSettings.class.getPackage().getImplementationVersion();
- return packageVersion != null ? packageVersion : DEFAULT_GAPIC_VERSION;
+ if (gapicVersion == null) {
+ gapicVersion =
+ PropertiesProvider.loadProperty(
+ ErrorStatsServiceSettings.class, PROPERTIES_FILE, META_VERSION_KEY);
+ gapicVersion = gapicVersion == null ? DEFAULT_GAPIC_VERSION : gapicVersion;
+ }
+ return gapicVersion;
}
/** Returns a builder for this class with recommended defaults. */
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 4bd9fd99c30b..372ce78d03ff 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,6 +16,7 @@
package com.google.cloud.errorreporting.spi.v1beta1;
import com.google.api.gax.core.GoogleCredentialsProvider;
+import com.google.api.gax.core.PropertiesProvider;
import com.google.api.gax.core.RetrySettings;
import com.google.api.gax.grpc.ChannelProvider;
import com.google.api.gax.grpc.ClientSettings;
@@ -68,12 +69,6 @@
@Generated("by GAPIC v0.0.5")
@ExperimentalApi
public class ReportErrorsServiceSettings extends ClientSettings {
- /** The default address of the service. */
- private static final String DEFAULT_SERVICE_ADDRESS = "clouderrorreporting.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().add("https://www.googleapis.com/auth/cloud-platform").build();
@@ -81,6 +76,11 @@ public class ReportErrorsServiceSettings extends ClientSettings {
private static final String DEFAULT_GAPIC_NAME = "gapic";
private static final String DEFAULT_GAPIC_VERSION = "";
+ private static final String PROPERTIES_FILE = "/project.properties";
+ private static final String META_VERSION_KEY = "artifact.version";
+
+ private static String gapicVersion;
+
private final SimpleCallSettings
reportErrorEventSettings;
@@ -95,14 +95,9 @@ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuild
return InstantiatingExecutorProvider.newBuilder();
}
- /** 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 endpoint. */
+ public static String getDefaultEndpoint() {
+ return "clouderrorreporting.googleapis.com:443";
}
/** Returns the default service scopes. */
@@ -118,16 +113,19 @@ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilde
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingChannelProvider.Builder defaultChannelProviderBuilder() {
return InstantiatingChannelProvider.newBuilder()
- .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
- .setPort(DEFAULT_SERVICE_PORT)
+ .setEndpoint(getDefaultEndpoint())
.setGeneratorHeader(DEFAULT_GAPIC_NAME, getGapicVersion())
.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
}
private static String getGapicVersion() {
- String packageVersion =
- ReportErrorsServiceSettings.class.getPackage().getImplementationVersion();
- return packageVersion != null ? packageVersion : DEFAULT_GAPIC_VERSION;
+ if (gapicVersion == null) {
+ gapicVersion =
+ PropertiesProvider.loadProperty(
+ ReportErrorsServiceSettings.class, PROPERTIES_FILE, META_VERSION_KEY);
+ gapicVersion = gapicVersion == null ? DEFAULT_GAPIC_VERSION : gapicVersion;
+ }
+ return gapicVersion;
}
/** Returns a builder for this class with recommended defaults. */
diff --git a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceClientTest.java b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceClientTest.java
index f36aefdcb516..dc0f7a6d6d5f 100644
--- a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceClientTest.java
+++ b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceClientTest.java
@@ -100,7 +100,7 @@ public void getGroupTest() {
@Test
@SuppressWarnings("all")
public void getGroupExceptionTest() throws Exception {
- StatusRuntimeException exception = new StatusRuntimeException(Status.INTERNAL);
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockErrorGroupService.addException(exception);
try {
@@ -109,7 +109,7 @@ public void getGroupExceptionTest() throws Exception {
client.getGroup(groupName);
Assert.fail("No exception raised");
} catch (ApiException e) {
- Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
}
}
@@ -137,7 +137,7 @@ public void updateGroupTest() {
@Test
@SuppressWarnings("all")
public void updateGroupExceptionTest() throws Exception {
- StatusRuntimeException exception = new StatusRuntimeException(Status.INTERNAL);
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockErrorGroupService.addException(exception);
try {
@@ -146,7 +146,7 @@ public void updateGroupExceptionTest() throws Exception {
client.updateGroup(group);
Assert.fail("No exception raised");
} catch (ApiException e) {
- Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
}
}
}
diff --git a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceClientTest.java b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceClientTest.java
index 5d99dedf092f..76b3f535a433 100644
--- a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceClientTest.java
+++ b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceClientTest.java
@@ -119,7 +119,7 @@ public void listGroupStatsTest() {
@Test
@SuppressWarnings("all")
public void listGroupStatsExceptionTest() throws Exception {
- StatusRuntimeException exception = new StatusRuntimeException(Status.INTERNAL);
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockErrorStatsService.addException(exception);
try {
@@ -129,7 +129,7 @@ public void listGroupStatsExceptionTest() throws Exception {
client.listGroupStats(projectName, timeRange);
Assert.fail("No exception raised");
} catch (ApiException e) {
- Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
}
}
@@ -166,7 +166,7 @@ public void listEventsTest() {
@Test
@SuppressWarnings("all")
public void listEventsExceptionTest() throws Exception {
- StatusRuntimeException exception = new StatusRuntimeException(Status.INTERNAL);
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockErrorStatsService.addException(exception);
try {
@@ -176,7 +176,7 @@ public void listEventsExceptionTest() throws Exception {
client.listEvents(projectName, groupId);
Assert.fail("No exception raised");
} catch (ApiException e) {
- Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
}
}
@@ -201,7 +201,7 @@ public void deleteEventsTest() {
@Test
@SuppressWarnings("all")
public void deleteEventsExceptionTest() throws Exception {
- StatusRuntimeException exception = new StatusRuntimeException(Status.INTERNAL);
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockErrorStatsService.addException(exception);
try {
@@ -210,7 +210,7 @@ public void deleteEventsExceptionTest() throws Exception {
client.deleteEvents(projectName);
Assert.fail("No exception raised");
} catch (ApiException e) {
- Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
}
}
}
diff --git a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceClientTest.java b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceClientTest.java
index edf2da22c398..93a5d3524b58 100644
--- a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceClientTest.java
+++ b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceClientTest.java
@@ -99,7 +99,7 @@ public void reportErrorEventTest() {
@Test
@SuppressWarnings("all")
public void reportErrorEventExceptionTest() throws Exception {
- StatusRuntimeException exception = new StatusRuntimeException(Status.INTERNAL);
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockReportErrorsService.addException(exception);
try {
@@ -109,7 +109,7 @@ public void reportErrorEventExceptionTest() throws Exception {
client.reportErrorEvent(projectName, event);
Assert.fail("No exception raised");
} catch (ApiException e) {
- Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
}
}
}
diff --git a/google-cloud-examples/README.md b/google-cloud-examples/README.md
index 1dbbc9ce1417..67a1fe10fdb8 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.10.0-alpha
+ 0.12.0-alpha
```
If you are using Gradle, add this to your dependencies
```Groovy
-compile 'com.google.cloud:google-cloud-examples:0.10.0-alpha'
+compile 'com.google.cloud:google-cloud-examples:0.12.0-alpha'
```
If you are using SBT, add this to your dependencies
```Scala
-libraryDependencies += "com.google.cloud" % "google-cloud-examples" % "0.10.0-alpha"
+libraryDependencies += "com.google.cloud" % "google-cloud-examples" % "0.12.0-alpha"
```
To run examples from your command line:
@@ -128,7 +128,6 @@ To run examples from your command line:
target/appassembler/bin/PubSubExample create topic test-topic
target/appassembler/bin/PubSubExample create subscription test-topic test-subscription
target/appassembler/bin/PubSubExample publish test-topic message1 message2
- target/appassembler/bin/PubSubExample pull sync test-subscription 2
```
* Here's an example run of `ResourceManagerExample`.
@@ -170,7 +169,7 @@ To run examples from your command line:
* Here's an example run of `TranslateExample`.
- Before running the example, go to the [Google Developers Console][developers-console] to ensure that "Google Translate API" is enabled and that you have a valid API key.
+ Before running the example, go to the [Google Developers Console][developers-console] to ensure that "Google Translation API" is enabled and that you have a valid API key.
```
target/appassembler/bin/TranslateExample languages
target/appassembler/bin/TranslateExample detect Hello,\ World!
diff --git a/google-cloud-examples/pom.xml b/google-cloud-examples/pom.xml
index cf6d14d4e6fc..e4249ecaff4c 100644
--- a/google-cloud-examples/pom.xml
+++ b/google-cloud-examples/pom.xml
@@ -11,7 +11,7 @@
com.google.cloud
google-cloud-pom
- 0.10.1-alpha-SNAPSHOT
+ 0.12.1-alpha-SNAPSHOT
google-cloud-examples
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
new file mode 100644
index 000000000000..826ee4fd3f4b
--- /dev/null
+++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/PubSubExample.java
@@ -0,0 +1,840 @@
+/*
+ * 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.examples.pubsub;
+
+import com.google.api.gax.core.ApiFuture;
+import com.google.api.gax.core.ApiFutureCallback;
+import com.google.api.gax.core.ApiFutures;
+import com.google.cloud.Identity;
+import com.google.cloud.Role;
+import com.google.cloud.ServiceOptions;
+import com.google.cloud.pubsub.spi.v1.*;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.google.iam.v1.Binding;
+import com.google.iam.v1.Policy;
+import com.google.iam.v1.TestIamPermissionsResponse;
+import com.google.protobuf.ByteString;
+import com.google.pubsub.v1.*;
+
+import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * An example of using Google Pub/Sub.
+ *
+ * This example demonstrates a simple/typical Pub/Sub usage.
+ *
+ *
See the
+ *
+ * README for compilation instructions. Run this code with
+ *
{@code target/appassembler/bin/PubSubExample
+ * -Dexec.args="[]
+ * pull async ?
+ * pull sync
+ * publish +
+ * replace-push-config ?
+ * create topic
+ * create subscription ?
+ * list subscriptions ?
+ * list topics
+ * delete topic
+ * delete subscription
+ * info topic
+ * info subscription
+ * get-policy topic
+ * get-policy subscription
+ * add-identity topic
+ * add-identity subscription
+ * test-permissions topic +
+ * test-permissions subscription +"}
+ *
+ * The first parameter is an optional {@code project_id} (logged-in project will be used if not
+ * supplied). Second parameter is a Pub/Sub operation and can be used to demonstrate its usage. For
+ * operations that apply to more than one entity (`list`, `create`, `info` and `delete`) the third
+ * parameter specifies the entity. `pull` operation also takes a third parameter to specify whether
+ * pulling should be synchronous or asynchronous.
+ */
+public class PubSubExample {
+
+ private static final Map CREATE_ACTIONS = new HashMap<>();
+ private static final Map INFO_ACTIONS = new HashMap<>();
+ private static final Map LIST_ACTIONS = new HashMap<>();
+ private static final Map DELETE_ACTIONS = new HashMap<>();
+ private static final Map PULL_ACTIONS = new HashMap<>();
+ private static final Map GET_IAM_ACTIONS = new HashMap<>();
+ private static final Map REPLACE_IAM_ACTIONS = new HashMap<>();
+ private static final Map TEST_IAM_ACTIONS = new HashMap<>();
+ private static final Map ACTIONS = new HashMap<>();
+
+ private static String projectId;
+
+ private abstract static class PubSubAction {
+
+ abstract void run(T arg) throws Exception;
+
+ abstract T parse(String... args) throws Exception;
+
+ protected String params() {
+ return "";
+ }
+ }
+
+ private static class Tuple {
+
+ private final X x;
+ private final Y y;
+
+ private Tuple(X x, Y y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ public static Tuple of(X x, Y y) {
+ return new Tuple<>(x, y);
+ }
+
+ X x() {
+ return x;
+ }
+
+ Y y() {
+ return y;
+ }
+ }
+
+ private static class ParentAction extends PubSubAction> {
+
+ private final Map subActions;
+
+ ParentAction(Map subActions) {
+ this.subActions = ImmutableMap.copyOf(subActions);
+ }
+
+ @Override
+ @SuppressWarnings("unchecked")
+ void run(Tuple subaction) throws Exception {
+ subaction.x().run(subaction.y());
+ }
+
+ @Override
+ Tuple parse(String... args) throws Exception {
+ if (args.length >= 1) {
+ PubSubAction action = subActions.get(args[0]);
+ if (action != null) {
+ Object actionArguments = action.parse(Arrays.copyOfRange(args, 1, args.length));
+ return Tuple.of(action, actionArguments);
+ } else {
+ throw new IllegalArgumentException("Unrecognized entity '" + args[0] + "'.");
+ }
+ }
+ throw new IllegalArgumentException("Missing required entity.");
+ }
+
+ @Override
+ public String params() {
+ StringBuilder builder = new StringBuilder();
+ for (Map.Entry entry : subActions.entrySet()) {
+ builder.append('\n').append(entry.getKey());
+ String param = entry.getValue().params();
+ if (param != null && !param.isEmpty()) {
+ builder.append(' ').append(param);
+ }
+ }
+ return builder.toString();
+ }
+ }
+
+ private abstract static class NoArgsAction extends PubSubAction {
+ @Override
+ Void parse(String... args) throws Exception {
+ if (args.length == 0) {
+ return null;
+ }
+ throw new IllegalArgumentException("This action takes no arguments.");
+ }
+ }
+
+ /**
+ * This class demonstrates how to list Pub/Sub topics.
+ *
+ * @see List
+ * topics in your project
+ */
+ private static class ListTopicsAction extends NoArgsAction {
+ @Override
+ public void run(Void arg) throws Exception {
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+ ListTopicsRequest listTopicsRequest =
+ ListTopicsRequest.newBuilder()
+ .setProjectWithProjectName(ProjectName.create(projectId))
+ .build();
+ PagedResponseWrappers.ListTopicsPagedResponse response = topicAdminClient.listTopics(listTopicsRequest);
+ Iterable topics = response.iterateAllElements();
+ for (Topic topic : topics) {
+ System.out.println(topic.getName());
+ }
+ }
+ }
+ }
+
+ private abstract static class TopicAction extends PubSubAction {
+ @Override
+ String parse(String... args) throws Exception {
+ String message;
+ if (args.length == 1) {
+ return args[0];
+ } else if (args.length > 1) {
+ message = "Too many arguments.";
+ } else {
+ message = "Missing required topic name.";
+ }
+ throw new IllegalArgumentException(message);
+ }
+
+ @Override
+ public String params() {
+ return "";
+ }
+ }
+
+ /**
+ * This class demonstrates how to retrieve information on a Pub/Sub topic.
+ */
+ private static class TopicRetrievalAction extends TopicAction {
+ @Override
+ public void run(String topicId) throws Exception {
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+ Topic topic = topicAdminClient.getTopic(TopicName.create(projectId, topicId));
+ System.out.printf("Topic : %s%n", topic);
+ }
+ }
+ }
+
+ /**
+ * This class demonstrates how to create a Pub/Sub topic.
+ *
+ * @see Create a topic
+ */
+ private static class CreateTopicAction extends TopicAction {
+ @Override
+ public void run(String topicId) throws Exception {
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+ TopicName topicName = TopicName.create(projectId, topicId);
+ Topic topic = topicAdminClient.createTopic(topicName);
+ System.out.printf("Created topic %s%n", topic.getName());
+ }
+ }
+ }
+
+ /**
+ * This class demonstrates how to delete a Pub/Sub topic.
+ *
+ * @see Delete a topic
+ */
+ private static class DeleteTopicAction extends TopicAction {
+ @Override
+ public void run(String topicId) throws Exception {
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+ topicAdminClient.deleteTopic(TopicName.create(projectId, topicId));
+ System.out.printf("Deleted topic %s%n", topicId);
+ }
+ }
+ }
+
+ /**
+ * This class demonstrates how to list Pub/Sub subscriptions.
+ *
+ * @see List subscriptions
+ */
+ private static class ListSubscriptionsAction extends PubSubAction {
+ @Override
+ public void run(String topic) throws Exception {
+ if (topic == null) {
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ PagedResponseWrappers.ListSubscriptionsPagedResponse response =
+ subscriptionAdminClient.listSubscriptions(ProjectName.create(projectId));
+ Iterable subscriptions = response.iterateAllElements();
+ for (Subscription subscription : subscriptions) {
+ System.out.println(subscription.getName());
+ }
+ }
+ } else {
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+ PagedResponseWrappers.ListTopicSubscriptionsPagedResponse response =
+ topicAdminClient.listTopicSubscriptions(TopicName.create(projectId, topic));
+ Iterable subscriptionNames = response.iterateAllElements();
+ for (String subscriptionName : subscriptionNames) {
+ System.out.println(subscriptionName);
+ }
+ }
+ }
+ }
+
+ @Override
+ String parse(String... args) throws Exception {
+ if (args.length == 1) {
+ return args[0];
+ } else if (args.length == 0) {
+ return null;
+ } else {
+ throw new IllegalArgumentException("Too many arguments.");
+ }
+ }
+
+ @Override
+ public String params() {
+ return "?";
+ }
+ }
+
+ /**
+ * This class demonstrates how to publish messages to a Pub/Sub topic.
+ *
+ * @see Publish
+ * messages to a topic
+ */
+ private static class PublishMessagesAction extends PubSubAction>> {
+ @Override
+ public void run(Tuple> params) throws Exception {
+ String topic = params.x();
+ TopicName topicName = TopicName.create(projectId, topic);
+ Publisher publisher = Publisher.defaultBuilder(topicName).build();
+ List messages = params.y();
+ for (PubsubMessage message : messages) {
+ ApiFuture messageIdFuture = publisher.publish(message);
+ ApiFutures.addCallback(messageIdFuture, new ApiFutureCallback() {
+ public void onSuccess(String messageId) {
+ System.out.println("published with message id: " + messageId);
+ }
+
+ public void onFailure(Throwable t) {
+ System.out.println("failed to publish: " + t);
+ }
+ });
+ }
+ System.out.printf("Published %d messages to topic %s%n", messages.size(), topic);
+ }
+
+ @Override
+ Tuple> parse(String... args) throws Exception {
+ if (args.length < 2) {
+ throw new IllegalArgumentException("Missing required topic and messages");
+ }
+ String topic = args[0];
+ List messages = new ArrayList<>();
+ for (String payload : Arrays.copyOfRange(args, 1, args.length)) {
+ ByteString data = ByteString.copyFromUtf8(payload);
+ PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
+ messages.add(pubsubMessage);
+ }
+ return Tuple.of(topic, messages);
+ }
+
+ @Override
+ public String params() {
+ return " +";
+ }
+ }
+
+ private abstract static class SubscriptionAction extends PubSubAction {
+ @Override
+ String parse(String... args) throws Exception {
+ String message;
+ if (args.length == 1) {
+ return args[0];
+ } else if (args.length > 1) {
+ message = "Too many arguments.";
+ } else {
+ message = "Missing required subscription name.";
+ }
+ throw new IllegalArgumentException(message);
+ }
+
+ @Override
+ public String params() {
+ return "";
+ }
+ }
+
+ /**
+ * This class demonstrates how to retrieve a Pub/Sub subscription.
+ */
+ private static class SubscriptionInfoAction extends SubscriptionAction {
+ @Override
+ public void run(String subscriptionId) throws Exception {
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ Subscription subscription = subscriptionAdminClient.getSubscription(
+ SubscriptionName.create(projectId, subscriptionId));
+ System.out.printf("Subscription info: %s%n", subscription.getName());
+ }
+ }
+ }
+
+ /**
+ * This class demonstrates how to create a Pub/Sub subscription.
+ *
+ * @see Create a subscription
+ */
+ private static class CreateSubscriptionAction extends
+ PubSubAction, PushConfig>> {
+ @Override
+ public void run(Tuple, PushConfig> subscriptionParams) throws Exception {
+ Tuple nameTuple = subscriptionParams.x();
+ TopicName topicName = nameTuple.x();
+ SubscriptionName subscriptionName = nameTuple.y();
+ PushConfig pushConfig = subscriptionParams.y();
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ Subscription subscription = subscriptionAdminClient.createSubscription(
+ subscriptionName, topicName, pushConfig, 60);
+ System.out.printf("Created subscription %s%n", subscription.getName());
+ }
+ }
+
+ @Override
+ Tuple, PushConfig> parse(String... args) throws Exception {
+ String message;
+ if (args.length > 3) {
+ message = "Too many arguments.";
+ } else if (args.length < 2) {
+ message = "Missing required topic or subscription name";
+ } else {
+ TopicName topicName = TopicName.create(projectId, args[0]);
+ SubscriptionName subscriptionName = SubscriptionName.create(projectId, args[1]);
+ PushConfig pushConfig = PushConfig.getDefaultInstance();
+ if (args.length == 3) {
+ pushConfig = PushConfig.newBuilder().setPushEndpoint(args[2]).build();
+ }
+ return new Tuple<>(new Tuple<>(topicName, subscriptionName), pushConfig);
+ }
+ throw new IllegalArgumentException(message);
+ }
+
+ @Override
+ public String params() {
+ return " ?";
+ }
+ }
+
+ /**
+ * This class demonstrates how to delete a Pub/Sub subscription.
+ */
+ private static class DeleteSubscriptionAction extends SubscriptionAction {
+ @Override
+ public void run(String subscriptionId) throws Exception {
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ subscriptionAdminClient.deleteSubscription(SubscriptionName.create(projectId, subscriptionId));
+ System.out.printf("Deleted subscription %s%n", subscriptionId);
+ }
+ }
+ }
+
+ /**
+ * This class demonstrates how to modify the push configuration for a Pub/Sub subscription.
+ *
+ * @see
+ * Switching between push and pull delivery
+ */
+ private static class ReplacePushConfigAction extends
+ PubSubAction> {
+ @Override
+ public void run(Tuple params) throws Exception {
+ SubscriptionName subscriptionName = params.x();
+ PushConfig pushConfig = params.y();
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ subscriptionAdminClient.modifyPushConfig(subscriptionName, pushConfig);
+ }
+ System.out.printf("Set push config %s for subscription %s%n", pushConfig, subscriptionName);
+ }
+
+ @Override
+ Tuple parse(String... args) throws Exception {
+ String message;
+ if (args.length > 2) {
+ message = "Too many arguments.";
+ } else if (args.length < 1) {
+ message = "Missing required subscription name";
+ } else {
+ SubscriptionName subscriptionName = SubscriptionName.create(projectId, args[0]);
+ PushConfig pushConfig = null;
+ if (args.length == 2) {
+ pushConfig = PushConfig.newBuilder().setPushEndpoint(args[1]).build();
+ }
+ return Tuple.of(subscriptionName, pushConfig);
+ }
+ throw new IllegalArgumentException(message);
+ }
+
+ @Override
+ public String params() {
+ return " ?";
+ }
+ }
+
+ /**
+ * This class demonstrates how to asynchronously pull messages from a Pub/Sub pull subscription.
+ * Messages are pulled until a timeout is reached.
+ *
+ * @see Receiving
+ * pull messages
+ */
+ private static class PullAsyncAction extends PubSubAction> {
+ @Override
+ public void run(Tuple params) throws Exception {
+ final AtomicInteger messageCount = new AtomicInteger();
+ MessageReceiver receiver =
+ new MessageReceiver() {
+ @Override
+ public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
+ messageCount.incrementAndGet();
+ consumer.accept(AckReply.ACK);
+ }
+ };
+ SubscriptionName subscriptionName = params.x();
+ Subscriber subscriber = null;
+ try {
+ subscriber = Subscriber.defaultBuilder(subscriptionName, receiver).build();
+ subscriber.addListener(
+ new Subscriber.Listener() {
+ @Override
+ public void failed(Subscriber.State from, Throwable failure) {
+ // Handle failure.
+ // This is called when the Subscriber encountered a fatal error and is shutting down.
+ System.err.println(failure);
+ }
+ },
+ MoreExecutors.directExecutor());
+ subscriber.startAsync().awaitRunning();
+ Thread.sleep(params.y());
+ } finally {
+ if (subscriber != null) {
+ subscriber.stopAsync();
+ }
+ }
+ System.out.printf("Pulled %d messages from subscription %s%n", messageCount.get(), subscriptionName);
+ }
+
+ @Override
+ Tuple parse(String... args) throws Exception {
+ String message;
+ if (args.length > 2) {
+ message = "Too many arguments.";
+ } else if (args.length < 1) {
+ message = "Missing required subscription name";
+ } else {
+ String subscriptionId = args[0];
+ long timeout = 60_000;
+ if (args.length == 2) {
+ timeout = Long.parseLong(args[1]);
+ }
+ return Tuple.of(SubscriptionName.create(projectId, subscriptionId), timeout);
+ }
+ throw new IllegalArgumentException(message);
+ }
+
+ @Override
+ public String params() {
+ return " ?";
+ }
+ }
+
+ private abstract static class GetPolicyAction extends PubSubAction {
+ @Override
+ String parse(String... args) throws Exception {
+ String message;
+ if (args.length == 1) {
+ return args[0];
+ } else if (args.length > 1) {
+ message = "Too many arguments.";
+ } else {
+ message = "Missing required resource name";
+ }
+ throw new IllegalArgumentException(message);
+ }
+
+ @Override
+ public String params() {
+ return "";
+ }
+ }
+
+ /**
+ * This class demonstrates how to get the IAM policy of a topic.
+ *
+ * @see Access Control
+ */
+ private static class GetTopicPolicyAction extends GetPolicyAction {
+ @Override
+ public void run(String topicId) throws Exception {
+ TopicName topicName = TopicName.create(projectId, topicId);
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+ Policy policy = topicAdminClient.getIamPolicy(topicName.toString());
+ System.out.printf("Policy for topic %s%n", topicId);
+ System.out.println(policy);
+ }
+ }
+ }
+
+ /**
+ * This class demonstrates how to get the IAM policy of a subscription.
+ *
+ * @see Access Control
+ */
+ private static class GetSubscriptionPolicyAction extends GetPolicyAction {
+ @Override
+ public void run(String subscription) throws Exception {
+ SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscription);
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ Policy policy = subscriptionAdminClient.getIamPolicy(subscriptionName.toString());
+ System.out.printf("Policy for subscription %s%n", subscription);
+ System.out.println(policy);
+ }
+ }
+ }
+
+ private abstract static class AddIdentityAction extends PubSubAction>> {
+ @Override
+ Tuple> parse(String... args) throws Exception {
+ String message;
+ if (args.length == 3) {
+ String resourceName = args[0];
+ Role role = Role.of(args[1]);
+ Identity identity = Identity.valueOf(args[2]);
+ return Tuple.of(resourceName, Tuple.of(role, identity));
+ } else if (args.length > 2) {
+ message = "Too many arguments.";
+ } else {
+ message = "Missing required resource name, role and identity";
+ }
+ throw new IllegalArgumentException(message);
+ }
+
+ @Override
+ public String params() {
+ return " ";
+ }
+ }
+
+
+ /**
+ * This class demonstrates how to add an identity to a certain role in a topic's IAM policy.
+ *
+ * @see Access Control
+ */
+ private static class AddIdentityTopicAction extends AddIdentityAction {
+ @Override
+ public void run(Tuple> param) throws Exception {
+ TopicName topicName = TopicName.create(projectId, param.x());
+ Tuple roleAndIdentity = param.y();
+ Role role = roleAndIdentity.x();
+ Identity identity = roleAndIdentity.y();
+ Binding binding =
+ Binding.newBuilder()
+ .setRole(role.toString())
+ .addMembers(identity.toString())
+ .build();
+ //Update policy
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+ Policy policy = topicAdminClient.getIamPolicy(topicName.toString());
+ //Update policy
+ Policy updatedPolicy = policy.toBuilder().addBindings(binding).build();
+ updatedPolicy = topicAdminClient.setIamPolicy(topicName.toString(), updatedPolicy);
+ System.out.printf("Added role %s to identity %s for topic %s%n", role, identity, topicName);
+ System.out.println(updatedPolicy);
+ }
+ }
+ }
+
+ /**
+ * This class demonstrates how to add an identity to a certain role in a subscription's IAM
+ * policy.
+ *
+ * @see Access Control
+ */
+ private static class AddIdentitySubscriptionAction extends AddIdentityAction {
+ @Override
+ public void run(Tuple> param) throws Exception {
+ SubscriptionName subscriptionName = SubscriptionName.create(projectId, param.x());
+ // Create a role => identity binding
+ Role role = param.y().x();
+ Identity identity = param.y().y();
+ Binding binding =
+ Binding.newBuilder()
+ .setRole(role.toString())
+ .addMembers(identity.toString())
+ .build();
+
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ Policy policy = subscriptionAdminClient.getIamPolicy(subscriptionName.toString());
+ //Update policy
+ Policy updatedPolicy = policy.toBuilder().addBindings(binding).build();
+
+ updatedPolicy = subscriptionAdminClient.setIamPolicy(subscriptionName.toString(), updatedPolicy);
+ System.out.printf("Added role %s to identity %s for subscription %s%n", role, identity,
+ subscriptionName);
+ System.out.println(updatedPolicy);
+ }
+ }
+ }
+
+ private abstract static class TestPermissionsAction extends PubSubAction>> {
+ @Override
+ Tuple> parse(String... args) throws Exception {
+ if (args.length >= 2) {
+ String resourceName = args[0];
+ return Tuple.of(resourceName, Arrays.asList(Arrays.copyOfRange(args, 1, args.length)));
+ }
+ throw new IllegalArgumentException("Missing required resource name and permissions");
+ }
+
+ @Override
+ public String params() {
+ return " +";
+ }
+ }
+
+ /**
+ * This class demonstrates how to test whether the caller has the provided permissions on a topic.
+ *
+ * @see Access Control
+ */
+ private static class TestTopicPermissionsAction extends TestPermissionsAction {
+ @Override
+ public void run(Tuple> param) throws Exception {
+ TopicName topicName = TopicName.create(projectId, param.x());
+ List permissions = param.y();
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+ TestIamPermissionsResponse response =
+ topicAdminClient.testIamPermissions(topicName.toString(), permissions);
+ System.out.println("Topic permissions test : ");
+ Set actualPermissions = new HashSet<>();
+ actualPermissions.addAll(response.getPermissionsList());
+ for (String permission : permissions) {
+ System.out.println(permission + " : " + actualPermissions.contains(permission));
+ }
+ }
+ }
+ }
+
+ /**
+ * This class demonstrates how to test whether the caller has the provided permissions on a
+ * subscription.
+ *
+ * @see Access Control
+ */
+ private static class TestSubscriptionPermissionsAction extends TestPermissionsAction {
+ @Override
+ public void run(Tuple> param) throws Exception {
+ SubscriptionName subscriptionName = SubscriptionName.create(projectId, param.x());
+ List permissions = param.y();
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ TestIamPermissionsResponse response =
+ subscriptionAdminClient.testIamPermissions(subscriptionName.toString(),
+ permissions);
+ System.out.println("Subscription permissions test : ");
+ Set actualPermissions = new HashSet<>();
+ actualPermissions.addAll(response.getPermissionsList());
+ for (String permission : permissions) {
+ System.out.println(permission + " : " + actualPermissions.contains(permission));
+ }
+ }
+ }
+ }
+
+ static {
+ CREATE_ACTIONS.put("topic", new CreateTopicAction());
+ CREATE_ACTIONS.put("subscription", new CreateSubscriptionAction());
+ INFO_ACTIONS.put("topic", new TopicRetrievalAction());
+ INFO_ACTIONS.put("subscription", new SubscriptionInfoAction());
+ LIST_ACTIONS.put("topics", new ListTopicsAction());
+ LIST_ACTIONS.put("subscriptions", new ListSubscriptionsAction());
+ DELETE_ACTIONS.put("topic", new DeleteTopicAction());
+ DELETE_ACTIONS.put("subscription", new DeleteSubscriptionAction());
+ PULL_ACTIONS.put("async", new PullAsyncAction());
+ GET_IAM_ACTIONS.put("topic", new GetTopicPolicyAction());
+ GET_IAM_ACTIONS.put("subscription", new GetSubscriptionPolicyAction());
+ REPLACE_IAM_ACTIONS.put("topic", new AddIdentityTopicAction());
+ REPLACE_IAM_ACTIONS.put("subscription", new AddIdentitySubscriptionAction());
+ TEST_IAM_ACTIONS.put("topic", new TestTopicPermissionsAction());
+ TEST_IAM_ACTIONS.put("subscription", new TestSubscriptionPermissionsAction());
+ ACTIONS.put("create", new ParentAction(CREATE_ACTIONS));
+ ACTIONS.put("info", new ParentAction(INFO_ACTIONS));
+ ACTIONS.put("list", new ParentAction(LIST_ACTIONS));
+ ACTIONS.put("delete", new ParentAction(DELETE_ACTIONS));
+ ACTIONS.put("pull", new ParentAction(PULL_ACTIONS));
+ ACTIONS.put("get-policy", new ParentAction(GET_IAM_ACTIONS));
+ ACTIONS.put("add-identity", new ParentAction(REPLACE_IAM_ACTIONS));
+ ACTIONS.put("test-permissions", new ParentAction(TEST_IAM_ACTIONS));
+ ACTIONS.put("publish", new PublishMessagesAction());
+ ACTIONS.put("replace-push-config", new ReplacePushConfigAction());
+ }
+
+ private static void printUsage() {
+ StringBuilder actionAndParams = new StringBuilder();
+ for (Map.Entry entry : ACTIONS.entrySet()) {
+ actionAndParams.append("\n\t").append(entry.getKey());
+
+ String param = entry.getValue().params();
+ if (param != null && !param.isEmpty()) {
+ actionAndParams.append(' ').append(param.replace("\n", "\n\t\t"));
+ }
+ }
+ System.out.printf("Usage: %s [] operation [entity] *%s%n",
+ PubSubExample.class.getSimpleName(), actionAndParams);
+ }
+
+ @SuppressWarnings("unchecked")
+ public static void main(String... args) throws Exception {
+ if (args.length < 1) {
+ System.out.println("Missing required project id and action");
+ printUsage();
+ return;
+ }
+ PubSubAction action;
+ String actionName;
+ if (args.length >= 2 && !ACTIONS.containsKey(args[0])) {
+ actionName = args[1];
+ projectId = args[0];
+ action = ACTIONS.get(args[1]);
+ args = Arrays.copyOfRange(args, 2, args.length);
+ } else {
+ actionName = args[0];
+ projectId = ServiceOptions.getDefaultProjectId();
+ action = ACTIONS.get(args[0]);
+ args = Arrays.copyOfRange(args, 1, args.length);
+ }
+ if (action == null) {
+ System.out.println("Unrecognized action.");
+ printUsage();
+ return;
+ }
+ Object arg;
+ try {
+ arg = action.parse(args);
+ } catch (IllegalArgumentException ex) {
+ System.out.printf("Invalid input for action '%s'. %s%n", actionName, ex.getMessage());
+ System.out.printf("Expected: %s%n", action.params());
+ return;
+ } catch (Exception ex) {
+ System.out.println("Failed to parse arguments.");
+ ex.printStackTrace();
+ return;
+ }
+ action.run(arg);
+ }
+}
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 531de1cc7fbf..2fece107b678 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
@@ -20,7 +20,7 @@
import com.google.cloud.pubsub.spi.v1.AckReplyConsumer;
import com.google.cloud.pubsub.spi.v1.MessageReceiver;
import com.google.cloud.pubsub.spi.v1.Subscriber;
-import com.google.cloud.pubsub.spi.v1.SubscriberClient;
+import com.google.cloud.pubsub.spi.v1.SubscriptionAdminClient;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.PushConfig;
@@ -34,11 +34,12 @@
public class CreateSubscriptionAndPullMessages {
public static void main(String... args) throws Exception {
+ // [START async_pull_subscription]
TopicName topic = TopicName.create("test-project", "test-topic");
SubscriptionName subscription = SubscriptionName.create("test-project", "test-subscription");
- try (SubscriberClient subscriberClient = SubscriberClient.create()) {
- subscriberClient.createSubscription(subscription, topic, PushConfig.getDefaultInstance(), 0);
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ subscriptionAdminClient.createSubscription(subscription, topic, PushConfig.getDefaultInstance(), 0);
}
MessageReceiver receiver =
@@ -51,9 +52,9 @@ public void receiveMessage(PubsubMessage message, AckReplyConsumer consumer) {
};
Subscriber subscriber = null;
try {
- subscriber = Subscriber.newBuilder(subscription, receiver).build();
+ subscriber = Subscriber.defaultBuilder(subscription, receiver).build();
subscriber.addListener(
- new Subscriber.SubscriberListener() {
+ new Subscriber.Listener() {
@Override
public void failed(Subscriber.State from, Throwable failure) {
// Handle failure. This is called when the Subscriber encountered a fatal error and is shutting down.
@@ -62,11 +63,13 @@ public void failed(Subscriber.State from, Throwable failure) {
},
MoreExecutors.directExecutor());
subscriber.startAsync().awaitRunning();
+
Thread.sleep(60000);
} finally {
if (subscriber != null) {
subscriber.stopAsync();
}
}
+ // [END async_pull_subscription]
}
}
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 43c55005a7be..8021bf736c8b 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
@@ -18,7 +18,7 @@
import com.google.api.gax.core.ApiFuture;
import com.google.cloud.pubsub.spi.v1.Publisher;
-import com.google.cloud.pubsub.spi.v1.PublisherClient;
+import com.google.cloud.pubsub.spi.v1.TopicAdminClient;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.TopicName;
@@ -33,13 +33,13 @@
public class CreateTopicAndPublishMessages {
public static void main(String... args) throws Exception {
TopicName topic = TopicName.create("test-project", "test-topic");
- try (PublisherClient publisherClient = PublisherClient.create()) {
- publisherClient.createTopic(topic);
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+ topicAdminClient.createTopic(topic);
}
Publisher publisher = null;
try {
- publisher = Publisher.newBuilder(topic).build();
+ publisher = Publisher.defaultBuilder(topic).build();
List messages = Arrays.asList("first message", "second message");
List> messageIds = new ArrayList<>();
for (String message : messages) {
diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherSnippets.java
index 6f431d6277f1..39465d573149 100644
--- a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherSnippets.java
+++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherSnippets.java
@@ -65,7 +65,7 @@ public void onFailure(Throwable t) {
public static void newBuilder(String projectName, String topicName) throws Exception {
// [START newBuilder]
TopicName topic = TopicName.create(projectName, topicName);
- Publisher publisher = Publisher.newBuilder(topic).build();
+ Publisher publisher = Publisher.defaultBuilder(topic).build();
try {
// ...
} finally {
diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberSnippets.java
index d2340d2a0834..e5c0d840399d 100644
--- a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberSnippets.java
+++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberSnippets.java
@@ -53,8 +53,8 @@ public SubscriberSnippets(
// [TARGET startAsync()]
public void startAndWait() throws Exception {
// [START startAsync]
- Subscriber subscriber = Subscriber.newBuilder(subscription, receiver).build();
- subscriber.addListener(new Subscriber.SubscriberListener() {
+ Subscriber subscriber = Subscriber.defaultBuilder(subscription, receiver).build();
+ subscriber.addListener(new Subscriber.Listener() {
public void failed(Subscriber.State from, Throwable failure) {
// Handle error.
}
diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberClientSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriptionAdminClientSnippets.java
similarity index 56%
rename from google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberClientSnippets.java
rename to google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriptionAdminClientSnippets.java
index bee70a1a118b..40df803b451f 100644
--- a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberClientSnippets.java
+++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriptionAdminClientSnippets.java
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-/** This class contains snippets for the {@link SubscriberClient} interface. */
+/** This class contains snippets for the {@link SubscriptionAdminClient} interface. */
package com.google.cloud.examples.pubsub.snippets;
@@ -22,8 +22,8 @@
import com.google.cloud.Role;
import com.google.cloud.ServiceOptions;
import com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListSubscriptionsPagedResponse;
-import com.google.cloud.pubsub.spi.v1.PublisherClient;
-import com.google.cloud.pubsub.spi.v1.SubscriberClient;
+import com.google.cloud.pubsub.spi.v1.TopicAdminClient;
+import com.google.cloud.pubsub.spi.v1.SubscriptionAdminClient;
import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import com.google.iam.v1.TestIamPermissionsResponse;
@@ -39,12 +39,12 @@
import java.util.LinkedList;
import java.util.List;
-/** This class contains a number of snippets for the {@link SubscriberClient} interface. */
-public class SubscriberClientSnippets {
+/** This class contains a number of snippets for the {@link SubscriptionAdminClient} interface. */
+public class SubscriptionAdminClientSnippets {
private final String projectId;
- public SubscriberClientSnippets() {
+ public SubscriptionAdminClientSnippets() {
this.projectId = ServiceOptions.getDefaultProjectId();
}
@@ -53,97 +53,107 @@ public String getProjectId() {
}
/** Example of creating a pull subscription for a topic. */
- public Subscription createSubscription(String topic, String subscriptionId) throws Exception {
- try (SubscriberClient subscriberClient = SubscriberClient.create()) {
- // [START createSubscription]
- TopicName topicName = TopicName.create(projectId, topic);
+ public Subscription createSubscription(String topicId, String subscriptionId) throws Exception {
+ // [START createSubscription]
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ // eg. projectId = "my-test-project", topicId = "my-test-topic"
+ TopicName topicName = TopicName.create(projectId, topicId);
+ // eg. subscriptionId = "my-test-subscription"
SubscriptionName subscriptionName =
SubscriptionName.create(projectId, subscriptionId);
+ // create a pull subscription with default acknowledgement deadline
Subscription subscription =
- subscriberClient.createSubscription(
+ subscriptionAdminClient.createSubscription(
subscriptionName, topicName, PushConfig.getDefaultInstance(), 0);
- // [END createSubscription]
return subscription;
}
+ // [END createSubscription]
}
- /** Example of pulling a maximum number of messages from a subscription. */
- public PullResponse pull(String subscriptionId) throws Exception {
- try (SubscriberClient subscriberClient = SubscriberClient.create()) {
- // [START pull]
- SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
- PullResponse response = subscriberClient.pull(subscriptionName, true, 100);
- for (ReceivedMessage message : response.getReceivedMessagesList()) {
- // do something with message, then ack or nack
- subscriberClient.acknowledge(
- subscriptionName, Collections.singletonList(message.getAckId()));
- }
- // [END pull]
- return response;
+ /** Example of creating a subscription with a push endpoint. */
+ public Subscription createSubscriptionWithPushEndpoint(String topicId, String subscriptionId, String endpoint)
+ throws Exception {
+ // [START createSubscriptionWithPushEndpoint]
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ TopicName topicName = TopicName.create(projectId, topicId);
+ SubscriptionName subscriptionName =
+ SubscriptionName.create(projectId, subscriptionId);
+
+ // eg. endpoint = "https://my-test-project.appspot.com/push"
+ PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(endpoint).build();
+
+ // acknowledgement deadline in seconds for the message received over the push endpoint
+ int ackDeadlineInSeconds = 10;
+
+ Subscription subscription =
+ subscriptionAdminClient.createSubscription(
+ subscriptionName, topicName, pushConfig, ackDeadlineInSeconds);
+ return subscription;
}
+ // [END createSubscriptionWithPushEndpoint]
}
/** Example of replacing the push configuration of a subscription, setting the push endpoint. */
public void replacePushConfig(String subscriptionId, String endpoint) throws Exception {
- try (SubscriberClient subscriberClient = SubscriberClient.create()) {
- // [START replacePushConfig]
+ // [START replacePushConfig]
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(endpoint).build();
- subscriberClient.modifyPushConfig(subscriptionName, pushConfig);
- // [END replacePushConfig]
+ subscriptionAdminClient.modifyPushConfig(subscriptionName, pushConfig);
}
+ // [END replacePushConfig]
}
/** Example of listing subscriptions. */
public ListSubscriptionsPagedResponse listSubscriptions() throws Exception {
- try (SubscriberClient subscriberClient = SubscriberClient.create()) {
- // [START listSubscriptions]
+ // [START listSubscriptions]
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
ListSubscriptionsRequest listSubscriptionsRequest =
ListSubscriptionsRequest.newBuilder()
.setProjectWithProjectName(ProjectName.create(projectId))
.build();
ListSubscriptionsPagedResponse response =
- subscriberClient.listSubscriptions(listSubscriptionsRequest);
+ subscriptionAdminClient.listSubscriptions(listSubscriptionsRequest);
Iterable subscriptions = response.iterateAllElements();
for (Subscription subscription : subscriptions) {
// do something with the subscription
}
- // [END listSubscriptions]
return response;
}
+ // [END listSubscriptions]
}
/** Example of deleting a subscription. */
public SubscriptionName deleteSubscription(String subscriptionId) throws Exception {
- try (SubscriberClient subscriberClient = SubscriberClient.create()) {
- // [START deleteSubscription]
+ // [START deleteSubscription]
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
- subscriberClient.deleteSubscription(subscriptionName);
- // [END deleteSubscription]
+ subscriptionAdminClient.deleteSubscription(subscriptionName);
return subscriptionName;
}
+ // [END deleteSubscription]
}
/** Example of getting a subscription policy. */
public Policy getSubscriptionPolicy(String subscriptionId) throws Exception {
- try (SubscriberClient subscriberClient = SubscriberClient.create()) {
- // [START getSubscriptionPolicy]
+ // [START getSubscriptionPolicy]
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
- Policy policy = subscriberClient.getIamPolicy(subscriptionName.toString());
+ Policy policy = subscriptionAdminClient.getIamPolicy(subscriptionName.toString());
if (policy == null) {
// subscription was not found
}
- // [END getSubscriptionPolicy]
return policy;
}
+ // [END getSubscriptionPolicy]
}
/** Example of replacing a subscription policy. */
public Policy replaceSubscriptionPolicy(String subscriptionId) throws Exception {
- try (SubscriberClient subscriberClient = SubscriberClient.create()) {
- // [START replaceSubscriptionPolicy]
+ // [START replaceSubscriptionPolicy]
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
- Policy policy = subscriberClient.getIamPolicy(subscriptionName.toString());
+ Policy policy = subscriptionAdminClient.getIamPolicy(subscriptionName.toString());
// Create a role => members binding
Binding binding =
Binding.newBuilder()
@@ -153,35 +163,35 @@ public Policy replaceSubscriptionPolicy(String subscriptionId) throws Exception
//Update policy
Policy updatedPolicy = policy.toBuilder().addBindings(binding).build();
- updatedPolicy = subscriberClient.setIamPolicy(subscriptionName.toString(), updatedPolicy);
- // [END replaceSubscriptionPolicy]
+ updatedPolicy = subscriptionAdminClient.setIamPolicy(subscriptionName.toString(), updatedPolicy);
return updatedPolicy;
}
+ // [END replaceSubscriptionPolicy]
}
/** Example of testing whether the caller has the provided permissions on a subscription. */
public TestIamPermissionsResponse testSubscriptionPermissions(String subscriptionId)
throws Exception {
- try (PublisherClient publisherClient = PublisherClient.create()) {
- // [START testSubscriptionPermissions]
+ // [START testSubscriptionPermissions]
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
List permissions = new LinkedList<>();
permissions.add("pubsub.subscriptions.get");
SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
TestIamPermissionsResponse testedPermissions =
- publisherClient.testIamPermissions(subscriptionName.toString(), permissions);
- // [END testSubscriptionPermissions]
+ topicAdminClient.testIamPermissions(subscriptionName.toString(), permissions);
return testedPermissions;
}
+ // [END testSubscriptionPermissions]
}
/** Example of getting a subscription. */
public Subscription getSubscription(String subscriptionId) throws Exception {
- try (SubscriberClient subscriberClient = SubscriberClient.create()) {
- // [START getSubscription]
+ // [START getSubscription]
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId);
- Subscription subscription = subscriberClient.getSubscription(subscriptionName);
- // [END getSubscription]
+ Subscription subscription = subscriptionAdminClient.getSubscription(subscriptionName);
return subscription;
}
+ // [END getSubscription]
}
}
diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherClientSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/TopicAdminClientSnippets.java
similarity index 70%
rename from google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherClientSnippets.java
rename to google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/TopicAdminClientSnippets.java
index 9737bf4a3087..62855bd09081 100644
--- a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherClientSnippets.java
+++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/TopicAdminClientSnippets.java
@@ -21,7 +21,7 @@
import com.google.cloud.ServiceOptions;
import com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicSubscriptionsPagedResponse;
import com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicsPagedResponse;
-import com.google.cloud.pubsub.spi.v1.PublisherClient;
+import com.google.cloud.pubsub.spi.v1.TopicAdminClient;
import com.google.iam.v1.Binding;
import com.google.iam.v1.Policy;
import com.google.iam.v1.TestIamPermissionsResponse;
@@ -33,12 +33,12 @@
import java.util.LinkedList;
import java.util.List;
-/** This class contains a number of snippets for the {@link PublisherClient} interface. */
-public class PublisherClientSnippets {
+/** This class contains a number of snippets for the {@link TopicAdminClient} interface. */
+public class TopicAdminClientSnippets {
private final String projectId;
- public PublisherClientSnippets() {
+ public TopicAdminClientSnippets() {
this.projectId = ServiceOptions.getDefaultProjectId();
}
@@ -48,85 +48,85 @@ public String getProjectId() {
/** Example of creating a topic. */
public Topic createTopic(String topicId) throws Exception {
- try (PublisherClient publisherClient = PublisherClient.create()) {
- // [START createTopic]
+ // [START createTopic]
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
TopicName topicName = TopicName.create(projectId, topicId);
- Topic topic = publisherClient.createTopic(topicName);
- // [END createTopic]
+ Topic topic = topicAdminClient.createTopic(topicName);
return topic;
}
+ // [END createTopic]
}
/** Example of listing topics. */
public ListTopicsPagedResponse listTopics() throws Exception {
- try (PublisherClient publisherClient = PublisherClient.create()) {
- // [START listTopics]
+ // [START listTopics]
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
ListTopicsRequest listTopicsRequest =
ListTopicsRequest.newBuilder()
.setProjectWithProjectName(ProjectName.create(projectId))
.build();
- ListTopicsPagedResponse response = publisherClient.listTopics(listTopicsRequest);
+ ListTopicsPagedResponse response = topicAdminClient.listTopics(listTopicsRequest);
Iterable topics = response.iterateAllElements();
for (Topic topic : topics) {
// do something with the topic
}
- // [END listTopics]
return response;
}
+ // [END listTopics]
}
/** Example of listing topics for a subscription. */
public ListTopicSubscriptionsPagedResponse listTopicSubscriptions(String topicId)
throws Exception {
- try (PublisherClient publisherClient = PublisherClient.create()) {
- // [START listTopicSubscriptions]
+ // [START listTopicSubscriptions]
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
TopicName topicName = TopicName.create(projectId, topicId);
ListTopicSubscriptionsRequest request =
ListTopicSubscriptionsRequest.newBuilder()
.setTopicWithTopicName(topicName)
.build();
ListTopicSubscriptionsPagedResponse response =
- publisherClient.listTopicSubscriptions(request);
+ topicAdminClient.listTopicSubscriptions(request);
Iterable subscriptionNames = response.iterateAllElements();
for (String subscriptionName : subscriptionNames) {
// do something with the subscription name
}
- // [END listTopicSubscriptions]
return response;
}
+ // [END listTopicSubscriptions]
}
/** Example of deleting a topic. */
public TopicName deleteTopic(String topicId) throws Exception {
- try (PublisherClient publisherClient = PublisherClient.create()) {
- // [START deleteTopic]
+ // [START deleteTopic]
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
TopicName topicName = TopicName.create(projectId, topicId);
- publisherClient.deleteTopic(topicName);
- // [END deleteTopic]
+ topicAdminClient.deleteTopic(topicName);
return topicName;
}
+ // [END deleteTopic]
}
/** Example of getting a topic policy. */
public Policy getTopicPolicy(String topicId) throws Exception {
- try (PublisherClient publisherClient = PublisherClient.create()) {
- // [START getTopicPolicy]
+ // [START getTopicPolicy]
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
TopicName topicName = TopicName.create(projectId, topicId);
- Policy policy = publisherClient.getIamPolicy(topicName.toString());
+ Policy policy = topicAdminClient.getIamPolicy(topicName.toString());
if (policy == null) {
// topic iam policy was not found
}
- // [END getTopicPolicy]
return policy;
}
+ // [END getTopicPolicy]
}
/** Example of replacing a topic policy. */
public Policy replaceTopicPolicy(String topicId) throws Exception {
- try (PublisherClient publisherClient = PublisherClient.create()) {
- // [START replaceTopicPolicy]
+ // [START replaceTopicPolicy]
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
String topicName = TopicName.create(projectId, topicId).toString();
- Policy policy = publisherClient.getIamPolicy(topicName);
+ Policy policy = topicAdminClient.getIamPolicy(topicName);
// add role -> members binding
Binding binding =
Binding.newBuilder()
@@ -135,35 +135,35 @@ public Policy replaceTopicPolicy(String topicId) throws Exception {
.build();
// create updated policy
Policy updatedPolicy = Policy.newBuilder(policy).addBindings(binding).build();
- updatedPolicy = publisherClient.setIamPolicy(topicName, updatedPolicy);
- // [END replaceTopicPolicy]
+ updatedPolicy = topicAdminClient.setIamPolicy(topicName, updatedPolicy);
return updatedPolicy;
}
+ // [END replaceTopicPolicy]
}
/** Example of testing whether the caller has the provided permissions on a topic.
* Only viewer, editor or admin/owner can view results of pubsub.topics.get */
public TestIamPermissionsResponse testTopicPermissions(String topicId) throws Exception {
- try (PublisherClient publisherClient = PublisherClient.create()) {
- // [START testTopicPermissions]
+ // [START testTopicPermissions]
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
List permissions = new LinkedList<>();
permissions.add("pubsub.topics.get");
TopicName topicName = TopicName.create(projectId, topicId);
TestIamPermissionsResponse testedPermissions =
- publisherClient.testIamPermissions(topicName.toString(), permissions);
- // [END testTopicPermissions]
+ topicAdminClient.testIamPermissions(topicName.toString(), permissions);
return testedPermissions;
}
+ // [END testTopicPermissions]
}
/** Example of getting a topic. */
public Topic getTopic(String topicId) throws Exception {
- try (PublisherClient publisherClient = PublisherClient.create()) {
- // [START getTopic]
+ // [START getTopic]
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
TopicName topicName = TopicName.create(projectId, topicId);
- Topic topic = publisherClient.getTopic(topicName);
- // [END createTopic]
+ Topic topic = topicAdminClient.getTopic(topicName);
return topic;
}
+ // [END getTopic]
}
}
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 547689b96f80..5e3829698177 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
@@ -28,9 +28,9 @@
import java.util.Map;
/**
- * An example of using Google Translate.
+ * An example of using Google Translation.
*
- * This example demonstrates a simple/typical Translate usage.
+ *
This example demonstrates a simple/typical Translation usage.
*
*
See the
*
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 5d506fe22fec..ab28d630f728 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
@@ -29,7 +29,7 @@
import com.google.cloud.translate.Translation;
/**
- * A snippet for Google Translate showing how to detect the language of some text and translate
+ * A snippet for Google Translation showing how to detect the language of some text and translate
* some other text.
*/
public class DetectLanguageAndTranslate {
diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/Cleanup.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/Cleanup.java
index c9911fd392a3..3f2c9e64be73 100644
--- a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/Cleanup.java
+++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/Cleanup.java
@@ -16,8 +16,8 @@
package com.google.cloud.examples.pubsub.snippets;
-import com.google.cloud.pubsub.spi.v1.PublisherClient;
-import com.google.cloud.pubsub.spi.v1.SubscriberClient;
+import com.google.cloud.pubsub.spi.v1.TopicAdminClient;
+import com.google.cloud.pubsub.spi.v1.SubscriptionAdminClient;
import com.google.pubsub.v1.SubscriptionName;
import com.google.pubsub.v1.TopicName;
@@ -30,10 +30,10 @@ protected static void deleteTestTopicsAndSubscriptions(
}
private static void deleteTestTopics(String projectId, String[] testTopics) throws Exception {
- try (PublisherClient publisherClient = PublisherClient.create()) {
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
for (String topicId : testTopics) {
try {
- publisherClient.deleteTopic(TopicName.create(projectId, topicId));
+ topicAdminClient.deleteTopic(TopicName.create(projectId, topicId));
System.out.println("Topic deleted : " + topicId);
} catch (Exception e) {
//do nothing catch clause
@@ -44,10 +44,10 @@ private static void deleteTestTopics(String projectId, String[] testTopics) thro
private static void deleteTestSubscriptions(String projectId, String[] subscriptions)
throws Exception {
- try (SubscriberClient subscriberClient = SubscriberClient.create()) {
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
for (String subscriptionId : subscriptions) {
try {
- subscriberClient.deleteSubscription(
+ subscriptionAdminClient.deleteSubscription(
SubscriptionName.create(projectId, subscriptionId));
System.out.println("Subscription deleted : " + subscriptionId);
} catch (Exception e) {
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
new file mode 100644
index 000000000000..fc329f660585
--- /dev/null
+++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITPubSubSnippets.java
@@ -0,0 +1,127 @@
+/*
+ * 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.examples.pubsub.snippets;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import com.google.api.gax.core.ApiFutureCallback;
+import com.google.api.gax.core.ApiFutures;
+import com.google.api.gax.core.SettableApiFuture;
+import com.google.cloud.ServiceOptions;
+import com.google.cloud.pubsub.spi.v1.Publisher;
+import com.google.cloud.pubsub.spi.v1.SubscriptionAdminClient;
+import com.google.cloud.pubsub.spi.v1.TopicAdminClient;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.google.pubsub.v1.PubsubMessage;
+import com.google.pubsub.v1.PushConfig;
+import com.google.pubsub.v1.SubscriptionName;
+import com.google.pubsub.v1.TopicName;
+import java.util.UUID;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.TimeUnit;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.Timeout;
+
+public class ITPubSubSnippets {
+
+ private static final String NAME_SUFFIX = UUID.randomUUID().toString();
+
+ @Rule public Timeout globalTimeout = Timeout.seconds(300);
+
+ private static String formatForTest(String resourceName) {
+ return resourceName + "-" + NAME_SUFFIX;
+ }
+
+ @Test
+ public void testPublisherSubscriber() throws Exception {
+ TopicName topicName =
+ TopicName.create(ServiceOptions.getDefaultProjectId(), formatForTest("test-topic"));
+ SubscriptionName subscriptionName =
+ SubscriptionName.create(
+ ServiceOptions.getDefaultProjectId(), formatForTest("test-subscription"));
+ try (TopicAdminClient publisherClient = TopicAdminClient.create();
+ SubscriptionAdminClient subscriberClient = SubscriptionAdminClient.create()) {
+ publisherClient.createTopic(topicName);
+ subscriberClient.createSubscription(
+ subscriptionName, topicName, PushConfig.getDefaultInstance(), 0);
+
+ testPublisherSubscriberHelper(topicName, subscriptionName);
+
+ subscriberClient.deleteSubscription(subscriptionName);
+ publisherClient.deleteTopic(topicName);
+ }
+ }
+
+ private void testPublisherSubscriberHelper(TopicName topicName, SubscriptionName subscriptionName)
+ throws Exception {
+ String messageToPublish = "my-message";
+
+ Publisher publisher = null;
+ try {
+ publisher = Publisher.defaultBuilder(topicName).build();
+ PublisherSnippets snippets = new PublisherSnippets(publisher);
+ final SettableApiFuture done = SettableApiFuture.create();
+ ApiFutures.addCallback(
+ snippets.publish(messageToPublish),
+ new ApiFutureCallback() {
+ public void onSuccess(String messageId) {
+ done.set(null);
+ }
+
+ public void onFailure(Throwable t) {
+ done.setException(t);
+ }
+ });
+ done.get();
+ } finally {
+ if (publisher != null) {
+ publisher.shutdown();
+ }
+ }
+
+ final BlockingQueue queue = new ArrayBlockingQueue<>(1);
+ final SettableApiFuture done = SettableApiFuture.create();
+ final SettableApiFuture received = SettableApiFuture.create();
+ SubscriberSnippets snippets =
+ new SubscriberSnippets(
+ subscriptionName,
+ new MessageReceiverSnippets(queue).messageReceiver(),
+ done,
+ MoreExecutors.directExecutor());
+ new Thread(
+ new Runnable() {
+ @Override
+ public void run() {
+ try {
+ received.set(queue.poll(10, TimeUnit.MINUTES));
+ } catch (InterruptedException e) {
+ received.set(null);
+ }
+ done.set(null); // signal the subscriber to clean up
+ }
+ })
+ .start();
+ snippets.startAndWait(); // blocks until done is set
+
+ PubsubMessage message = received.get();
+ assertNotNull(message);
+ assertEquals(message.getData().toStringUtf8(), messageToPublish);
+ }
+}
diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriberClientSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriptionAdminClientSnippets.java
similarity index 68%
rename from google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriberClientSnippets.java
rename to google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriptionAdminClientSnippets.java
index 50fc5b52ac93..82caac5d5288 100644
--- a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriberClientSnippets.java
+++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriptionAdminClientSnippets.java
@@ -25,7 +25,7 @@
import com.google.cloud.Role;
import com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListSubscriptionsPagedResponse;
import com.google.cloud.pubsub.spi.v1.Publisher;
-import com.google.cloud.pubsub.spi.v1.PublisherClient;
+import com.google.cloud.pubsub.spi.v1.TopicAdminClient;
import com.google.common.collect.Iterables;
import com.google.iam.v1.Policy;
import com.google.iam.v1.TestIamPermissionsResponse;
@@ -47,13 +47,13 @@
import org.junit.Test;
import org.junit.rules.Timeout;
-public class ITSubscriberClientSnippets {
+public class ITSubscriptionAdminClientSnippets {
private static final String NAME_SUFFIX = UUID.randomUUID().toString();
private static String projectId;
- private static SubscriberClientSnippets subscriberClientSnippets;
+ private static SubscriptionAdminClientSnippets subscriptionAdminClientSnippets;
private static String[] topics = {
formatForTest("topic-1"),
@@ -73,8 +73,8 @@ private static String formatForTest(String resourceName) {
@BeforeClass
public static void beforeClass() {
- subscriberClientSnippets = new SubscriberClientSnippets();
- projectId = subscriberClientSnippets.getProjectId();
+ subscriptionAdminClientSnippets = new SubscriptionAdminClientSnippets();
+ projectId = subscriptionAdminClientSnippets.getProjectId();
}
@Before
@@ -82,36 +82,19 @@ public void setUp() throws Exception {
Cleanup.deleteTestTopicsAndSubscriptions(projectId, topics, subscriptions);
}
- private Subscription createSubscription(String topicName, String subscriptionName)
- throws Exception {
+ @Test
+ public void createSubscriptionWithPushIsSuccessful() throws Exception {
+ String topicName = topics[0];
+ String subscriptionName = subscriptions[0];
createTopic(topicName);
+ String endpoint = "https://" + projectId + ".appspot.com/push";
Subscription subscription =
- subscriberClientSnippets.createSubscription(topicName, subscriptionName);
+ subscriptionAdminClientSnippets.createSubscriptionWithPushEndpoint(topicName, subscriptionName, endpoint);
assertNotNull(subscription);
- Subscription retrievedSubscription = subscriberClientSnippets.getSubscription(subscriptionName);
+ Subscription retrievedSubscription = subscriptionAdminClientSnippets.getSubscription(subscriptionName);
assertNotNull(retrievedSubscription);
assertEquals(subscription.getName(), retrievedSubscription.getName());
- return subscription;
- }
-
- @Test
- public void publishAndPullMessagesIsSuccessful() throws Exception {
- String topicName = topics[0];
- String subscriptionName = subscriptions[0];
- createSubscription(topicName, subscriptionName);
- Set messages = publishMessages(topicName, 5);
- //pulls max 100 messages
- PullResponse response = subscriberClientSnippets.pull(subscriptionName);
- assertNotNull(response);
- //remove messages that match sent
- for (ReceivedMessage receivedMessage : response.getReceivedMessagesList()) {
- String message = receivedMessage.getMessage().getData().toStringUtf8();
- if (messages.contains(message)) {
- messages.remove(message);
- }
- }
- //all messages published were received
- assertTrue(messages.isEmpty());
+ assertEquals(subscription.getPushConfig().getPushEndpoint(), endpoint);
}
@Test
@@ -120,8 +103,8 @@ public void replacePushConfigIsSuccessful() throws Exception {
String subscriptionName = subscriptions[0];
createSubscription(topicName, subscriptionName);
String endpoint = "https://" + projectId + ".appspot.com/push";
- subscriberClientSnippets.replacePushConfig(subscriptionName, endpoint);
- Subscription subscription = subscriberClientSnippets.getSubscription(subscriptionName);
+ subscriptionAdminClientSnippets.replacePushConfig(subscriptionName, endpoint);
+ Subscription subscription = subscriptionAdminClientSnippets.getSubscription(subscriptionName);
assertNotNull(subscription.getPushConfig());
assertEquals(subscription.getPushConfig().getPushEndpoint(), endpoint);
}
@@ -137,7 +120,7 @@ public void listSubscriptionsRetrievesAllAddedSubscriptions() throws Exception {
addedSubscriptions.add(createSubscription(topicName2, subscriptionName2));
boolean[] subFound = {false, false};
- ListSubscriptionsPagedResponse response = subscriberClientSnippets.listSubscriptions();
+ ListSubscriptionsPagedResponse response = subscriptionAdminClientSnippets.listSubscriptions();
assertNotNull(response);
Iterable subscriptions = response.iterateAllElements();
for (int i = 0; i < 2; i++) {
@@ -153,9 +136,9 @@ public void deleteSubscriptionThrowsExceptionWhenRetrieved() throws Exception {
String topicName = topics[0];
String subscriptionName = subscriptions[0];
createSubscription(topicName, subscriptionName);
- subscriberClientSnippets.deleteSubscription(subscriptionName);
+ subscriptionAdminClientSnippets.deleteSubscription(subscriptionName);
//expected to throw exception on retrieval
- subscriberClientSnippets.getSubscription(subscriptionName);
+ subscriptionAdminClientSnippets.getSubscription(subscriptionName);
}
@Test
@@ -163,7 +146,7 @@ public void subscriptionHasValidIamPolicy() throws Exception {
String topicName = topics[0];
String subscriptionName = subscriptions[0];
createSubscription(topicName, subscriptionName);
- Policy policy = subscriberClientSnippets.getSubscriptionPolicy(subscriptionName);
+ Policy policy = subscriptionAdminClientSnippets.getSubscriptionPolicy(subscriptionName);
assertNotNull(policy);
}
@@ -172,33 +155,32 @@ public void replaceSubscriptionPolicyAndTestPermissionsIsSuccessful() throws Exc
String topicName = topics[0];
String subscriptionName = subscriptions[0];
createSubscription(topicName, subscriptionName);
- Policy policy = subscriberClientSnippets.replaceSubscriptionPolicy(subscriptionName);
+ Policy policy = subscriptionAdminClientSnippets.replaceSubscriptionPolicy(subscriptionName);
assertNotNull(policy.getBindingsCount());
assertTrue(policy.getBindings(0).getRole().equalsIgnoreCase(Role.viewer().toString()));
assertTrue(policy.getBindings(0).getMembers(0)
.equalsIgnoreCase(Identity.allAuthenticatedUsers().toString()));
TestIamPermissionsResponse response =
- subscriberClientSnippets.testSubscriptionPermissions(subscriptionName);
+ subscriptionAdminClientSnippets.testSubscriptionPermissions(subscriptionName);
assertTrue(response.getPermissionsList().contains("pubsub.subscriptions.get"));
}
private void createTopic(String name) throws Exception {
- try (PublisherClient publisherClient = PublisherClient.create()) {
- publisherClient.createTopic(TopicName.create(projectId, name));
+ try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) {
+ topicAdminClient.createTopic(TopicName.create(projectId, name));
}
}
- private Set publishMessages(String topicName, int numMessages) throws Exception {
- Set messages = new HashSet<>();
- Publisher publisher = Publisher.newBuilder(TopicName.create(projectId, topicName)).build();
- for (int i = 1; i<= numMessages; i++) {
- String message = formatForTest("message-" + i);
- PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(
- ByteString.copyFromUtf8(message)).build();
- publisher.publish(pubsubMessage);
- messages.add(message);
- }
- return messages;
+ private Subscription createSubscription(String topicName, String subscriptionName)
+ throws Exception {
+ createTopic(topicName);
+ Subscription subscription =
+ subscriptionAdminClientSnippets.createSubscription(topicName, subscriptionName);
+ assertNotNull(subscription);
+ Subscription retrievedSubscription = subscriptionAdminClientSnippets.getSubscription(subscriptionName);
+ assertNotNull(retrievedSubscription);
+ assertEquals(subscription.getName(), retrievedSubscription.getName());
+ return subscription;
}
@After
diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITPublisherClientSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITTopicAdminClientSnippets.java
similarity index 77%
rename from google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITPublisherClientSnippets.java
rename to google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITTopicAdminClientSnippets.java
index d607a1568d45..c3cd9cffc86e 100644
--- a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITPublisherClientSnippets.java
+++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITTopicAdminClientSnippets.java
@@ -25,7 +25,7 @@
import com.google.cloud.Role;
import com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicSubscriptionsPagedResponse;
import com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicsPagedResponse;
-import com.google.cloud.pubsub.spi.v1.SubscriberClient;
+import com.google.cloud.pubsub.spi.v1.SubscriptionAdminClient;
import com.google.common.collect.Iterables;
import com.google.iam.v1.Policy;
import com.google.iam.v1.TestIamPermissionsResponse;
@@ -44,13 +44,13 @@
import org.junit.Test;
import org.junit.rules.Timeout;
-public class ITPublisherClientSnippets {
+public class ITTopicAdminClientSnippets {
private static final String NAME_SUFFIX = UUID.randomUUID().toString();
private static String projectId;
- private static PublisherClientSnippets publisherClientSnippets;
+ private static TopicAdminClientSnippets topicAdminClientSnippets;
private static String[] topics = {
formatForTest("topic-1"),
@@ -70,8 +70,8 @@ private static String formatForTest(String resourceName) {
@BeforeClass
public static void beforeClass() {
- publisherClientSnippets = new PublisherClientSnippets();
- projectId = publisherClientSnippets.getProjectId();
+ topicAdminClientSnippets = new TopicAdminClientSnippets();
+ projectId = topicAdminClientSnippets.getProjectId();
}
@Before
@@ -82,9 +82,9 @@ public void setUp() throws Exception {
@Test
public void topicAddedIsSameAsRetrieved() throws Exception {
String topicName = topics[0];
- Topic topicAdded = publisherClientSnippets.createTopic(topicName);
+ Topic topicAdded = topicAdminClientSnippets.createTopic(topicName);
assertNotNull(topicAdded);
- Topic topicRetrieved = publisherClientSnippets.getTopic(topicName);
+ Topic topicRetrieved = topicAdminClientSnippets.getTopic(topicName);
assertEquals(topicAdded, topicRetrieved);
}
@@ -92,12 +92,12 @@ public void topicAddedIsSameAsRetrieved() throws Exception {
public void listTopicsRetreivesAddedTopics() throws Exception {
List addedTopics = new ArrayList<>();
String topicName1 = topics[0];
- addedTopics.add(publisherClientSnippets.createTopic(topicName1));
+ addedTopics.add(topicAdminClientSnippets.createTopic(topicName1));
String topicName2 = topics[1];
- addedTopics.add(publisherClientSnippets.createTopic(topicName2));
+ addedTopics.add(topicAdminClientSnippets.createTopic(topicName2));
boolean[] topicFound = {false, false};
- ListTopicsPagedResponse response = publisherClientSnippets.listTopics();
+ ListTopicsPagedResponse response = topicAdminClientSnippets.listTopics();
assertNotNull(response);
Iterable topics = response.iterateAllElements();
@@ -114,7 +114,7 @@ public void listTopicsRetreivesAddedTopics() throws Exception {
public void listTopicSubscriptionsRetrievesAddedSubscriptions() throws Exception {
List addedSubscriptions = new ArrayList<>();
String topicName1 = topics[0];
- publisherClientSnippets.createTopic(topicName1);
+ topicAdminClientSnippets.createTopic(topicName1);
String subscriptionName1 = subscriptions[0];
String subscriptionName2 = subscriptions[1];
addedSubscriptions.add(createSubscription(topicName1, subscriptionName1));
@@ -123,7 +123,7 @@ public void listTopicSubscriptionsRetrievesAddedSubscriptions() throws Exception
boolean[] subFound = {false, false};
ListTopicSubscriptionsPagedResponse response =
- publisherClientSnippets.listTopicSubscriptions(topicName1);
+ topicAdminClientSnippets.listTopicSubscriptions(topicName1);
assertNotNull(response);
@@ -139,37 +139,37 @@ public void listTopicSubscriptionsRetrievesAddedSubscriptions() throws Exception
@Test(expected = ApiException.class)
public void deletedTopicIsNotRetrievableAndThrowsException() throws Exception {
String topicName = topics[0];
- Topic topicAdded = publisherClientSnippets.createTopic(topicName);
+ Topic topicAdded = topicAdminClientSnippets.createTopic(topicName);
assertNotNull(topicAdded);
- TopicName formattedName = publisherClientSnippets.deleteTopic(topicName);
+ TopicName formattedName = topicAdminClientSnippets.deleteTopic(topicName);
assertNotNull(formattedName);
- publisherClientSnippets.getTopic(topicName);
+ topicAdminClientSnippets.getTopic(topicName);
}
@Test
public void topicPolicyIsCorrectlyRetrieved() throws Exception {
String topicName = topics[0];
- publisherClientSnippets.createTopic(topicName);
- Policy policy = publisherClientSnippets.getTopicPolicy(topicName);
+ topicAdminClientSnippets.createTopic(topicName);
+ Policy policy = topicAdminClientSnippets.getTopicPolicy(topicName);
assertNotNull(policy);
}
@Test
public void replaceTopicPolicyAndTestPermissionsIsSuccessful() throws Exception {
String topicName = topics[0];
- publisherClientSnippets.createTopic(topicName);
- Policy policy = publisherClientSnippets.replaceTopicPolicy(topicName);
+ topicAdminClientSnippets.createTopic(topicName);
+ Policy policy = topicAdminClientSnippets.replaceTopicPolicy(topicName);
assertNotNull(policy.getBindingsCount());
assertTrue(policy.getBindings(0).getRole().equalsIgnoreCase(Role.viewer().toString()));
assertTrue(policy.getBindings(0).getMembers(0)
.equalsIgnoreCase(Identity.allAuthenticatedUsers().toString()));
- TestIamPermissionsResponse response = publisherClientSnippets.testTopicPermissions(topicName);
+ TestIamPermissionsResponse response = topicAdminClientSnippets.testTopicPermissions(topicName);
assertTrue(response.getPermissionsList().contains("pubsub.topics.get"));
}
private String createSubscription(String topic, String subscriptionName) throws Exception {
- try (SubscriberClient subscriberClient = SubscriberClient.create()) {
- Subscription subscription = subscriberClient.createSubscription(
+ try (SubscriptionAdminClient subscriptionAdminClient = SubscriptionAdminClient.create()) {
+ Subscription subscription = subscriptionAdminClient.createSubscription(
SubscriptionName.create(projectId, subscriptionName),
TopicName.create(projectId, topic), PushConfig.getDefaultInstance(), 0);
return subscription.getName();
diff --git a/google-cloud-language/pom.xml b/google-cloud-language/pom.xml
index 5116fb1a435b..6c3e3f43fbc3 100644
--- a/google-cloud-language/pom.xml
+++ b/google-cloud-language/pom.xml
@@ -2,6 +2,7 @@
4.0.0
google-cloud-language
+ ${beta.version}
jar
Google Cloud Natural Language
https://github.com/GoogleCloudPlatform/google-cloud-java/tree/master/google-cloud-language
@@ -11,10 +12,11 @@
com.google.cloud
google-cloud-pom
- 0.10.1-alpha-SNAPSHOT
+ 0.12.1-alpha-SNAPSHOT
google-cloud-language
+ ${project.version}
@@ -30,7 +32,18 @@
com.google.api.grpc
grpc-google-cloud-language-v1
- 0.1.5
+ 0.1.6
+
+
+ io.grpc
+ grpc-all
+
+
+
+
+ com.google.api.grpc
+ grpc-google-cloud-language-v1beta2
+ 0.1.6
io.grpc
@@ -87,6 +100,22 @@
+
+ org.codehaus.mojo
+ properties-maven-plugin
+ 1.0-alpha-2
+
+
+ generate-resources
+
+ write-project-properties
+
+
+ ${project.build.outputDirectory}/project.properties
+
+
+
+
org.codehaus.mojo
build-helper-maven-plugin
diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1/LanguageServiceClient.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1/LanguageServiceClient.java
index d36a394e2fc1..e52b83183e25 100644
--- a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1/LanguageServiceClient.java
+++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1/LanguageServiceClient.java
@@ -238,8 +238,8 @@ 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 proper names and common nouns) in the text along with entity
+ * types, salience, mentions for each entity, and other properties.
*
* Sample code:
*
@@ -268,8 +268,8 @@ 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 proper names and common nouns) in the text along with entity
+ * types, salience, mentions for each entity, and other properties.
*
*
Sample code:
*
@@ -294,8 +294,8 @@ 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 proper names and common nouns) in the text along with entity
+ * types, salience, mentions for each entity, and other properties.
*
*
Sample code:
*
diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1/LanguageServiceSettings.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1/LanguageServiceSettings.java
index a28ce690798d..2efab91f55de 100644
--- a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1/LanguageServiceSettings.java
+++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1/LanguageServiceSettings.java
@@ -16,6 +16,7 @@
package com.google.cloud.language.spi.v1;
import com.google.api.gax.core.GoogleCredentialsProvider;
+import com.google.api.gax.core.PropertiesProvider;
import com.google.api.gax.core.RetrySettings;
import com.google.api.gax.grpc.ChannelProvider;
import com.google.api.gax.grpc.ClientSettings;
@@ -73,12 +74,6 @@
@Generated("by GAPIC v0.0.5")
@ExperimentalApi
public class LanguageServiceSettings extends ClientSettings {
- /** The default address of the service. */
- private static final String DEFAULT_SERVICE_ADDRESS = "language.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().add("https://www.googleapis.com/auth/cloud-platform").build();
@@ -86,6 +81,11 @@ public class LanguageServiceSettings extends ClientSettings {
private static final String DEFAULT_GAPIC_NAME = "gapic";
private static final String DEFAULT_GAPIC_VERSION = "";
+ private static final String PROPERTIES_FILE = "/project.properties";
+ private static final String META_VERSION_KEY = "artifact.version";
+
+ private static String gapicVersion;
+
private final SimpleCallSettings
analyzeSentimentSettings;
private final SimpleCallSettings
@@ -121,14 +121,9 @@ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuild
return InstantiatingExecutorProvider.newBuilder();
}
- /** 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 endpoint. */
+ public static String getDefaultEndpoint() {
+ return "language.googleapis.com:443";
}
/** Returns the default service scopes. */
@@ -144,15 +139,19 @@ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilde
/** Returns a builder for the default ChannelProvider for this service. */
public static InstantiatingChannelProvider.Builder defaultChannelProviderBuilder() {
return InstantiatingChannelProvider.newBuilder()
- .setServiceAddress(DEFAULT_SERVICE_ADDRESS)
- .setPort(DEFAULT_SERVICE_PORT)
+ .setEndpoint(getDefaultEndpoint())
.setGeneratorHeader(DEFAULT_GAPIC_NAME, getGapicVersion())
.setCredentialsProvider(defaultCredentialsProviderBuilder().build());
}
private static String getGapicVersion() {
- String packageVersion = LanguageServiceSettings.class.getPackage().getImplementationVersion();
- return packageVersion != null ? packageVersion : DEFAULT_GAPIC_VERSION;
+ if (gapicVersion == null) {
+ gapicVersion =
+ PropertiesProvider.loadProperty(
+ LanguageServiceSettings.class, PROPERTIES_FILE, META_VERSION_KEY);
+ gapicVersion = gapicVersion == null ? DEFAULT_GAPIC_VERSION : gapicVersion;
+ }
+ return gapicVersion;
}
/** Returns a builder for this class with recommended defaults. */
diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta2/LanguageServiceClient.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta2/LanguageServiceClient.java
new file mode 100644
index 000000000000..06ae5526a0f1
--- /dev/null
+++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta2/LanguageServiceClient.java
@@ -0,0 +1,589 @@
+/*
+ * Copyright 2017, 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.v1beta2;
+
+import com.google.api.gax.grpc.ChannelAndExecutor;
+import com.google.api.gax.grpc.UnaryCallable;
+import com.google.cloud.language.v1beta2.AnalyzeEntitiesRequest;
+import com.google.cloud.language.v1beta2.AnalyzeEntitiesResponse;
+import com.google.cloud.language.v1beta2.AnalyzeEntitySentimentRequest;
+import com.google.cloud.language.v1beta2.AnalyzeEntitySentimentResponse;
+import com.google.cloud.language.v1beta2.AnalyzeSentimentRequest;
+import com.google.cloud.language.v1beta2.AnalyzeSentimentResponse;
+import com.google.cloud.language.v1beta2.AnalyzeSyntaxRequest;
+import com.google.cloud.language.v1beta2.AnalyzeSyntaxResponse;
+import com.google.cloud.language.v1beta2.AnnotateTextRequest;
+import com.google.cloud.language.v1beta2.AnnotateTextRequest.Features;
+import com.google.cloud.language.v1beta2.AnnotateTextResponse;
+import com.google.cloud.language.v1beta2.Document;
+import com.google.cloud.language.v1beta2.EncodingType;
+import com.google.protobuf.ExperimentalApi;
+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;
+import javax.annotation.Generated;
+
+// AUTO-GENERATED DOCUMENTATION AND SERVICE
+/**
+ * Service Description: Provides text analysis operations such as sentiment analysis and entity
+ * recognition.
+ *
+ * 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 (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * AnalyzeSentimentResponse response = languageServiceClient.analyzeSentiment(document);
+ * }
+ *
+ *
+ *
+ * Note: close() needs to be called on the languageServiceClient 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:
+ *
+ *
+ * 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.
+ * 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 API
+ * callable 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 LanguageServiceSettings to
+ * create(). For example:
+ *
+ *
+ *
+ * InstantiatingChannelProvider channelProvider =
+ * LanguageServiceSettings.defaultChannelProviderBuilder()
+ * .setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
+ * .build();
+ * LanguageServiceSettings languageServiceSettings =
+ * LanguageServiceSettings.defaultBuilder().setChannelProvider(channelProvider).build();
+ * LanguageServiceClient languageServiceClient =
+ * LanguageServiceClient.create(languageServiceSettings);
+ *
+ *
+ */
+@Generated("by GAPIC")
+@ExperimentalApi
+public class LanguageServiceClient implements AutoCloseable {
+ private final LanguageServiceSettings settings;
+ private final ScheduledExecutorService executor;
+ private final ManagedChannel channel;
+ private final List closeables = new ArrayList<>();
+
+ private final UnaryCallable
+ analyzeSentimentCallable;
+ private final UnaryCallable
+ analyzeEntitiesCallable;
+ private final UnaryCallable
+ analyzeEntitySentimentCallable;
+ private final UnaryCallable analyzeSyntaxCallable;
+ private final UnaryCallable annotateTextCallable;
+
+ /** Constructs an instance of LanguageServiceClient with default settings. */
+ public static final LanguageServiceClient create() throws IOException {
+ return create(LanguageServiceSettings.defaultBuilder().build());
+ }
+
+ /**
+ * Constructs an instance of LanguageServiceClient, 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 LanguageServiceClient create(LanguageServiceSettings settings)
+ throws IOException {
+ return new LanguageServiceClient(settings);
+ }
+
+ /**
+ * Constructs an instance of LanguageServiceClient, 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 LanguageServiceClient(LanguageServiceSettings settings) throws IOException {
+ this.settings = settings;
+ ChannelAndExecutor channelAndExecutor = settings.getChannelAndExecutor();
+ this.executor = channelAndExecutor.getExecutor();
+ this.channel = channelAndExecutor.getChannel();
+
+ this.analyzeSentimentCallable =
+ UnaryCallable.create(settings.analyzeSentimentSettings(), this.channel, this.executor);
+ this.analyzeEntitiesCallable =
+ UnaryCallable.create(settings.analyzeEntitiesSettings(), this.channel, this.executor);
+ this.analyzeEntitySentimentCallable =
+ UnaryCallable.create(
+ settings.analyzeEntitySentimentSettings(), this.channel, this.executor);
+ this.analyzeSyntaxCallable =
+ UnaryCallable.create(settings.analyzeSyntaxSettings(), this.channel, this.executor);
+ this.annotateTextCallable =
+ UnaryCallable.create(settings.annotateTextSettings(), 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 LanguageServiceSettings getSettings() {
+ return settings;
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * Analyzes the sentiment of the provided text.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * AnalyzeSentimentResponse response = languageServiceClient.analyzeSentiment(document);
+ * }
+ *
+ *
+ * @param document Input document. Currently, `analyzeSentiment` only supports English text
+ * ([Document.language][google.cloud.language.v1beta2.Document.language]="EN").
+ * @throws com.google.api.gax.grpc.ApiException if the remote call fails
+ */
+ public final AnalyzeSentimentResponse analyzeSentiment(Document document) {
+
+ AnalyzeSentimentRequest request =
+ AnalyzeSentimentRequest.newBuilder().setDocument(document).build();
+ return analyzeSentiment(request);
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * Analyzes the sentiment of the provided text.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * AnalyzeSentimentRequest request = AnalyzeSentimentRequest.newBuilder()
+ * .setDocument(document)
+ * .build();
+ * AnalyzeSentimentResponse response = languageServiceClient.analyzeSentiment(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
+ */
+ private final AnalyzeSentimentResponse analyzeSentiment(AnalyzeSentimentRequest request) {
+ return analyzeSentimentCallable().call(request);
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * Analyzes the sentiment of the provided text.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * AnalyzeSentimentRequest request = AnalyzeSentimentRequest.newBuilder()
+ * .setDocument(document)
+ * .build();
+ * ApiFuture<AnalyzeSentimentResponse> future = languageServiceClient.analyzeSentimentCallable().futureCall(request);
+ * // Do something
+ * AnalyzeSentimentResponse response = future.get();
+ * }
+ *
+ */
+ public final UnaryCallable
+ analyzeSentimentCallable() {
+ return analyzeSentimentCallable;
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * Finds named entities (currently proper names and common nouns) in the text along with entity
+ * types, salience, mentions for each entity, and other properties.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * EncodingType encodingType = EncodingType.NONE;
+ * AnalyzeEntitiesResponse response = languageServiceClient.analyzeEntities(document, encodingType);
+ * }
+ *
+ *
+ * @param document Input document.
+ * @param encodingType The encoding type used by the API to calculate offsets.
+ * @throws com.google.api.gax.grpc.ApiException if the remote call fails
+ */
+ public final AnalyzeEntitiesResponse analyzeEntities(
+ Document document, EncodingType encodingType) {
+
+ AnalyzeEntitiesRequest request =
+ AnalyzeEntitiesRequest.newBuilder()
+ .setDocument(document)
+ .setEncodingType(encodingType)
+ .build();
+ return analyzeEntities(request);
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * Finds named entities (currently proper names and common nouns) in the text along with entity
+ * types, salience, mentions for each entity, and other properties.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * EncodingType encodingType = EncodingType.NONE;
+ * AnalyzeEntitiesRequest request = AnalyzeEntitiesRequest.newBuilder()
+ * .setDocument(document)
+ * .setEncodingType(encodingType)
+ * .build();
+ * AnalyzeEntitiesResponse response = languageServiceClient.analyzeEntities(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 AnalyzeEntitiesResponse analyzeEntities(AnalyzeEntitiesRequest request) {
+ return analyzeEntitiesCallable().call(request);
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * Finds named entities (currently proper names and common nouns) in the text along with entity
+ * types, salience, mentions for each entity, and other properties.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * EncodingType encodingType = EncodingType.NONE;
+ * AnalyzeEntitiesRequest request = AnalyzeEntitiesRequest.newBuilder()
+ * .setDocument(document)
+ * .setEncodingType(encodingType)
+ * .build();
+ * ApiFuture<AnalyzeEntitiesResponse> future = languageServiceClient.analyzeEntitiesCallable().futureCall(request);
+ * // Do something
+ * AnalyzeEntitiesResponse response = future.get();
+ * }
+ *
+ */
+ public final UnaryCallable
+ analyzeEntitiesCallable() {
+ return analyzeEntitiesCallable;
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * Finds entities, similar to
+ * [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text
+ * and analyzes sentiment associated with each entity and its mentions.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * EncodingType encodingType = EncodingType.NONE;
+ * AnalyzeEntitySentimentResponse response = languageServiceClient.analyzeEntitySentiment(document, encodingType);
+ * }
+ *
+ *
+ * @param document Input document.
+ * @param encodingType The encoding type used by the API to calculate offsets.
+ * @throws com.google.api.gax.grpc.ApiException if the remote call fails
+ */
+ public final AnalyzeEntitySentimentResponse analyzeEntitySentiment(
+ Document document, EncodingType encodingType) {
+
+ AnalyzeEntitySentimentRequest request =
+ AnalyzeEntitySentimentRequest.newBuilder()
+ .setDocument(document)
+ .setEncodingType(encodingType)
+ .build();
+ return analyzeEntitySentiment(request);
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * Finds entities, similar to
+ * [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text
+ * and analyzes sentiment associated with each entity and its mentions.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * EncodingType encodingType = EncodingType.NONE;
+ * AnalyzeEntitySentimentRequest request = AnalyzeEntitySentimentRequest.newBuilder()
+ * .setDocument(document)
+ * .setEncodingType(encodingType)
+ * .build();
+ * AnalyzeEntitySentimentResponse response = languageServiceClient.analyzeEntitySentiment(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 AnalyzeEntitySentimentResponse analyzeEntitySentiment(
+ AnalyzeEntitySentimentRequest request) {
+ return analyzeEntitySentimentCallable().call(request);
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * Finds entities, similar to
+ * [AnalyzeEntities][google.cloud.language.v1beta2.LanguageService.AnalyzeEntities] in the text
+ * and analyzes sentiment associated with each entity and its mentions.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * EncodingType encodingType = EncodingType.NONE;
+ * AnalyzeEntitySentimentRequest request = AnalyzeEntitySentimentRequest.newBuilder()
+ * .setDocument(document)
+ * .setEncodingType(encodingType)
+ * .build();
+ * ApiFuture<AnalyzeEntitySentimentResponse> future = languageServiceClient.analyzeEntitySentimentCallable().futureCall(request);
+ * // Do something
+ * AnalyzeEntitySentimentResponse response = future.get();
+ * }
+ *
+ */
+ public final UnaryCallable
+ analyzeEntitySentimentCallable() {
+ return analyzeEntitySentimentCallable;
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * Analyzes the syntax of the text and provides sentence boundaries and tokenization along with
+ * part of speech tags, dependency trees, and other properties.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * EncodingType encodingType = EncodingType.NONE;
+ * AnalyzeSyntaxResponse response = languageServiceClient.analyzeSyntax(document, encodingType);
+ * }
+ *
+ *
+ * @param document Input document.
+ * @param encodingType The encoding type used by the API to calculate offsets.
+ * @throws com.google.api.gax.grpc.ApiException if the remote call fails
+ */
+ public final AnalyzeSyntaxResponse analyzeSyntax(Document document, EncodingType encodingType) {
+
+ AnalyzeSyntaxRequest request =
+ AnalyzeSyntaxRequest.newBuilder()
+ .setDocument(document)
+ .setEncodingType(encodingType)
+ .build();
+ return analyzeSyntax(request);
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * Analyzes the syntax of the text and provides sentence boundaries and tokenization along with
+ * part of speech tags, dependency trees, and other properties.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * EncodingType encodingType = EncodingType.NONE;
+ * AnalyzeSyntaxRequest request = AnalyzeSyntaxRequest.newBuilder()
+ * .setDocument(document)
+ * .setEncodingType(encodingType)
+ * .build();
+ * AnalyzeSyntaxResponse response = languageServiceClient.analyzeSyntax(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 AnalyzeSyntaxResponse analyzeSyntax(AnalyzeSyntaxRequest request) {
+ return analyzeSyntaxCallable().call(request);
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * Analyzes the syntax of the text and provides sentence boundaries and tokenization along with
+ * part of speech tags, dependency trees, and other properties.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * EncodingType encodingType = EncodingType.NONE;
+ * AnalyzeSyntaxRequest request = AnalyzeSyntaxRequest.newBuilder()
+ * .setDocument(document)
+ * .setEncodingType(encodingType)
+ * .build();
+ * ApiFuture<AnalyzeSyntaxResponse> future = languageServiceClient.analyzeSyntaxCallable().futureCall(request);
+ * // Do something
+ * AnalyzeSyntaxResponse response = future.get();
+ * }
+ *
+ */
+ public final UnaryCallable analyzeSyntaxCallable() {
+ return analyzeSyntaxCallable;
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * A convenience method that provides all syntax, sentiment, and entity features in one call.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * AnnotateTextRequest.Features features = AnnotateTextRequest.Features.newBuilder().build();
+ * EncodingType encodingType = EncodingType.NONE;
+ * AnnotateTextResponse response = languageServiceClient.annotateText(document, features, encodingType);
+ * }
+ *
+ *
+ * @param document Input document.
+ * @param features The enabled features.
+ * @param encodingType The encoding type used by the API to calculate offsets.
+ * @throws com.google.api.gax.grpc.ApiException if the remote call fails
+ */
+ public final AnnotateTextResponse annotateText(
+ Document document, AnnotateTextRequest.Features features, EncodingType encodingType) {
+
+ AnnotateTextRequest request =
+ AnnotateTextRequest.newBuilder()
+ .setDocument(document)
+ .setFeatures(features)
+ .setEncodingType(encodingType)
+ .build();
+ return annotateText(request);
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * A convenience method that provides all syntax, sentiment, and entity features in one call.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * AnnotateTextRequest.Features features = AnnotateTextRequest.Features.newBuilder().build();
+ * EncodingType encodingType = EncodingType.NONE;
+ * AnnotateTextRequest request = AnnotateTextRequest.newBuilder()
+ * .setDocument(document)
+ * .setFeatures(features)
+ * .setEncodingType(encodingType)
+ * .build();
+ * AnnotateTextResponse response = languageServiceClient.annotateText(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 AnnotateTextResponse annotateText(AnnotateTextRequest request) {
+ return annotateTextCallable().call(request);
+ }
+
+ // AUTO-GENERATED DOCUMENTATION AND METHOD
+ /**
+ * A convenience method that provides all syntax, sentiment, and entity features in one call.
+ *
+ * Sample code:
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * AnnotateTextRequest.Features features = AnnotateTextRequest.Features.newBuilder().build();
+ * EncodingType encodingType = EncodingType.NONE;
+ * AnnotateTextRequest request = AnnotateTextRequest.newBuilder()
+ * .setDocument(document)
+ * .setFeatures(features)
+ * .setEncodingType(encodingType)
+ * .build();
+ * ApiFuture<AnnotateTextResponse> future = languageServiceClient.annotateTextCallable().futureCall(request);
+ * // Do something
+ * AnnotateTextResponse response = future.get();
+ * }
+ *
+ */
+ public final UnaryCallable annotateTextCallable() {
+ return annotateTextCallable;
+ }
+
+ /**
+ * 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-language/src/main/java/com/google/cloud/language/spi/v1beta2/LanguageServiceSettings.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta2/LanguageServiceSettings.java
new file mode 100644
index 000000000000..144b5bc80709
--- /dev/null
+++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta2/LanguageServiceSettings.java
@@ -0,0 +1,376 @@
+/*
+ * Copyright 2017, 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.v1beta2;
+
+import com.google.api.gax.core.GoogleCredentialsProvider;
+import com.google.api.gax.core.PropertiesProvider;
+import com.google.api.gax.core.RetrySettings;
+import com.google.api.gax.grpc.ChannelProvider;
+import com.google.api.gax.grpc.ClientSettings;
+import com.google.api.gax.grpc.ExecutorProvider;
+import com.google.api.gax.grpc.InstantiatingChannelProvider;
+import com.google.api.gax.grpc.InstantiatingExecutorProvider;
+import com.google.api.gax.grpc.SimpleCallSettings;
+import com.google.api.gax.grpc.UnaryCallSettings;
+import com.google.cloud.language.v1beta2.AnalyzeEntitiesRequest;
+import com.google.cloud.language.v1beta2.AnalyzeEntitiesResponse;
+import com.google.cloud.language.v1beta2.AnalyzeEntitySentimentRequest;
+import com.google.cloud.language.v1beta2.AnalyzeEntitySentimentResponse;
+import com.google.cloud.language.v1beta2.AnalyzeSentimentRequest;
+import com.google.cloud.language.v1beta2.AnalyzeSentimentResponse;
+import com.google.cloud.language.v1beta2.AnalyzeSyntaxRequest;
+import com.google.cloud.language.v1beta2.AnalyzeSyntaxResponse;
+import com.google.cloud.language.v1beta2.AnnotateTextRequest;
+import com.google.cloud.language.v1beta2.AnnotateTextResponse;
+import com.google.cloud.language.v1beta2.LanguageServiceGrpc;
+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.protobuf.ExperimentalApi;
+import io.grpc.Status;
+import java.io.IOException;
+import javax.annotation.Generated;
+import org.joda.time.Duration;
+
+// AUTO-GENERATED DOCUMENTATION AND CLASS
+/**
+ * Settings class to configure an instance of {@link LanguageServiceClient}.
+ *
+ * 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 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:
+ *
+ *
+ *
+ * LanguageServiceSettings.Builder languageServiceSettingsBuilder =
+ * LanguageServiceSettings.defaultBuilder();
+ * languageServiceSettingsBuilder.analyzeSentimentSettings().getRetrySettingsBuilder()
+ * .setTotalTimeout(Duration.standardSeconds(30));
+ * LanguageServiceSettings languageServiceSettings = languageServiceSettingsBuilder.build();
+ *
+ *
+ */
+@Generated("by GAPIC v0.0.5")
+@ExperimentalApi
+public class LanguageServiceSettings extends ClientSettings {
+ /** The default scopes of the service. */
+ private static final ImmutableList DEFAULT_SERVICE_SCOPES =
+ ImmutableList.builder().add("https://www.googleapis.com/auth/cloud-platform").build();
+
+ private static final String DEFAULT_GAPIC_NAME = "gapic";
+ private static final String DEFAULT_GAPIC_VERSION = "";
+
+ private static final String PROPERTIES_FILE = "/project.properties";
+ private static final String META_VERSION_KEY = "artifact.version";
+
+ private static String gapicVersion;
+
+ private final SimpleCallSettings
+ analyzeSentimentSettings;
+ private final SimpleCallSettings
+ analyzeEntitiesSettings;
+ private final SimpleCallSettings
+ analyzeEntitySentimentSettings;
+ private final SimpleCallSettings
+ analyzeSyntaxSettings;
+ private final SimpleCallSettings annotateTextSettings;
+
+ /** 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. */
+ public SimpleCallSettings
+ analyzeEntitiesSettings() {
+ return analyzeEntitiesSettings;
+ }
+
+ /** Returns the object with the settings used for calls to analyzeEntitySentiment. */
+ public SimpleCallSettings
+ analyzeEntitySentimentSettings() {
+ return analyzeEntitySentimentSettings;
+ }
+
+ /** Returns the object with the settings used for calls to analyzeSyntax. */
+ public SimpleCallSettings analyzeSyntaxSettings() {
+ return analyzeSyntaxSettings;
+ }
+
+ /** Returns the object with the settings used for calls to annotateText. */
+ public SimpleCallSettings annotateTextSettings() {
+ return annotateTextSettings;
+ }
+
+ /** Returns a builder for the default ExecutorProvider for this service. */
+ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() {
+ return InstantiatingExecutorProvider.newBuilder();
+ }
+
+ /** Returns the default service endpoint. */
+ public static String getDefaultEndpoint() {
+ return "language.googleapis.com:443";
+ }
+
+ /** Returns the default service scopes. */
+ public static ImmutableList getDefaultServiceScopes() {
+ return DEFAULT_SERVICE_SCOPES;
+ }
+
+ /** Returns a builder for the default credentials for this service. */
+ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() {
+ return GoogleCredentialsProvider.newBuilder().setScopesToApply(DEFAULT_SERVICE_SCOPES);
+ }
+
+ /** Returns a builder for the default ChannelProvider for this service. */
+ public static InstantiatingChannelProvider.Builder defaultChannelProviderBuilder() {
+ return InstantiatingChannelProvider.newBuilder()
+ .setEndpoint(getDefaultEndpoint())
+ .setGeneratorHeader(DEFAULT_GAPIC_NAME, getGapicVersion())
+ .setCredentialsProvider(defaultCredentialsProviderBuilder().build());
+ }
+
+ private static String getGapicVersion() {
+ if (gapicVersion == null) {
+ gapicVersion =
+ PropertiesProvider.loadProperty(
+ LanguageServiceSettings.class, PROPERTIES_FILE, META_VERSION_KEY);
+ gapicVersion = gapicVersion == null ? DEFAULT_GAPIC_VERSION : gapicVersion;
+ }
+ return gapicVersion;
+ }
+
+ /** 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 LanguageServiceSettings(Builder settingsBuilder) throws IOException {
+ super(settingsBuilder.getExecutorProvider(), settingsBuilder.getChannelProvider());
+
+ analyzeSentimentSettings = settingsBuilder.analyzeSentimentSettings().build();
+ analyzeEntitiesSettings = settingsBuilder.analyzeEntitiesSettings().build();
+ analyzeEntitySentimentSettings = settingsBuilder.analyzeEntitySentimentSettings().build();
+ analyzeSyntaxSettings = settingsBuilder.analyzeSyntaxSettings().build();
+ annotateTextSettings = settingsBuilder.annotateTextSettings().build();
+ }
+
+ /** Builder for LanguageServiceSettings. */
+ public static class Builder extends ClientSettings.Builder {
+ private final ImmutableList unaryMethodSettingsBuilders;
+
+ private final SimpleCallSettings.Builder
+ analyzeSentimentSettings;
+ private final SimpleCallSettings.Builder
+ analyzeEntitiesSettings;
+ private final SimpleCallSettings.Builder<
+ AnalyzeEntitySentimentRequest, AnalyzeEntitySentimentResponse>
+ analyzeEntitySentimentSettings;
+ private final SimpleCallSettings.Builder
+ analyzeSyntaxSettings;
+ private final SimpleCallSettings.Builder
+ annotateTextSettings;
+
+ 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(Status.Code.UNAVAILABLE)));
+ 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(60000L))
+ .setRpcTimeoutMultiplier(1.0)
+ .setMaxRpcTimeout(Duration.millis(60000L))
+ .setTotalTimeout(Duration.millis(600000L));
+ definitions.put("default", settingsBuilder);
+ RETRY_PARAM_DEFINITIONS = definitions.build();
+ }
+
+ private Builder() {
+ super(defaultChannelProviderBuilder().build());
+
+ analyzeSentimentSettings =
+ SimpleCallSettings.newBuilder(LanguageServiceGrpc.METHOD_ANALYZE_SENTIMENT);
+
+ analyzeEntitiesSettings =
+ SimpleCallSettings.newBuilder(LanguageServiceGrpc.METHOD_ANALYZE_ENTITIES);
+
+ analyzeEntitySentimentSettings =
+ SimpleCallSettings.newBuilder(LanguageServiceGrpc.METHOD_ANALYZE_ENTITY_SENTIMENT);
+
+ analyzeSyntaxSettings =
+ SimpleCallSettings.newBuilder(LanguageServiceGrpc.METHOD_ANALYZE_SYNTAX);
+
+ annotateTextSettings =
+ SimpleCallSettings.newBuilder(LanguageServiceGrpc.METHOD_ANNOTATE_TEXT);
+
+ unaryMethodSettingsBuilders =
+ ImmutableList.of(
+ analyzeSentimentSettings,
+ analyzeEntitiesSettings,
+ analyzeEntitySentimentSettings,
+ analyzeSyntaxSettings,
+ annotateTextSettings);
+ }
+
+ private static Builder createDefault() {
+ Builder builder = new Builder();
+
+ builder
+ .analyzeSentimentSettings()
+ .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
+ .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));
+
+ builder
+ .analyzeEntitiesSettings()
+ .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
+ .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));
+
+ builder
+ .analyzeEntitySentimentSettings()
+ .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
+ .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));
+
+ builder
+ .analyzeSyntaxSettings()
+ .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
+ .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));
+
+ builder
+ .annotateTextSettings()
+ .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("idempotent"))
+ .setRetrySettingsBuilder(RETRY_PARAM_DEFINITIONS.get("default"));
+
+ return builder;
+ }
+
+ private Builder(LanguageServiceSettings settings) {
+ super(settings);
+
+ analyzeSentimentSettings = settings.analyzeSentimentSettings.toBuilder();
+ analyzeEntitiesSettings = settings.analyzeEntitiesSettings.toBuilder();
+ analyzeEntitySentimentSettings = settings.analyzeEntitySentimentSettings.toBuilder();
+ analyzeSyntaxSettings = settings.analyzeSyntaxSettings.toBuilder();
+ annotateTextSettings = settings.annotateTextSettings.toBuilder();
+
+ unaryMethodSettingsBuilders =
+ ImmutableList.of(
+ analyzeSentimentSettings,
+ analyzeEntitiesSettings,
+ analyzeEntitySentimentSettings,
+ analyzeSyntaxSettings,
+ annotateTextSettings);
+ }
+
+ @Override
+ public Builder setExecutorProvider(ExecutorProvider executorProvider) {
+ super.setExecutorProvider(executorProvider);
+ return this;
+ }
+
+ @Override
+ public Builder setChannelProvider(ChannelProvider channelProvider) {
+ super.setChannelProvider(channelProvider);
+ return this;
+ }
+
+ /**
+ * 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 applyToAllUnaryMethods(UnaryCallSettings.Builder unaryCallSettings)
+ throws Exception {
+ super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, unaryCallSettings);
+ return this;
+ }
+
+ /** 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. */
+ public SimpleCallSettings.Builder
+ analyzeEntitiesSettings() {
+ return analyzeEntitiesSettings;
+ }
+
+ /** Returns the builder for the settings used for calls to analyzeEntitySentiment. */
+ public SimpleCallSettings.Builder
+ analyzeEntitySentimentSettings() {
+ return analyzeEntitySentimentSettings;
+ }
+
+ /** Returns the builder for the settings used for calls to analyzeSyntax. */
+ public SimpleCallSettings.Builder
+ analyzeSyntaxSettings() {
+ return analyzeSyntaxSettings;
+ }
+
+ /** Returns the builder for the settings used for calls to annotateText. */
+ public SimpleCallSettings.Builder
+ annotateTextSettings() {
+ return annotateTextSettings;
+ }
+
+ @Override
+ public LanguageServiceSettings build() throws IOException {
+ return new LanguageServiceSettings(this);
+ }
+ }
+}
diff --git a/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta2/package-info.java b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta2/package-info.java
new file mode 100644
index 000000000000..39e9f44eb781
--- /dev/null
+++ b/google-cloud-language/src/main/java/com/google/cloud/language/spi/v1beta2/package-info.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2017, Google Inc. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * A client to Google Cloud Natural Language API.
+ *
+ * The interfaces provided are listed below, along with usage samples.
+ *
+ *
===================== LanguageServiceClient =====================
+ *
+ *
Service Description: Provides text analysis operations such as sentiment analysis and entity
+ * recognition.
+ *
+ *
Sample for LanguageServiceClient:
+ *
+ *
+ *
+ * try (LanguageServiceClient languageServiceClient = LanguageServiceClient.create()) {
+ * Document document = Document.newBuilder().build();
+ * AnalyzeSentimentResponse response = languageServiceClient.analyzeSentiment(document);
+ * }
+ *
+ *
+ */
+package com.google.cloud.language.spi.v1beta2;
diff --git a/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1/LanguageServiceClientTest.java b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1/LanguageServiceClientTest.java
index 8fadd45dc42f..3d7fe8efa52d 100644
--- a/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1/LanguageServiceClientTest.java
+++ b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1/LanguageServiceClientTest.java
@@ -99,7 +99,7 @@ public void analyzeSentimentTest() {
@Test
@SuppressWarnings("all")
public void analyzeSentimentExceptionTest() throws Exception {
- StatusRuntimeException exception = new StatusRuntimeException(Status.INTERNAL);
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockLanguageService.addException(exception);
try {
@@ -108,7 +108,7 @@ public void analyzeSentimentExceptionTest() throws Exception {
client.analyzeSentiment(document);
Assert.fail("No exception raised");
} catch (ApiException e) {
- Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
}
}
@@ -137,7 +137,7 @@ public void analyzeEntitiesTest() {
@Test
@SuppressWarnings("all")
public void analyzeEntitiesExceptionTest() throws Exception {
- StatusRuntimeException exception = new StatusRuntimeException(Status.INTERNAL);
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockLanguageService.addException(exception);
try {
@@ -147,7 +147,7 @@ public void analyzeEntitiesExceptionTest() throws Exception {
client.analyzeEntities(document, encodingType);
Assert.fail("No exception raised");
} catch (ApiException e) {
- Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
}
}
@@ -176,7 +176,7 @@ public void analyzeSyntaxTest() {
@Test
@SuppressWarnings("all")
public void analyzeSyntaxExceptionTest() throws Exception {
- StatusRuntimeException exception = new StatusRuntimeException(Status.INTERNAL);
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockLanguageService.addException(exception);
try {
@@ -186,7 +186,7 @@ public void analyzeSyntaxExceptionTest() throws Exception {
client.analyzeSyntax(document, encodingType);
Assert.fail("No exception raised");
} catch (ApiException e) {
- Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
}
}
@@ -217,7 +217,7 @@ public void annotateTextTest() {
@Test
@SuppressWarnings("all")
public void annotateTextExceptionTest() throws Exception {
- StatusRuntimeException exception = new StatusRuntimeException(Status.INTERNAL);
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
mockLanguageService.addException(exception);
try {
@@ -228,7 +228,7 @@ public void annotateTextExceptionTest() throws Exception {
client.annotateText(document, features, encodingType);
Assert.fail("No exception raised");
} catch (ApiException e) {
- Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
}
}
}
diff --git a/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta2/LanguageServiceClientTest.java b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta2/LanguageServiceClientTest.java
new file mode 100644
index 000000000000..b0c4c5969c4b
--- /dev/null
+++ b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta2/LanguageServiceClientTest.java
@@ -0,0 +1,277 @@
+/*
+ * Copyright 2017, 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.v1beta2;
+
+import com.google.api.gax.grpc.ApiException;
+import com.google.api.gax.testing.MockGrpcService;
+import com.google.api.gax.testing.MockServiceHelper;
+import com.google.cloud.language.v1beta2.AnalyzeEntitiesRequest;
+import com.google.cloud.language.v1beta2.AnalyzeEntitiesResponse;
+import com.google.cloud.language.v1beta2.AnalyzeEntitySentimentRequest;
+import com.google.cloud.language.v1beta2.AnalyzeEntitySentimentResponse;
+import com.google.cloud.language.v1beta2.AnalyzeSentimentRequest;
+import com.google.cloud.language.v1beta2.AnalyzeSentimentResponse;
+import com.google.cloud.language.v1beta2.AnalyzeSyntaxRequest;
+import com.google.cloud.language.v1beta2.AnalyzeSyntaxResponse;
+import com.google.cloud.language.v1beta2.AnnotateTextRequest;
+import com.google.cloud.language.v1beta2.AnnotateTextRequest.Features;
+import com.google.cloud.language.v1beta2.AnnotateTextResponse;
+import com.google.cloud.language.v1beta2.Document;
+import com.google.cloud.language.v1beta2.EncodingType;
+import com.google.protobuf.GeneratedMessageV3;
+import io.grpc.Status;
+import io.grpc.StatusRuntimeException;
+import java.io.IOException;
+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 LanguageServiceClientTest {
+ private static MockLanguageService mockLanguageService;
+ private static MockServiceHelper serviceHelper;
+ private LanguageServiceClient client;
+
+ @BeforeClass
+ public static void startStaticServer() {
+ mockLanguageService = new MockLanguageService();
+ serviceHelper =
+ new MockServiceHelper("in-process-1", Arrays.asList(mockLanguageService));
+ serviceHelper.start();
+ }
+
+ @AfterClass
+ public static void stopServer() {
+ serviceHelper.stop();
+ }
+
+ @Before
+ public void setUp() throws IOException {
+ serviceHelper.reset();
+ LanguageServiceSettings settings =
+ LanguageServiceSettings.defaultBuilder()
+ .setChannelProvider(serviceHelper.createChannelProvider())
+ .build();
+ client = LanguageServiceClient.create(settings);
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ client.close();
+ }
+
+ @Test
+ @SuppressWarnings("all")
+ public void analyzeSentimentTest() {
+ String language = "language-1613589672";
+ AnalyzeSentimentResponse expectedResponse =
+ AnalyzeSentimentResponse.newBuilder().setLanguage(language).build();
+ mockLanguageService.addResponse(expectedResponse);
+
+ Document document = Document.newBuilder().build();
+
+ AnalyzeSentimentResponse actualResponse = client.analyzeSentiment(document);
+ Assert.assertEquals(expectedResponse, actualResponse);
+
+ List actualRequests = mockLanguageService.getRequests();
+ Assert.assertEquals(1, actualRequests.size());
+ AnalyzeSentimentRequest actualRequest = (AnalyzeSentimentRequest) actualRequests.get(0);
+
+ Assert.assertEquals(document, actualRequest.getDocument());
+ }
+
+ @Test
+ @SuppressWarnings("all")
+ public void analyzeSentimentExceptionTest() throws Exception {
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
+ mockLanguageService.addException(exception);
+
+ try {
+ Document document = Document.newBuilder().build();
+
+ client.analyzeSentiment(document);
+ Assert.fail("No exception raised");
+ } catch (ApiException e) {
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
+ }
+ }
+
+ @Test
+ @SuppressWarnings("all")
+ public void analyzeEntitiesTest() {
+ String language = "language-1613589672";
+ AnalyzeEntitiesResponse expectedResponse =
+ AnalyzeEntitiesResponse.newBuilder().setLanguage(language).build();
+ mockLanguageService.addResponse(expectedResponse);
+
+ Document document = Document.newBuilder().build();
+ EncodingType encodingType = EncodingType.NONE;
+
+ AnalyzeEntitiesResponse actualResponse = client.analyzeEntities(document, encodingType);
+ Assert.assertEquals(expectedResponse, actualResponse);
+
+ List actualRequests = mockLanguageService.getRequests();
+ Assert.assertEquals(1, actualRequests.size());
+ AnalyzeEntitiesRequest actualRequest = (AnalyzeEntitiesRequest) actualRequests.get(0);
+
+ Assert.assertEquals(document, actualRequest.getDocument());
+ Assert.assertEquals(encodingType, actualRequest.getEncodingType());
+ }
+
+ @Test
+ @SuppressWarnings("all")
+ public void analyzeEntitiesExceptionTest() throws Exception {
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
+ mockLanguageService.addException(exception);
+
+ try {
+ Document document = Document.newBuilder().build();
+ EncodingType encodingType = EncodingType.NONE;
+
+ client.analyzeEntities(document, encodingType);
+ Assert.fail("No exception raised");
+ } catch (ApiException e) {
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
+ }
+ }
+
+ @Test
+ @SuppressWarnings("all")
+ public void analyzeEntitySentimentTest() {
+ String language = "language-1613589672";
+ AnalyzeEntitySentimentResponse expectedResponse =
+ AnalyzeEntitySentimentResponse.newBuilder().setLanguage(language).build();
+ mockLanguageService.addResponse(expectedResponse);
+
+ Document document = Document.newBuilder().build();
+ EncodingType encodingType = EncodingType.NONE;
+
+ AnalyzeEntitySentimentResponse actualResponse =
+ client.analyzeEntitySentiment(document, encodingType);
+ Assert.assertEquals(expectedResponse, actualResponse);
+
+ List actualRequests = mockLanguageService.getRequests();
+ Assert.assertEquals(1, actualRequests.size());
+ AnalyzeEntitySentimentRequest actualRequest =
+ (AnalyzeEntitySentimentRequest) actualRequests.get(0);
+
+ Assert.assertEquals(document, actualRequest.getDocument());
+ Assert.assertEquals(encodingType, actualRequest.getEncodingType());
+ }
+
+ @Test
+ @SuppressWarnings("all")
+ public void analyzeEntitySentimentExceptionTest() throws Exception {
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
+ mockLanguageService.addException(exception);
+
+ try {
+ Document document = Document.newBuilder().build();
+ EncodingType encodingType = EncodingType.NONE;
+
+ client.analyzeEntitySentiment(document, encodingType);
+ Assert.fail("No exception raised");
+ } catch (ApiException e) {
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
+ }
+ }
+
+ @Test
+ @SuppressWarnings("all")
+ public void analyzeSyntaxTest() {
+ String language = "language-1613589672";
+ AnalyzeSyntaxResponse expectedResponse =
+ AnalyzeSyntaxResponse.newBuilder().setLanguage(language).build();
+ mockLanguageService.addResponse(expectedResponse);
+
+ Document document = Document.newBuilder().build();
+ EncodingType encodingType = EncodingType.NONE;
+
+ AnalyzeSyntaxResponse actualResponse = client.analyzeSyntax(document, encodingType);
+ Assert.assertEquals(expectedResponse, actualResponse);
+
+ List actualRequests = mockLanguageService.getRequests();
+ Assert.assertEquals(1, actualRequests.size());
+ AnalyzeSyntaxRequest actualRequest = (AnalyzeSyntaxRequest) actualRequests.get(0);
+
+ Assert.assertEquals(document, actualRequest.getDocument());
+ Assert.assertEquals(encodingType, actualRequest.getEncodingType());
+ }
+
+ @Test
+ @SuppressWarnings("all")
+ public void analyzeSyntaxExceptionTest() throws Exception {
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
+ mockLanguageService.addException(exception);
+
+ try {
+ Document document = Document.newBuilder().build();
+ EncodingType encodingType = EncodingType.NONE;
+
+ client.analyzeSyntax(document, encodingType);
+ Assert.fail("No exception raised");
+ } catch (ApiException e) {
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
+ }
+ }
+
+ @Test
+ @SuppressWarnings("all")
+ public void annotateTextTest() {
+ String language = "language-1613589672";
+ AnnotateTextResponse expectedResponse =
+ AnnotateTextResponse.newBuilder().setLanguage(language).build();
+ mockLanguageService.addResponse(expectedResponse);
+
+ Document document = Document.newBuilder().build();
+ AnnotateTextRequest.Features features = AnnotateTextRequest.Features.newBuilder().build();
+ EncodingType encodingType = EncodingType.NONE;
+
+ AnnotateTextResponse actualResponse = client.annotateText(document, features, encodingType);
+ Assert.assertEquals(expectedResponse, actualResponse);
+
+ List actualRequests = mockLanguageService.getRequests();
+ Assert.assertEquals(1, actualRequests.size());
+ AnnotateTextRequest actualRequest = (AnnotateTextRequest) actualRequests.get(0);
+
+ Assert.assertEquals(document, actualRequest.getDocument());
+ Assert.assertEquals(features, actualRequest.getFeatures());
+ Assert.assertEquals(encodingType, actualRequest.getEncodingType());
+ }
+
+ @Test
+ @SuppressWarnings("all")
+ public void annotateTextExceptionTest() throws Exception {
+ StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT);
+ mockLanguageService.addException(exception);
+
+ try {
+ Document document = Document.newBuilder().build();
+ AnnotateTextRequest.Features features = AnnotateTextRequest.Features.newBuilder().build();
+ EncodingType encodingType = EncodingType.NONE;
+
+ client.annotateText(document, features, encodingType);
+ Assert.fail("No exception raised");
+ } catch (ApiException e) {
+ Assert.assertEquals(Status.INVALID_ARGUMENT.getCode(), e.getStatusCode());
+ }
+ }
+}
diff --git a/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta2/MockLanguageService.java b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta2/MockLanguageService.java
new file mode 100644
index 000000000000..21146ba5d120
--- /dev/null
+++ b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta2/MockLanguageService.java
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2017, 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.v1beta2;
+
+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 MockLanguageService implements MockGrpcService {
+ private final MockLanguageServiceImpl serviceImpl;
+
+ public MockLanguageService() {
+ serviceImpl = new MockLanguageServiceImpl();
+ }
+
+ @Override
+ public List getRequests() {
+ return serviceImpl.getRequests();
+ }
+
+ @Override
+ public void addResponse(GeneratedMessageV3 response) {
+ serviceImpl.addResponse(response);
+ }
+
+ @Override
+ public void addException(Exception exception) {
+ serviceImpl.addException(exception);
+ }
+
+ 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-language/src/test/java/com/google/cloud/language/spi/v1beta2/MockLanguageServiceImpl.java b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta2/MockLanguageServiceImpl.java
new file mode 100644
index 000000000000..766c4bb5f53b
--- /dev/null
+++ b/google-cloud-language/src/test/java/com/google/cloud/language/spi/v1beta2/MockLanguageServiceImpl.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright 2017, 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.v1beta2;
+
+import com.google.cloud.language.v1beta2.AnalyzeEntitiesRequest;
+import com.google.cloud.language.v1beta2.AnalyzeEntitiesResponse;
+import com.google.cloud.language.v1beta2.AnalyzeEntitySentimentRequest;
+import com.google.cloud.language.v1beta2.AnalyzeEntitySentimentResponse;
+import com.google.cloud.language.v1beta2.AnalyzeSentimentRequest;
+import com.google.cloud.language.v1beta2.AnalyzeSentimentResponse;
+import com.google.cloud.language.v1beta2.AnalyzeSyntaxRequest;
+import com.google.cloud.language.v1beta2.AnalyzeSyntaxResponse;
+import com.google.cloud.language.v1beta2.AnnotateTextRequest;
+import com.google.cloud.language.v1beta2.AnnotateTextResponse;
+import com.google.cloud.language.v1beta2.LanguageServiceGrpc.LanguageServiceImplBase;
+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 MockLanguageServiceImpl extends LanguageServiceImplBase {
+ private ArrayList requests;
+ private Queue responses;
+
+ public MockLanguageServiceImpl() {
+ requests = new ArrayList<>();
+ responses = new LinkedList<>();
+ }
+
+ public List getRequests() {
+ return requests;
+ }
+
+ public void addResponse(GeneratedMessageV3 response) {
+ responses.add(response);
+ }
+
+ public void setResponses(List responses) {
+ this.responses = new LinkedList(responses);
+ }
+
+ public void addException(Exception exception) {
+ responses.add(exception);
+ }
+
+ public void reset() {
+ requests = new ArrayList<>();
+ responses = new LinkedList<>();
+ }
+
+ @Override
+ public void analyzeSentiment(
+ AnalyzeSentimentRequest request, StreamObserver responseObserver) {
+ Object response = responses.remove();
+ if (response instanceof AnalyzeSentimentResponse) {
+ requests.add(request);
+ responseObserver.onNext((AnalyzeSentimentResponse) response);
+ responseObserver.onCompleted();
+ } else if (response instanceof Exception) {
+ responseObserver.onError((Exception) response);
+ } else {
+ responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
+ }
+ }
+
+ @Override
+ public void analyzeEntities(
+ AnalyzeEntitiesRequest request, StreamObserver responseObserver) {
+ Object response = responses.remove();
+ if (response instanceof AnalyzeEntitiesResponse) {
+ requests.add(request);
+ responseObserver.onNext((AnalyzeEntitiesResponse) response);
+ responseObserver.onCompleted();
+ } else if (response instanceof Exception) {
+ responseObserver.onError((Exception) response);
+ } else {
+ responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
+ }
+ }
+
+ @Override
+ public void analyzeEntitySentiment(
+ AnalyzeEntitySentimentRequest request,
+ StreamObserver responseObserver) {
+ Object response = responses.remove();
+ if (response instanceof AnalyzeEntitySentimentResponse) {
+ requests.add(request);
+ responseObserver.onNext((AnalyzeEntitySentimentResponse) response);
+ responseObserver.onCompleted();
+ } else if (response instanceof Exception) {
+ responseObserver.onError((Exception) response);
+ } else {
+ responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
+ }
+ }
+
+ @Override
+ public void analyzeSyntax(
+ AnalyzeSyntaxRequest request, StreamObserver responseObserver) {
+ Object response = responses.remove();
+ if (response instanceof AnalyzeSyntaxResponse) {
+ requests.add(request);
+ responseObserver.onNext((AnalyzeSyntaxResponse) response);
+ responseObserver.onCompleted();
+ } else if (response instanceof Exception) {
+ responseObserver.onError((Exception) response);
+ } else {
+ responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
+ }
+ }
+
+ @Override
+ public void annotateText(
+ AnnotateTextRequest request, StreamObserver responseObserver) {
+ Object response = responses.remove();
+ if (response instanceof AnnotateTextResponse) {
+ requests.add(request);
+ responseObserver.onNext((AnnotateTextResponse) response);
+ responseObserver.onCompleted();
+ } else if (response instanceof Exception) {
+ responseObserver.onError((Exception) response);
+ } else {
+ responseObserver.onError(new IllegalArgumentException("Unrecognized response type"));
+ }
+ }
+}
diff --git a/google-cloud-logging/README.md b/google-cloud-logging/README.md
index 9846fed5994b..c4f8a42dd84b 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.10.0-beta
+ 0.12.0-beta
```
If you are using Gradle, add this to your dependencies
```Groovy
-compile 'com.google.cloud:google-cloud-logging:0.10.0-beta'
+compile 'com.google.cloud:google-cloud-logging:0.12.0-beta'
```
If you are using SBT, add this to your dependencies
```Scala
-libraryDependencies += "com.google.cloud" % "google-cloud-logging" % "0.10.0-beta"
+libraryDependencies += "com.google.cloud" % "google-cloud-logging" % "0.12.0-beta"
```
Example Application
diff --git a/google-cloud-logging/pom.xml b/google-cloud-logging/pom.xml
index e81b0222cdb3..6e1a85e84e1f 100644
--- a/google-cloud-logging/pom.xml
+++ b/google-cloud-logging/pom.xml
@@ -12,10 +12,11 @@
com.google.cloud
google-cloud-pom
- 0.10.1-alpha-SNAPSHOT
+ 0.12.1-alpha-SNAPSHOT
google-cloud-logging
+ ${project.version}
@@ -88,6 +89,22 @@
+
+ org.codehaus.mojo
+ properties-maven-plugin
+ 1.0-alpha-2
+
+
+ generate-resources
+
+ write-project-properties
+
+
+ ${project.build.outputDirectory}/project.properties
+
+
+
+
org.codehaus.mojo
build-helper-maven-plugin
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 d82b68db74f3..1474640b5bba 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
@@ -18,16 +18,19 @@
import static com.google.common.base.MoreObjects.firstNonNull;
+import com.google.api.gax.core.ApiFuture;
+import com.google.api.gax.core.ApiFutureCallback;
+import com.google.api.gax.core.ApiFutures;
import com.google.cloud.MonitoredResource;
import com.google.cloud.logging.Logging.WriteOption;
-import com.google.api.gax.core.ApiFutures;
-import com.google.api.gax.core.ApiFutureCallback;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.Uninterruptibles;
import java.util.ArrayList;
import java.util.Collections;
-import java.util.LinkedList;
+import java.util.IdentityHashMap;
import java.util.List;
+import java.util.Set;
import java.util.logging.ErrorManager;
import java.util.logging.Filter;
import java.util.logging.Formatter;
@@ -120,6 +123,10 @@ public class LoggingHandler extends Handler {
// https://github.com/GoogleCloudPlatform/google-cloud-java/issues/1740 .
private final Level baseLevel;
+ private final Object writeLock = new Object();
+ private final Set> pendingWrites =
+ Collections.newSetFromMap(new IdentityHashMap, Boolean>());
+
/**
* Creates an handler that publishes messages to Stackdriver Logging.
*/
@@ -376,6 +383,9 @@ public void publish(LogRecord record) {
if (entry != null) {
write(entry, writeOptions);
}
+ if (record.getLevel().intValue() >= flushLevel.intValue()) {
+ flush();
+ }
} finally {
inPublishCall.remove();
}
@@ -457,28 +467,60 @@ void write(LogEntry entry, WriteOption... options) {
reportError(null, ex, ErrorManager.FLUSH_FAILURE);
}
break;
+
case ASYNC:
default:
- ApiFutures.addCallback(getLogging().writeAsync(entryList, options), new ApiFutureCallback() {
- @Override
- public void onSuccess(Void v) {}
-
- @Override
- public void onFailure(Throwable t) {
- if (t instanceof Exception) {
- reportError(null, (Exception) t, ErrorManager.FLUSH_FAILURE);
- } else {
- reportError(null, new Exception(t), ErrorManager.FLUSH_FAILURE);
- }
- }
- });
+ final ApiFuture writeFuture = getLogging().writeAsync(entryList, options);
+ synchronized(writeLock) {
+ pendingWrites.add(writeFuture);
+ }
+ ApiFutures.addCallback(
+ writeFuture,
+ new ApiFutureCallback() {
+ private void removeFromPending() {
+ synchronized(writeLock) {
+ pendingWrites.remove(writeFuture);
+ }
+ }
+
+ @Override
+ public void onSuccess(Void v) {
+ removeFromPending();
+ }
+
+ @Override
+ public void onFailure(Throwable t) {
+ try {
+ if (t instanceof Exception) {
+ reportError(null, (Exception) t, ErrorManager.FLUSH_FAILURE);
+ } else {
+ reportError(null, new Exception(t), ErrorManager.FLUSH_FAILURE);
+ }
+ } finally {
+ removeFromPending();
+ }
+ }
+ });
break;
}
}
@Override
public void flush() {
- // BUG(1795): flush is broken, need support from batching implementation.
+ // BUG(1795): We should force batcher to issue RPC call for buffered messages,
+ // so the code below doesn't wait uselessly.
+
+ ArrayList> writesToFlush = new ArrayList<>();
+ synchronized(writeLock) {
+ writesToFlush.addAll(pendingWrites);
+ }
+ for (ApiFuture write : writesToFlush) {
+ try {
+ Uninterruptibles.getUninterruptibly(write);
+ } catch (Exception e) {
+ // Ignore exceptions, they are propagated to the error manager.
+ }
+ }
}
/**
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 65998d5b0813..feb7cdcacac7 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
@@ -34,8 +34,7 @@ public class LoggingOptions extends ServiceOptions {
private static final String API_SHORT_NAME = "Logging";
private static final String LOGGING_SCOPE = "https://www.googleapis.com/auth/logging.admin";
private static final Set SCOPES = ImmutableSet.of(LOGGING_SCOPE);
- private static final String DEFAULT_HOST = LoggingSettings.getDefaultServiceAddress()
- + ':' + LoggingSettings.getDefaultServicePort();
+ private static final String DEFAULT_HOST = LoggingSettings.getDefaultEndpoint();
private static final long serialVersionUID = 5753499510627426717L;
public static class DefaultLoggingFactory implements LoggingFactory {
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigClient.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigClient.java
index 4ca4168a1d0c..f188dbc88692 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigClient.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigClient.java
@@ -29,6 +29,7 @@
import com.google.logging.v2.SinkNameOneof;
import com.google.logging.v2.UpdateSinkRequest;
import com.google.protobuf.Empty;
+import com.google.protobuf.ExperimentalApi;
import io.grpc.ManagedChannel;
import java.io.Closeable;
import java.io.IOException;
@@ -94,6 +95,7 @@
*
*/
@Generated("by GAPIC")
+@ExperimentalApi
public class ConfigClient implements AutoCloseable {
private final ConfigSettings settings;
private final ScheduledExecutorService executor;
diff --git a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigSettings.java b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigSettings.java
index af3840601c0d..72fc086723ec 100644
--- a/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigSettings.java
+++ b/google-cloud-logging/src/main/java/com/google/cloud/logging/spi/v2/ConfigSettings.java
@@ -18,6 +18,7 @@
import static com.google.cloud.logging.spi.v2.PagedResponseWrappers.ListSinksPagedResponse;
import com.google.api.gax.core.GoogleCredentialsProvider;
+import com.google.api.gax.core.PropertiesProvider;
import com.google.api.gax.core.RetrySettings;
import com.google.api.gax.grpc.CallContext;
import com.google.api.gax.grpc.ChannelProvider;
@@ -80,12 +81,6 @@
@Generated("by GAPIC v0.0.5")
@ExperimentalApi
public class ConfigSettings extends ClientSettings {
- /** The default address of the service. */
- private static final String DEFAULT_SERVICE_ADDRESS = "logging.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()
@@ -99,6 +94,11 @@ public class ConfigSettings extends ClientSettings {
private static final String DEFAULT_GAPIC_NAME = "gapic";
private static final String DEFAULT_GAPIC_VERSION = "";
+ private static final String PROPERTIES_FILE = "/project.properties";
+ private static final String META_VERSION_KEY = "artifact.version";
+
+ private static String gapicVersion;
+
private final PagedCallSettings