*
* try (ErrorGroupServiceClient errorGroupServiceClient = ErrorGroupServiceClient.create()) {
- * String formattedGroupName = ErrorGroupServiceClient.formatGroupName("[PROJECT]", "[GROUP]");
- * ErrorGroup response = errorGroupServiceClient.getGroup(formattedGroupName);
+ * GroupName groupName = GroupName.create("[PROJECT]", "[GROUP]");
+ * ErrorGroup response = errorGroupServiceClient.getGroup(groupName);
* }
*
*
@@ -97,26 +97,6 @@ public class ErrorGroupServiceClient implements AutoCloseable {
private final UnaryCallable
* try (ErrorGroupServiceClient errorGroupServiceClient = ErrorGroupServiceClient.create()) {
- * String formattedGroupName = ErrorGroupServiceClient.formatGroupName("[PROJECT]", "[GROUP]");
- * ErrorGroup response = errorGroupServiceClient.getGroup(formattedGroupName);
+ * GroupName groupName = GroupName.create("[PROJECT]", "[GROUP]");
+ * ErrorGroup response = errorGroupServiceClient.getGroup(groupName);
* }
*
*
@@ -192,9 +172,10 @@ public final ErrorGroupServiceSettings getSettings() {
* Example: <code>projects/my-project-123/groups/my-group</code> * @throws com.google.api.gax.grpc.ApiException if the remote call fails */ - public final ErrorGroup getGroup(String groupName) { - GROUP_PATH_TEMPLATE.validate(groupName, "getGroup"); - GetGroupRequest request = GetGroupRequest.newBuilder().setGroupName(groupName).build(); + public final ErrorGroup getGroup(GroupName groupName) { + + GetGroupRequest request = + GetGroupRequest.newBuilder().setGroupNameWithGroupName(groupName).build(); return getGroup(request); } @@ -206,9 +187,9 @@ public final ErrorGroup getGroup(String groupName) { * *
* try (ErrorGroupServiceClient errorGroupServiceClient = ErrorGroupServiceClient.create()) {
- * String formattedGroupName = ErrorGroupServiceClient.formatGroupName("[PROJECT]", "[GROUP]");
+ * GroupName groupName = GroupName.create("[PROJECT]", "[GROUP]");
* GetGroupRequest request = GetGroupRequest.newBuilder()
- * .setGroupName(formattedGroupName)
+ * .setGroupNameWithGroupName(groupName)
* .build();
* ErrorGroup response = errorGroupServiceClient.getGroup(request);
* }
@@ -229,9 +210,9 @@ private final ErrorGroup getGroup(GetGroupRequest request) {
*
*
* try (ErrorGroupServiceClient errorGroupServiceClient = ErrorGroupServiceClient.create()) {
- * String formattedGroupName = ErrorGroupServiceClient.formatGroupName("[PROJECT]", "[GROUP]");
+ * GroupName groupName = GroupName.create("[PROJECT]", "[GROUP]");
* GetGroupRequest request = GetGroupRequest.newBuilder()
- * .setGroupName(formattedGroupName)
+ * .setGroupNameWithGroupName(groupName)
* .build();
* ListenableFuture<ErrorGroup> future = errorGroupServiceClient.getGroupCallable().futureCall(request);
* // Do something
diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceClient.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceClient.java
index a612ae883eb7..4a53ccaf92bb 100644
--- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceClient.java
+++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceClient.java
@@ -20,13 +20,13 @@
import com.google.api.gax.grpc.ChannelAndExecutor;
import com.google.api.gax.grpc.UnaryCallable;
-import com.google.api.gax.protobuf.PathTemplate;
import com.google.devtools.clouderrorreporting.v1beta1.DeleteEventsRequest;
import com.google.devtools.clouderrorreporting.v1beta1.DeleteEventsResponse;
import com.google.devtools.clouderrorreporting.v1beta1.ListEventsRequest;
import com.google.devtools.clouderrorreporting.v1beta1.ListEventsResponse;
import com.google.devtools.clouderrorreporting.v1beta1.ListGroupStatsRequest;
import com.google.devtools.clouderrorreporting.v1beta1.ListGroupStatsResponse;
+import com.google.devtools.clouderrorreporting.v1beta1.ProjectName;
import com.google.devtools.clouderrorreporting.v1beta1.QueryTimeRange;
import com.google.protobuf.ExperimentalApi;
import io.grpc.ManagedChannel;
@@ -48,8 +48,8 @@
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
- * DeleteEventsResponse response = errorStatsServiceClient.deleteEvents(formattedProjectName);
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
+ * DeleteEventsResponse response = errorStatsServiceClient.deleteEvents(projectName);
* }
*
*
@@ -109,19 +109,6 @@ public class ErrorStatsServiceClient implements AutoCloseable {
private final UnaryCallable listEventsPagedCallable;
private final UnaryCallable deleteEventsCallable;
- private static final PathTemplate PROJECT_PATH_TEMPLATE =
- PathTemplate.createWithoutUrlEncoding("projects/{project}");
-
- /** Formats a string containing the fully-qualified path to represent a project resource. */
- public static final String formatProjectName(String project) {
- return PROJECT_PATH_TEMPLATE.instantiate("project", project);
- }
-
- /** Parses the project from the given fully-qualified path which represents a project resource. */
- public static final String parseProjectFromProjectName(String projectName) {
- return PROJECT_PATH_TEMPLATE.parse(projectName).get("project");
- }
-
/** Constructs an instance of ErrorStatsServiceClient with default settings. */
public static final ErrorStatsServiceClient create() throws IOException {
return create(ErrorStatsServiceSettings.defaultBuilder().build());
@@ -192,9 +179,9 @@ public final ErrorStatsServiceSettings getSettings() {
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* QueryTimeRange timeRange = QueryTimeRange.newBuilder().build();
- * for (ErrorGroupStats element : errorStatsServiceClient.listGroupStats(formattedProjectName, timeRange).iterateAllElements()) {
+ * for (ErrorGroupStats element : errorStatsServiceClient.listGroupStats(projectName, timeRange).iterateAllElements()) {
* // doThingsWith(element);
* }
* }
@@ -205,18 +192,19 @@ public final ErrorStatsServiceSettings getSettings() {
* href="https://support.google.com/cloud/answer/6158840">Google Cloud Platform project
* ID</a>.
* Example: <code>projects/my-project-123</code>.
- * @param timeRange [Required] List data for the given time range. Only
- * <code>ErrorGroupStats</code> with a non-zero count in the given time range are
- * returned, unless the request contains an explicit group_id list. If a group_id list is
- * given, also <code>ErrorGroupStats</code> with zero occurrences are returned.
+ * @param timeRange [Optional] List data for the given time range. If not set a default time range
+ * is used. The field time_range_begin in the response will specify the beginning of this time
+ * range. Only <code>ErrorGroupStats</code> with a non-zero count in the given
+ * time range are returned, unless the request contains an explicit group_id list. If a
+ * group_id list is given, also <code>ErrorGroupStats</code> with zero occurrences
+ * are returned.
* @throws com.google.api.gax.grpc.ApiException if the remote call fails
*/
public final ListGroupStatsPagedResponse listGroupStats(
- String projectName, QueryTimeRange timeRange) {
- PROJECT_PATH_TEMPLATE.validate(projectName, "listGroupStats");
+ ProjectName projectName, QueryTimeRange timeRange) {
ListGroupStatsRequest request =
ListGroupStatsRequest.newBuilder()
- .setProjectName(projectName)
+ .setProjectNameWithProjectName(projectName)
.setTimeRange(timeRange)
.build();
return listGroupStats(request);
@@ -230,10 +218,10 @@ public final ListGroupStatsPagedResponse listGroupStats(
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* QueryTimeRange timeRange = QueryTimeRange.newBuilder().build();
* ListGroupStatsRequest request = ListGroupStatsRequest.newBuilder()
- * .setProjectName(formattedProjectName)
+ * .setProjectNameWithProjectName(projectName)
* .setTimeRange(timeRange)
* .build();
* for (ErrorGroupStats element : errorStatsServiceClient.listGroupStats(request).iterateAllElements()) {
@@ -257,10 +245,10 @@ public final ListGroupStatsPagedResponse listGroupStats(ListGroupStatsRequest re
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* QueryTimeRange timeRange = QueryTimeRange.newBuilder().build();
* ListGroupStatsRequest request = ListGroupStatsRequest.newBuilder()
- * .setProjectName(formattedProjectName)
+ * .setProjectNameWithProjectName(projectName)
* .setTimeRange(timeRange)
* .build();
* ListenableFuture<ListGroupStatsPagedResponse> future = errorStatsServiceClient.listGroupStatsPagedCallable().futureCall(request);
@@ -284,10 +272,10 @@ public final ListGroupStatsPagedResponse listGroupStats(ListGroupStatsRequest re
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* QueryTimeRange timeRange = QueryTimeRange.newBuilder().build();
* ListGroupStatsRequest request = ListGroupStatsRequest.newBuilder()
- * .setProjectName(formattedProjectName)
+ * .setProjectNameWithProjectName(projectName)
* .setTimeRange(timeRange)
* .build();
* while (true) {
@@ -318,9 +306,9 @@ public final ListGroupStatsPagedResponse listGroupStats(ListGroupStatsRequest re
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* String groupId = "";
- * for (ErrorEvent element : errorStatsServiceClient.listEvents(formattedProjectName, groupId).iterateAllElements()) {
+ * for (ErrorEvent element : errorStatsServiceClient.listEvents(projectName, groupId).iterateAllElements()) {
* // doThingsWith(element);
* }
* }
@@ -332,10 +320,12 @@ public final ListGroupStatsPagedResponse listGroupStats(ListGroupStatsRequest re
* @param groupId [Required] The group for which events shall be returned.
* @throws com.google.api.gax.grpc.ApiException if the remote call fails
*/
- public final ListEventsPagedResponse listEvents(String projectName, String groupId) {
- PROJECT_PATH_TEMPLATE.validate(projectName, "listEvents");
+ public final ListEventsPagedResponse listEvents(ProjectName projectName, String groupId) {
ListEventsRequest request =
- ListEventsRequest.newBuilder().setProjectName(projectName).setGroupId(groupId).build();
+ ListEventsRequest.newBuilder()
+ .setProjectNameWithProjectName(projectName)
+ .setGroupId(groupId)
+ .build();
return listEvents(request);
}
@@ -347,10 +337,10 @@ public final ListEventsPagedResponse listEvents(String projectName, String group
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* String groupId = "";
* ListEventsRequest request = ListEventsRequest.newBuilder()
- * .setProjectName(formattedProjectName)
+ * .setProjectNameWithProjectName(projectName)
* .setGroupId(groupId)
* .build();
* for (ErrorEvent element : errorStatsServiceClient.listEvents(request).iterateAllElements()) {
@@ -374,10 +364,10 @@ public final ListEventsPagedResponse listEvents(ListEventsRequest request) {
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* String groupId = "";
* ListEventsRequest request = ListEventsRequest.newBuilder()
- * .setProjectName(formattedProjectName)
+ * .setProjectNameWithProjectName(projectName)
* .setGroupId(groupId)
* .build();
* ListenableFuture<ListEventsPagedResponse> future = errorStatsServiceClient.listEventsPagedCallable().futureCall(request);
@@ -400,10 +390,10 @@ public final UnaryCallable listEvent
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* String groupId = "";
* ListEventsRequest request = ListEventsRequest.newBuilder()
- * .setProjectName(formattedProjectName)
+ * .setProjectNameWithProjectName(projectName)
* .setGroupId(groupId)
* .build();
* while (true) {
@@ -433,8 +423,8 @@ public final UnaryCallable listEventsCall
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
- * DeleteEventsResponse response = errorStatsServiceClient.deleteEvents(formattedProjectName);
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
+ * DeleteEventsResponse response = errorStatsServiceClient.deleteEvents(projectName);
* }
*
*
@@ -443,10 +433,10 @@ public final UnaryCallable listEventsCall
* ID](https://support.google.com/cloud/answer/6158840). Example: `projects/my-project-123`.
* @throws com.google.api.gax.grpc.ApiException if the remote call fails
*/
- public final DeleteEventsResponse deleteEvents(String projectName) {
- PROJECT_PATH_TEMPLATE.validate(projectName, "deleteEvents");
+ public final DeleteEventsResponse deleteEvents(ProjectName projectName) {
+
DeleteEventsRequest request =
- DeleteEventsRequest.newBuilder().setProjectName(projectName).build();
+ DeleteEventsRequest.newBuilder().setProjectNameWithProjectName(projectName).build();
return deleteEvents(request);
}
@@ -458,9 +448,9 @@ public final DeleteEventsResponse deleteEvents(String projectName) {
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* DeleteEventsRequest request = DeleteEventsRequest.newBuilder()
- * .setProjectName(formattedProjectName)
+ * .setProjectNameWithProjectName(projectName)
* .build();
* DeleteEventsResponse response = errorStatsServiceClient.deleteEvents(request);
* }
@@ -481,9 +471,9 @@ private final DeleteEventsResponse deleteEvents(DeleteEventsRequest request) {
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* DeleteEventsRequest request = DeleteEventsRequest.newBuilder()
- * .setProjectName(formattedProjectName)
+ * .setProjectNameWithProjectName(projectName)
* .build();
* ListenableFuture<DeleteEventsResponse> future = errorStatsServiceClient.deleteEventsCallable().futureCall(request);
* // Do something
diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceClient.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceClient.java
index 65a6ef234b4e..8189c716e86c 100644
--- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceClient.java
+++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceClient.java
@@ -17,7 +17,7 @@
import com.google.api.gax.grpc.ChannelAndExecutor;
import com.google.api.gax.grpc.UnaryCallable;
-import com.google.api.gax.protobuf.PathTemplate;
+import com.google.devtools.clouderrorreporting.v1beta1.ProjectName;
import com.google.devtools.clouderrorreporting.v1beta1.ReportErrorEventRequest;
import com.google.devtools.clouderrorreporting.v1beta1.ReportErrorEventResponse;
import com.google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent;
@@ -40,9 +40,9 @@
*
*
* try (ReportErrorsServiceClient reportErrorsServiceClient = ReportErrorsServiceClient.create()) {
- * String formattedProjectName = ReportErrorsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* ReportedErrorEvent event = ReportedErrorEvent.newBuilder().build();
- * ReportErrorEventResponse response = reportErrorsServiceClient.reportErrorEvent(formattedProjectName, event);
+ * ReportErrorEventResponse response = reportErrorsServiceClient.reportErrorEvent(projectName, event);
* }
*
*
@@ -98,19 +98,6 @@ public class ReportErrorsServiceClient implements AutoCloseable {
private final UnaryCallable
reportErrorEventCallable;
- private static final PathTemplate PROJECT_PATH_TEMPLATE =
- PathTemplate.createWithoutUrlEncoding("projects/{project}");
-
- /** Formats a string containing the fully-qualified path to represent a project resource. */
- public static final String formatProjectName(String project) {
- return PROJECT_PATH_TEMPLATE.instantiate("project", project);
- }
-
- /** Parses the project from the given fully-qualified path which represents a project resource. */
- public static final String parseProjectFromProjectName(String projectName) {
- return PROJECT_PATH_TEMPLATE.parse(projectName).get("project");
- }
-
/** Constructs an instance of ReportErrorsServiceClient with default settings. */
public static final ReportErrorsServiceClient create() throws IOException {
return create(ReportErrorsServiceSettings.defaultBuilder().build());
@@ -178,9 +165,9 @@ public final ReportErrorsServiceSettings getSettings() {
*
*
* try (ReportErrorsServiceClient reportErrorsServiceClient = ReportErrorsServiceClient.create()) {
- * String formattedProjectName = ReportErrorsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* ReportedErrorEvent event = ReportedErrorEvent.newBuilder().build();
- * ReportErrorEventResponse response = reportErrorsServiceClient.reportErrorEvent(formattedProjectName, event);
+ * ReportErrorEventResponse response = reportErrorsServiceClient.reportErrorEvent(projectName, event);
* }
*
*
@@ -191,10 +178,13 @@ public final ReportErrorsServiceSettings getSettings() {
* @throws com.google.api.gax.grpc.ApiException if the remote call fails
*/
public final ReportErrorEventResponse reportErrorEvent(
- String projectName, ReportedErrorEvent event) {
- PROJECT_PATH_TEMPLATE.validate(projectName, "reportErrorEvent");
+ ProjectName projectName, ReportedErrorEvent event) {
+
ReportErrorEventRequest request =
- ReportErrorEventRequest.newBuilder().setProjectName(projectName).setEvent(event).build();
+ ReportErrorEventRequest.newBuilder()
+ .setProjectNameWithProjectName(projectName)
+ .setEvent(event)
+ .build();
return reportErrorEvent(request);
}
@@ -213,10 +203,10 @@ public final ReportErrorEventResponse reportErrorEvent(
*
*
* try (ReportErrorsServiceClient reportErrorsServiceClient = ReportErrorsServiceClient.create()) {
- * String formattedProjectName = ReportErrorsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* ReportedErrorEvent event = ReportedErrorEvent.newBuilder().build();
* ReportErrorEventRequest request = ReportErrorEventRequest.newBuilder()
- * .setProjectName(formattedProjectName)
+ * .setProjectNameWithProjectName(projectName)
* .setEvent(event)
* .build();
* ReportErrorEventResponse response = reportErrorsServiceClient.reportErrorEvent(request);
@@ -245,10 +235,10 @@ public final ReportErrorEventResponse reportErrorEvent(ReportErrorEventRequest r
*
*
* try (ReportErrorsServiceClient reportErrorsServiceClient = ReportErrorsServiceClient.create()) {
- * String formattedProjectName = ReportErrorsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* ReportedErrorEvent event = ReportedErrorEvent.newBuilder().build();
* ReportErrorEventRequest request = ReportErrorEventRequest.newBuilder()
- * .setProjectName(formattedProjectName)
+ * .setProjectNameWithProjectName(projectName)
* .setEvent(event)
* .build();
* ListenableFuture<ReportErrorEventResponse> future = reportErrorsServiceClient.reportErrorEventCallable().futureCall(request);
diff --git a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/package-info.java b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/package-info.java
index 5254c3f2104a..f48abbe98e8d 100644
--- a/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/package-info.java
+++ b/google-cloud-errorreporting/src/main/java/com/google/cloud/errorreporting/spi/v1beta1/package-info.java
@@ -28,8 +28,8 @@
*
*
* try (ErrorGroupServiceClient errorGroupServiceClient = ErrorGroupServiceClient.create()) {
- * String formattedGroupName = ErrorGroupServiceClient.formatGroupName("[PROJECT]", "[GROUP]");
- * ErrorGroup response = errorGroupServiceClient.getGroup(formattedGroupName);
+ * GroupName groupName = GroupName.create("[PROJECT]", "[GROUP]");
+ * ErrorGroup response = errorGroupServiceClient.getGroup(groupName);
* }
*
*
@@ -44,8 +44,8 @@
*
*
* try (ErrorStatsServiceClient errorStatsServiceClient = ErrorStatsServiceClient.create()) {
- * String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
- * DeleteEventsResponse response = errorStatsServiceClient.deleteEvents(formattedProjectName);
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
+ * DeleteEventsResponse response = errorStatsServiceClient.deleteEvents(projectName);
* }
*
*
@@ -59,9 +59,9 @@
*
*
* try (ReportErrorsServiceClient reportErrorsServiceClient = ReportErrorsServiceClient.create()) {
- * String formattedProjectName = ReportErrorsServiceClient.formatProjectName("[PROJECT]");
+ * ProjectName projectName = ProjectName.create("[PROJECT]");
* ReportedErrorEvent event = ReportedErrorEvent.newBuilder().build();
- * ReportErrorEventResponse response = reportErrorsServiceClient.reportErrorEvent(formattedProjectName, event);
+ * ReportErrorEventResponse response = reportErrorsServiceClient.reportErrorEvent(projectName, event);
* }
*
*
diff --git a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceTest.java b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceTest.java
index f58d6313e864..b11c5cb6fd72 100644
--- a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceTest.java
+++ b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorGroupServiceTest.java
@@ -20,6 +20,7 @@
import com.google.api.gax.testing.MockServiceHelper;
import com.google.devtools.clouderrorreporting.v1beta1.ErrorGroup;
import com.google.devtools.clouderrorreporting.v1beta1.GetGroupRequest;
+import com.google.devtools.clouderrorreporting.v1beta1.GroupName;
import com.google.devtools.clouderrorreporting.v1beta1.UpdateGroupRequest;
import com.google.protobuf.GeneratedMessageV3;
import io.grpc.Status;
@@ -78,21 +79,22 @@ public void tearDown() throws Exception {
@Test
@SuppressWarnings("all")
public void getGroupTest() {
- String name = "name3373707";
+ GroupName name = GroupName.create("[PROJECT]", "[GROUP]");
String groupId = "groupId506361563";
- ErrorGroup expectedResponse = ErrorGroup.newBuilder().setName(name).setGroupId(groupId).build();
+ ErrorGroup expectedResponse =
+ ErrorGroup.newBuilder().setNameWithGroupName(name).setGroupId(groupId).build();
mockErrorGroupService.addResponse(expectedResponse);
- String formattedGroupName = ErrorGroupServiceClient.formatGroupName("[PROJECT]", "[GROUP]");
+ GroupName groupName = GroupName.create("[PROJECT]", "[GROUP]");
- ErrorGroup actualResponse = client.getGroup(formattedGroupName);
+ ErrorGroup actualResponse = client.getGroup(groupName);
Assert.assertEquals(expectedResponse, actualResponse);
List actualRequests = mockErrorGroupService.getRequests();
Assert.assertEquals(1, actualRequests.size());
GetGroupRequest actualRequest = (GetGroupRequest) actualRequests.get(0);
- Assert.assertEquals(formattedGroupName, actualRequest.getGroupName());
+ Assert.assertEquals(groupName, actualRequest.getGroupNameAsGroupName());
}
@Test
@@ -102,9 +104,9 @@ public void getGroupExceptionTest() throws Exception {
mockErrorGroupService.addException(exception);
try {
- String formattedGroupName = ErrorGroupServiceClient.formatGroupName("[PROJECT]", "[GROUP]");
+ GroupName groupName = GroupName.create("[PROJECT]", "[GROUP]");
- client.getGroup(formattedGroupName);
+ client.getGroup(groupName);
Assert.fail("No exception raised");
} catch (ApiException e) {
Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
@@ -114,9 +116,10 @@ public void getGroupExceptionTest() throws Exception {
@Test
@SuppressWarnings("all")
public void updateGroupTest() {
- String name = "name3373707";
+ GroupName name = GroupName.create("[PROJECT]", "[GROUP]");
String groupId = "groupId506361563";
- ErrorGroup expectedResponse = ErrorGroup.newBuilder().setName(name).setGroupId(groupId).build();
+ ErrorGroup expectedResponse =
+ ErrorGroup.newBuilder().setNameWithGroupName(name).setGroupId(groupId).build();
mockErrorGroupService.addResponse(expectedResponse);
ErrorGroup group = ErrorGroup.newBuilder().build();
diff --git a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceTest.java b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceTest.java
index 324a3caaf617..9d8250cbc24a 100644
--- a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceTest.java
+++ b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ErrorStatsServiceTest.java
@@ -30,6 +30,7 @@
import com.google.devtools.clouderrorreporting.v1beta1.ListEventsResponse;
import com.google.devtools.clouderrorreporting.v1beta1.ListGroupStatsRequest;
import com.google.devtools.clouderrorreporting.v1beta1.ListGroupStatsResponse;
+import com.google.devtools.clouderrorreporting.v1beta1.ProjectName;
import com.google.devtools.clouderrorreporting.v1beta1.QueryTimeRange;
import com.google.protobuf.GeneratedMessageV3;
import io.grpc.Status;
@@ -98,11 +99,10 @@ public void listGroupStatsTest() {
.build();
mockErrorStatsService.addResponse(expectedResponse);
- String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ ProjectName projectName = ProjectName.create("[PROJECT]");
QueryTimeRange timeRange = QueryTimeRange.newBuilder().build();
- ListGroupStatsPagedResponse pagedListResponse =
- client.listGroupStats(formattedProjectName, timeRange);
+ ListGroupStatsPagedResponse pagedListResponse = client.listGroupStats(projectName, timeRange);
List resources = Lists.newArrayList(pagedListResponse.iterateAllElements());
Assert.assertEquals(1, resources.size());
@@ -112,7 +112,7 @@ public void listGroupStatsTest() {
Assert.assertEquals(1, actualRequests.size());
ListGroupStatsRequest actualRequest = (ListGroupStatsRequest) actualRequests.get(0);
- Assert.assertEquals(formattedProjectName, actualRequest.getProjectName());
+ Assert.assertEquals(projectName, actualRequest.getProjectNameAsProjectName());
Assert.assertEquals(timeRange, actualRequest.getTimeRange());
}
@@ -123,10 +123,10 @@ public void listGroupStatsExceptionTest() throws Exception {
mockErrorStatsService.addException(exception);
try {
- String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ ProjectName projectName = ProjectName.create("[PROJECT]");
QueryTimeRange timeRange = QueryTimeRange.newBuilder().build();
- client.listGroupStats(formattedProjectName, timeRange);
+ client.listGroupStats(projectName, timeRange);
Assert.fail("No exception raised");
} catch (ApiException e) {
Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
@@ -146,10 +146,10 @@ public void listEventsTest() {
.build();
mockErrorStatsService.addResponse(expectedResponse);
- String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ ProjectName projectName = ProjectName.create("[PROJECT]");
String groupId = "groupId506361563";
- ListEventsPagedResponse pagedListResponse = client.listEvents(formattedProjectName, groupId);
+ ListEventsPagedResponse pagedListResponse = client.listEvents(projectName, groupId);
List resources = Lists.newArrayList(pagedListResponse.iterateAllElements());
Assert.assertEquals(1, resources.size());
@@ -159,7 +159,7 @@ public void listEventsTest() {
Assert.assertEquals(1, actualRequests.size());
ListEventsRequest actualRequest = (ListEventsRequest) actualRequests.get(0);
- Assert.assertEquals(formattedProjectName, actualRequest.getProjectName());
+ Assert.assertEquals(projectName, actualRequest.getProjectNameAsProjectName());
Assert.assertEquals(groupId, actualRequest.getGroupId());
}
@@ -170,10 +170,10 @@ public void listEventsExceptionTest() throws Exception {
mockErrorStatsService.addException(exception);
try {
- String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ ProjectName projectName = ProjectName.create("[PROJECT]");
String groupId = "groupId506361563";
- client.listEvents(formattedProjectName, groupId);
+ client.listEvents(projectName, groupId);
Assert.fail("No exception raised");
} catch (ApiException e) {
Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
@@ -186,16 +186,16 @@ public void deleteEventsTest() {
DeleteEventsResponse expectedResponse = DeleteEventsResponse.newBuilder().build();
mockErrorStatsService.addResponse(expectedResponse);
- String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ ProjectName projectName = ProjectName.create("[PROJECT]");
- DeleteEventsResponse actualResponse = client.deleteEvents(formattedProjectName);
+ DeleteEventsResponse actualResponse = client.deleteEvents(projectName);
Assert.assertEquals(expectedResponse, actualResponse);
List actualRequests = mockErrorStatsService.getRequests();
Assert.assertEquals(1, actualRequests.size());
DeleteEventsRequest actualRequest = (DeleteEventsRequest) actualRequests.get(0);
- Assert.assertEquals(formattedProjectName, actualRequest.getProjectName());
+ Assert.assertEquals(projectName, actualRequest.getProjectNameAsProjectName());
}
@Test
@@ -205,9 +205,9 @@ public void deleteEventsExceptionTest() throws Exception {
mockErrorStatsService.addException(exception);
try {
- String formattedProjectName = ErrorStatsServiceClient.formatProjectName("[PROJECT]");
+ ProjectName projectName = ProjectName.create("[PROJECT]");
- client.deleteEvents(formattedProjectName);
+ client.deleteEvents(projectName);
Assert.fail("No exception raised");
} catch (ApiException e) {
Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
diff --git a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceTest.java b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceTest.java
index 70b1bf877670..913840ab9fe1 100644
--- a/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceTest.java
+++ b/google-cloud-errorreporting/src/test/java/com/google/cloud/errorreporting/spi/v1beta1/ReportErrorsServiceTest.java
@@ -18,6 +18,7 @@
import com.google.api.gax.grpc.ApiException;
import com.google.api.gax.testing.MockGrpcService;
import com.google.api.gax.testing.MockServiceHelper;
+import com.google.devtools.clouderrorreporting.v1beta1.ProjectName;
import com.google.devtools.clouderrorreporting.v1beta1.ReportErrorEventRequest;
import com.google.devtools.clouderrorreporting.v1beta1.ReportErrorEventResponse;
import com.google.devtools.clouderrorreporting.v1beta1.ReportedErrorEvent;
@@ -81,17 +82,17 @@ public void reportErrorEventTest() {
ReportErrorEventResponse expectedResponse = ReportErrorEventResponse.newBuilder().build();
mockReportErrorsService.addResponse(expectedResponse);
- String formattedProjectName = ReportErrorsServiceClient.formatProjectName("[PROJECT]");
+ ProjectName projectName = ProjectName.create("[PROJECT]");
ReportedErrorEvent event = ReportedErrorEvent.newBuilder().build();
- ReportErrorEventResponse actualResponse = client.reportErrorEvent(formattedProjectName, event);
+ ReportErrorEventResponse actualResponse = client.reportErrorEvent(projectName, event);
Assert.assertEquals(expectedResponse, actualResponse);
List actualRequests = mockReportErrorsService.getRequests();
Assert.assertEquals(1, actualRequests.size());
ReportErrorEventRequest actualRequest = (ReportErrorEventRequest) actualRequests.get(0);
- Assert.assertEquals(formattedProjectName, actualRequest.getProjectName());
+ Assert.assertEquals(projectName, actualRequest.getProjectNameAsProjectName());
Assert.assertEquals(event, actualRequest.getEvent());
}
@@ -102,10 +103,10 @@ public void reportErrorEventExceptionTest() throws Exception {
mockReportErrorsService.addException(exception);
try {
- String formattedProjectName = ReportErrorsServiceClient.formatProjectName("[PROJECT]");
+ ProjectName projectName = ProjectName.create("[PROJECT]");
ReportedErrorEvent event = ReportedErrorEvent.newBuilder().build();
- client.reportErrorEvent(formattedProjectName, event);
+ client.reportErrorEvent(projectName, event);
Assert.fail("No exception raised");
} catch (ApiException e) {
Assert.assertEquals(Status.INTERNAL.getCode(), e.getStatusCode());
diff --git a/google-cloud-examples/README.md b/google-cloud-examples/README.md
index 5dbbffcb9f5e..3deb256e9968 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.8.0
+ 0.8.2-alpha
```
If you are using Gradle, add this to your dependencies
```Groovy
-compile 'com.google.cloud:google-cloud-examples:0.8.0'
+compile 'com.google.cloud:google-cloud-examples:0.8.2-alpha'
```
If you are using SBT, add this to your dependencies
```Scala
-libraryDependencies += "com.google.cloud" % "google-cloud-examples" % "0.8.0"
+libraryDependencies += "com.google.cloud" % "google-cloud-examples" % "0.8.2-alpha"
```
To run examples from your command line:
diff --git a/google-cloud-examples/pom.xml b/google-cloud-examples/pom.xml
index ffbb5f46df5f..495d4e431cb2 100644
--- a/google-cloud-examples/pom.xml
+++ b/google-cloud-examples/pom.xml
@@ -11,7 +11,7 @@
com.google.cloud
google-cloud-pom
- 0.8.1-SNAPSHOT
+ 0.8.2-alpha
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..7bb34839c4a3
--- /dev/null
+++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/PubSubExample.java
@@ -0,0 +1,898 @@
+/*
+ * 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.cloud.Identity;
+import com.google.cloud.Policy;
+import com.google.cloud.Role;
+import com.google.cloud.pubsub.Message;
+import com.google.cloud.pubsub.PubSub;
+import com.google.cloud.pubsub.PubSub.MessageProcessor;
+import com.google.cloud.pubsub.PubSubOptions;
+import com.google.cloud.pubsub.PushConfig;
+import com.google.cloud.pubsub.ReceivedMessage;
+import com.google.cloud.pubsub.Subscription;
+import com.google.cloud.pubsub.SubscriptionId;
+import com.google.cloud.pubsub.SubscriptionInfo;
+import com.google.cloud.pubsub.Topic;
+import com.google.cloud.pubsub.TopicInfo;
+import com.google.common.collect.ImmutableMap;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * An example of using Google BigQuery.
+ *
+ * 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 ?
+ * ack +
+ * nack +
+ * 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 abstract static class PubSubAction {
+
+ abstract void run(PubSub pubsub, 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(PubSub pubsub, Tuple subaction) throws Exception {
+ subaction.x().run(pubsub, 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(PubSub pubsub, Void arg) {
+ Iterator topicIterator = pubsub.listTopics().iterateAll();
+ while (topicIterator.hasNext()) {
+ System.out.println(topicIterator.next());
+ }
+ }
+ }
+
+ 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 TopicInfoAction extends TopicAction {
+ @Override
+ public void run(PubSub pubsub, String topic) {
+ System.out.printf("Topic info: %s%n", pubsub.getTopic(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(PubSub pubsub, String topic) {
+ pubsub.create(TopicInfo.of(topic));
+ System.out.printf("Created topic %s%n", topic);
+ }
+ }
+
+ /**
+ * This class demonstrates how to delete a Pub/Sub topic.
+ *
+ * @see Delete a topic
+ */
+ private static class DeleteTopicAction extends TopicAction {
+ @Override
+ public void run(PubSub pubsub, String topic) {
+ pubsub.deleteTopic(topic);
+ System.out.printf("Deleted topic %s%n", topic);
+ }
+ }
+
+ /**
+ * This class demonstrates how to list Pub/Sub subscriptions.
+ *
+ * @see List subscriptions
+ */
+ private static class ListSubscriptionsAction extends PubSubAction {
+ @Override
+ public void run(PubSub pubsub, String topic) {
+ if (topic == null) {
+ Iterator subscriptionIterator = pubsub.listSubscriptions().iterateAll();
+ while (subscriptionIterator.hasNext()) {
+ System.out.println(subscriptionIterator.next());
+ }
+ } else {
+ Iterator subscriptionIdIterator =
+ pubsub.listSubscriptions(topic).iterateAll();
+ while (subscriptionIdIterator.hasNext()) {
+ System.out.println(subscriptionIdIterator.next());
+ }
+ }
+ }
+
+ @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(PubSub pubsub, Tuple> params) {
+ String topic = params.x();
+ List messages = params.y();
+ pubsub.publish(topic, messages);
+ 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)) {
+ messages.add(Message.of(payload));
+ }
+ 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 information on a Pub/Sub subscription.
+ */
+ private static class SubscriptionInfoAction extends SubscriptionAction {
+ @Override
+ public void run(PubSub pubsub, String subscription) {
+ System.out.printf("Subscription info: %s%n", pubsub.getSubscription(subscription));
+ }
+ }
+
+ /**
+ * This class demonstrates how to create a Pub/Sub subscription.
+ *
+ * @see Create a subscription
+ */
+ private static class CreateSubscriptionAction extends PubSubAction {
+ @Override
+ public void run(PubSub pubsub, SubscriptionInfo subscription) {
+ pubsub.create(subscription);
+ System.out.printf("Created subscription %s%n", subscription.getName());
+ }
+
+ @Override
+ SubscriptionInfo 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 {
+ SubscriptionInfo.Builder builder = SubscriptionInfo.newBuilder(args[0], args[1]);
+ if (args.length == 3) {
+ builder.setPushConfig(PushConfig.of(args[2]));
+ }
+ return builder.build();
+ }
+ 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(PubSub pubsub, String subscription) {
+ pubsub.deleteSubscription(subscription);
+ System.out.printf("Deleted subscription %s%n", subscription);
+ }
+ }
+
+ /**
+ * 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(PubSub pubsub, Tuple params) {
+ String subscription = params.x();
+ PushConfig pushConfig = params.y();
+ pubsub.replacePushConfig(subscription, pushConfig);
+ System.out.printf("Set push config %s for subscription %s%n", pushConfig, subscription);
+ }
+
+ @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 subscription = args[0];
+ PushConfig pushConfig = null;
+ if (args.length == 2) {
+ pushConfig = PushConfig.of(args[1]);
+ }
+ return Tuple.of(subscription, pushConfig);
+ }
+ throw new IllegalArgumentException(message);
+ }
+
+ @Override
+ public String params() {
+ return " ?";
+ }
+ }
+
+ private abstract static class MessagesAction extends PubSubAction>> {
+ @Override
+ Tuple> parse(String... args) throws Exception {
+ if (args.length < 2) {
+ throw new IllegalArgumentException("Missing required subscription and ack IDs");
+ }
+ String subscription = args[0];
+ return Tuple.of(subscription, Arrays.asList(Arrays.copyOfRange(args, 1, args.length)));
+ }
+
+ @Override
+ public String params() {
+ return " +";
+ }
+ }
+
+ /**
+ * This class demonstrates how to acknowledge Pub/Sub messages for a subscription.
+ *
+ * @see Receiving
+ * pull messages
+ */
+ private static class AckMessagesAction extends MessagesAction {
+ @Override
+ public void run(PubSub pubsub, Tuple> params) {
+ String subscription = params.x();
+ List ackIds = params.y();
+ pubsub.ack(subscription, ackIds);
+ System.out.printf("Acked %d messages for subscription %s%n", ackIds.size(), subscription);
+ }
+ }
+
+ /**
+ * This class demonstrates how to "nack" Pub/Sub messages for a subscription. This action
+ * corresponds to setting the acknowledge deadline to 0.
+ *
+ * @see Message
+ * acknowledgement deadline
+ */
+ private static class NackMessagesAction extends MessagesAction {
+ @Override
+ public void run(PubSub pubsub, Tuple> params) {
+ String subscription = params.x();
+ List ackIds = params.y();
+ pubsub.nack(subscription, ackIds);
+ System.out.printf("Nacked %d messages for subscription %s%n", ackIds.size(), subscription);
+ }
+ }
+
+ /**
+ * This class demonstrates how modify the acknowledge deadline for messages in a Pub/Sub
+ * subscription.
+ *
+ * @see Message
+ * acknowledgement deadline
+ */
+ private static class ModifyAckDeadlineAction
+ extends PubSubAction>> {
+
+ static class SubscriptionAndDeadline {
+
+ private final String subscription;
+ private final int deadlineMillis;
+
+ private SubscriptionAndDeadline(String subscription, int deadlineMillis) {
+ this.subscription = subscription;
+ this.deadlineMillis = deadlineMillis;
+ }
+
+ String subscription() {
+ return subscription;
+ }
+
+ int deadlineMillis() {
+ return deadlineMillis;
+ }
+ }
+
+ @Override
+ public void run(PubSub pubsub, Tuple> params)
+ throws Exception {
+ String subscription = params.x().subscription();
+ int deadline = params.x().deadlineMillis();
+ List ackIds = params.y();
+ pubsub.modifyAckDeadline(subscription, deadline, TimeUnit.MILLISECONDS, ackIds);
+ System.out.printf("Ack deadline set to %d for %d messages in subscription %s%n", deadline,
+ ackIds.size(), subscription);
+ }
+
+ @Override
+ Tuple> parse(String... args) throws Exception {
+ if (args.length < 3) {
+ throw new IllegalArgumentException("Missing required subscription, deadline and ack IDs");
+ }
+ String subscription = args[0];
+ int deadline = Integer.parseInt(args[1]);
+ return Tuple.of(new SubscriptionAndDeadline(subscription, deadline),
+ Arrays.asList(Arrays.copyOfRange(args, 2, args.length)));
+ }
+
+ @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(PubSub pubsub, Tuple params) throws Exception {
+ String subscription = params.x();
+ Long timeout = params.y();
+ final AtomicInteger messageCount = new AtomicInteger();
+ MessageProcessor messageProcessor = new MessageProcessor() {
+
+ @Override
+ public void process(Message message) throws Exception {
+ System.out.printf("Received message \"%s\"%n", message);
+ messageCount.incrementAndGet();
+ }
+ };
+ try (PubSub.MessageConsumer consumer = pubsub.pullAsync(subscription, messageProcessor)) {
+ Thread.sleep(timeout);
+ }
+ System.out.printf("Pulled %d messages from subscription %s%n", messageCount.get(),
+ subscription);
+ }
+
+ @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 subscription = args[0];
+ long timeout = 60_000;
+ if (args.length == 2) {
+ timeout = Long.parseLong(args[1]);
+ }
+ return Tuple.of(subscription, timeout);
+ }
+ throw new IllegalArgumentException(message);
+ }
+
+ @Override
+ public String params() {
+ return " ?";
+ }
+ }
+
+ /**
+ * This class demonstrates how to synchronously pull messages from a Pub/Sub pull subscription.
+ * No more than the requested number of messages are pulled. Possibly less messages are pulled.
+ *
+ * @see Receiving
+ * pull messages
+ */
+ private static class PullSyncAction extends PubSubAction> {
+ @Override
+ public void run(PubSub pubsub, Tuple params) throws Exception {
+ String subscription = params.x();
+ Integer maxMessages = params.y();
+ Iterator messageIterator = pubsub.pull(subscription, maxMessages);
+ int messageCount = 0;
+ while (messageIterator.hasNext()) {
+ ReceivedMessage message = messageIterator.next();
+ System.out.printf("Received message \"%s\"%n", message);
+ message.ack();
+ messageCount++;
+ }
+ System.out.printf("Pulled %d messages from subscription %s%n", messageCount, subscription);
+ }
+
+ @Override
+ Tuple parse(String... args) throws Exception {
+ String message;
+ if (args.length == 2) {
+ String subscription = args[0];
+ int maxMessages = Integer.parseInt(args[1]);
+ return Tuple.of(subscription, maxMessages);
+ } else if (args.length > 2) {
+ message = "Too many arguments.";
+ } else {
+ message = "Missing required subscription name";
+ }
+ 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(PubSub pubsub, String topic) throws Exception {
+ Policy policy = pubsub.getTopicPolicy(topic);
+ System.out.printf("Policy for topic %s%n", topic);
+ 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(PubSub pubsub, String subscription) throws Exception {
+ Policy policy = pubsub.getSubscriptionPolicy(subscription);
+ 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(PubSub pubsub, Tuple> param) throws Exception {
+ String topic = param.x();
+ Tuple roleAndIdentity = param.y();
+ Role role = roleAndIdentity.x();
+ Identity identity = roleAndIdentity.y();
+ Policy policy = pubsub.getTopicPolicy(topic);
+ policy = pubsub.replaceTopicPolicy(topic,
+ policy.toBuilder().addIdentity(role, identity).build());
+ System.out.printf("Added role %s to identity %s for topic %s%n", role, identity, topic);
+ System.out.println(policy);
+ }
+ }
+
+ /**
+ * 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(PubSub pubsub, Tuple> param) throws Exception {
+ String subscription = param.x();
+ Tuple roleAndIdentity = param.y();
+ Role role = roleAndIdentity.x();
+ Identity identity = roleAndIdentity.y();
+ Policy policy = pubsub.getSubscriptionPolicy(subscription);
+ policy = pubsub.replaceSubscriptionPolicy(subscription,
+ policy.toBuilder().addIdentity(role, identity).build());
+ System.out.printf("Added role %s to identity %s for subscription %s%n", role, identity,
+ subscription);
+ System.out.println(policy);
+ }
+ }
+
+ 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(PubSub pubsub, Tuple> param) throws Exception {
+ String topic = param.x();
+ List permissions = param.y();
+ List booleanPermissions = pubsub.testTopicPermissions(topic, permissions);
+ System.out.printf("Caller permissions on topic %s%n", topic);
+ for (int i = 0; i < permissions.size(); i++) {
+ System.out.printf("%s: %b%n", permissions.get(i), booleanPermissions.get(i));
+ }
+ }
+ }
+
+ /**
+ * 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(PubSub pubsub, Tuple> param) throws Exception {
+ String subscription = param.x();
+ List permissions = param.y();
+ List booleanPermissions =
+ pubsub.testSubscriptionPermissions(subscription, permissions);
+ System.out.printf("Caller permissions on subscription %s%n", subscription);
+ for (int i = 0; i < permissions.size(); i++) {
+ System.out.printf("%s: %b%n", permissions.get(i), booleanPermissions.get(i));
+ }
+ }
+ }
+
+ static {
+ CREATE_ACTIONS.put("topic", new CreateTopicAction());
+ CREATE_ACTIONS.put("subscription", new CreateSubscriptionAction());
+ INFO_ACTIONS.put("topic", new TopicInfoAction());
+ 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());
+ PULL_ACTIONS.put("sync", new PullSyncAction());
+ 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());
+ ACTIONS.put("ack", new AckMessagesAction());
+ ACTIONS.put("nack", new NackMessagesAction());
+ ACTIONS.put("modify-ack-deadline", new ModifyAckDeadlineAction());
+ }
+
+ 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;
+ }
+ PubSubOptions.Builder optionsBuilder = PubSubOptions.newBuilder();
+ PubSubAction action;
+ String actionName;
+ if (args.length >= 2 && !ACTIONS.containsKey(args[0])) {
+ actionName = args[1];
+ optionsBuilder.setProjectId(args[0]);
+ action = ACTIONS.get(args[1]);
+ args = Arrays.copyOfRange(args, 2, args.length);
+ } else {
+ actionName = args[0];
+ action = ACTIONS.get(args[0]);
+ args = Arrays.copyOfRange(args, 1, args.length);
+ }
+ if (action == null) {
+ System.out.println("Unrecognized action.");
+ printUsage();
+ return;
+ }
+ try (PubSub pubsub = optionsBuilder.build().getService()) {
+ 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(pubsub, arg);
+ }
+ }
+}
diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PubSubSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PubSubSnippets.java
new file mode 100644
index 000000000000..d03cbe8347c8
--- /dev/null
+++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PubSubSnippets.java
@@ -0,0 +1,1050 @@
+/*
+ * Copyright 2016 Google Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * EDITING INSTRUCTIONS
+ * This file is referenced in PubSub's javadoc. Any change to this file should be reflected in
+ * PubSub's javadoc.
+ */
+
+package com.google.cloud.examples.pubsub.snippets;
+
+import com.google.cloud.AsyncPage;
+import com.google.cloud.Identity;
+import com.google.cloud.Page;
+import com.google.cloud.Policy;
+import com.google.cloud.Role;
+import com.google.cloud.pubsub.Message;
+import com.google.cloud.pubsub.PubSub;
+import com.google.cloud.pubsub.PubSub.ListOption;
+import com.google.cloud.pubsub.PubSub.MessageProcessor;
+import com.google.cloud.pubsub.PushConfig;
+import com.google.cloud.pubsub.ReceivedMessage;
+import com.google.cloud.pubsub.Subscription;
+import com.google.cloud.pubsub.SubscriptionId;
+import com.google.cloud.pubsub.SubscriptionInfo;
+import com.google.cloud.pubsub.Topic;
+import com.google.cloud.pubsub.TopicInfo;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * This class contains a number of snippets for the {@link PubSub} interface.
+ */
+public class PubSubSnippets {
+
+ private final PubSub pubsub;
+
+ public PubSubSnippets(PubSub pubsub) {
+ this.pubsub = pubsub;
+ }
+
+ /**
+ * Example of creating a topic.
+ */
+ // [TARGET create(TopicInfo)]
+ // [VARIABLE "my_topic_name"]
+ public Topic createTopic(String topicName) {
+ // [START createTopic]
+ TopicInfo topicInfo = TopicInfo.of(topicName);
+ Topic topic = pubsub.create(topicInfo);
+ // [END createTopic]
+ return topic;
+ }
+
+ /**
+ * Example of asynchronously creating a topic.
+ */
+ // [TARGET createAsync(TopicInfo)]
+ // [VARIABLE "my_topic_name"]
+ public Topic createTopicAsync(String topicName) throws ExecutionException, InterruptedException {
+ // [START createTopicAsync]
+ TopicInfo topicInfo = TopicInfo.of(topicName);
+ Future future = pubsub.createAsync(topicInfo);
+ // ...
+ Topic topic = future.get();
+ // [END createTopicAsync]
+ return topic;
+ }
+
+ /**
+ * Example of getting a topic.
+ */
+ // [TARGET getTopic(String)]
+ // [VARIABLE "my_topic_name"]
+ public Topic getTopic(String topicName) {
+ // [START getTopic]
+ Topic topic = pubsub.getTopic(topicName);
+ if (topic == null) {
+ // topic was not found
+ }
+ // [END getTopic]
+ return topic;
+ }
+
+ /**
+ * Example of asynchronously getting a topic.
+ */
+ // [TARGET getTopicAsync(String)]
+ // [VARIABLE "my_topic_name"]
+ public Topic getTopicAsync(String topicName) throws ExecutionException, InterruptedException {
+ // [START getTopicAsync]
+ Future future = pubsub.getTopicAsync(topicName);
+ // ...
+ Topic topic = future.get();
+ if (topic == null) {
+ // topic was not found
+ }
+ // [END getTopicAsync]
+ return topic;
+ }
+
+ /**
+ * Example of listing topics, specifying the page size.
+ */
+ // [TARGET listTopics(ListOption...)]
+ public Page listTopics() {
+ // [START listTopics]
+ Page topics = pubsub.listTopics(ListOption.pageSize(100));
+ Iterator topicIterator = topics.iterateAll();
+ while (topicIterator.hasNext()) {
+ Topic topic = topicIterator.next();
+ // do something with the topic
+ }
+ // [END listTopics]
+ return topics;
+ }
+
+ /**
+ * Example of asynchronously listing topics, specifying the page size.
+ */
+ // [TARGET listTopicsAsync(ListOption...)]
+ public Page listTopicsAsync() throws ExecutionException, InterruptedException {
+ // [START listTopicsAsync]
+ Future> future = pubsub.listTopicsAsync(ListOption.pageSize(100));
+ // ...
+ AsyncPage topics = future.get();
+ Iterator topicIterator = topics.iterateAll();
+ while (topicIterator.hasNext()) {
+ Topic topic = topicIterator.next();
+ // do something with the topic
+ }
+ // [END listTopicsAsync]
+ return topics;
+ }
+
+ /**
+ * Example of deleting a topic.
+ */
+ // [TARGET deleteTopic(String)]
+ // [VARIABLE "my_topic_name"]
+ public boolean deleteTopic(String topicName) {
+ // [START deleteTopic]
+ boolean deleted = pubsub.deleteTopic(topicName);
+ if (deleted) {
+ // the topic was deleted
+ } else {
+ // the topic was not found
+ }
+ // [END deleteTopic]
+ return deleted;
+ }
+
+ /**
+ * Example of asynchronously deleting a topic.
+ */
+ // [TARGET deleteTopicAsync(String)]
+ // [VARIABLE "my_topic_name"]
+ public boolean deleteTopicAsync(String topicName)
+ throws ExecutionException, InterruptedException {
+ // [START deleteTopicAsync]
+ Future future = pubsub.deleteTopicAsync(topicName);
+ // ...
+ boolean deleted = future.get();
+ if (deleted) {
+ // the topic was deleted
+ } else {
+ // the topic was not found
+ }
+ // [END deleteTopicAsync]
+ return deleted;
+ }
+
+ /**
+ * Example of publishing one message to a topic.
+ */
+ // [TARGET publish(String, Message)]
+ // [VARIABLE "my_topic_name"]
+ public String publishOneMessage(String topicName) {
+ // [START publishOneMessage]
+ Message message = Message.of("payload");
+ String messageId = pubsub.publish(topicName, message);
+ // [END publishOneMessage]
+ return messageId;
+ }
+
+ /**
+ * Example of asynchronously publishing one message to a topic.
+ */
+ // [TARGET publishAsync(String, Message)]
+ // [VARIABLE "my_topic_name"]
+ public String publishOneMessageAsync(String topicName)
+ throws ExecutionException, InterruptedException {
+ // [START publishOneMessageAsync]
+ Message message = Message.of("payload");
+ Future future = pubsub.publishAsync(topicName, message);
+ // ...
+ String messageId = future.get();
+ // [END publishOneMessageAsync]
+ return messageId;
+ }
+
+ /**
+ * Example of publishing a list of messages to a topic.
+ */
+ // [TARGET publish(String, Iterable)]
+ // [VARIABLE "my_topic_name"]
+ public List publishMessageList(String topicName) {
+ // [START publishMessageList]
+ List messages = new LinkedList<>();
+ messages.add(Message.of("payload1"));
+ messages.add(Message.of("payload2"));
+ List messageIds = pubsub.publish(topicName, messages);
+ // [END publishMessageList]
+ return messageIds;
+ }
+
+ /**
+ * Example of asynchronously publishing a list of messages to a topic.
+ */
+ // [TARGET publishAsync(String, Iterable)]
+ // [VARIABLE "my_topic_name"]
+ public List publishMessageListAsync(String topicName)
+ throws ExecutionException, InterruptedException {
+ // [START publishMessageListAsync]
+ List messages = new LinkedList<>();
+ messages.add(Message.of("payload1"));
+ messages.add(Message.of("payload2"));
+ Future> future = pubsub.publishAsync(topicName, messages);
+ // ...
+ List messageIds = future.get();
+ // [END publishMessageListAsync]
+ return messageIds;
+ }
+
+ /**
+ * Example of publishing some messages to a topic.
+ */
+ // [TARGET publish(String, Message, Message...)]
+ // [VARIABLE "my_topic_name"]
+ public List publishMessages(String topicName) {
+ // [START publishMessages]
+ Message message1 = Message.of("payload1");
+ Message message2 = Message.of("payload2");
+ List messageIds = pubsub.publish(topicName, message1, message2);
+ // [END publishMessages]
+ return messageIds;
+ }
+
+ /**
+ * Example of asynchronously publishing some messages to a topic.
+ */
+ // [TARGET publishAsync(String, Message, Message...)]
+ // [VARIABLE "my_topic_name"]
+ public List publishMessagesAsync(String topicName)
+ throws ExecutionException, InterruptedException {
+ // [START publishMessagesAsync]
+ Message message1 = Message.of("payload1");
+ Message message2 = Message.of("payload2");
+ Future> future = pubsub.publishAsync(topicName, message1, message2);
+ // ...
+ List messageIds = future.get();
+ // [END publishMessagesAsync]
+ return messageIds;
+ }
+
+ /**
+ * Example of creating a pull subscription for a topic.
+ */
+ // [TARGET create(SubscriptionInfo)]
+ // [VARIABLE "my_topic_name"]
+ // [VARIABLE "my_subscription_name"]
+ public Subscription createSubscription(String topicName, String subscriptionName) {
+ // [START createSubscription]
+ SubscriptionInfo subscriptionInfo = SubscriptionInfo.of(topicName, subscriptionName);
+ Subscription subscription = pubsub.create(subscriptionInfo);
+ // [END createSubscription]
+ return subscription;
+ }
+
+ /**
+ * Example of asynchronously creating a pull subscription for a topic.
+ */
+ // [TARGET createAsync(SubscriptionInfo)]
+ // [VARIABLE "my_topic_name"]
+ // [VARIABLE "my_subscription_name"]
+ public Subscription createSubscriptionAsync(String topicName, String subscriptionName)
+ throws ExecutionException, InterruptedException {
+ // [START createSubscriptionAsync]
+ SubscriptionInfo subscriptionInfo = SubscriptionInfo.of(topicName, subscriptionName);
+ Future future = pubsub.createAsync(subscriptionInfo);
+ // ...
+ Subscription subscription = future.get();
+ // [END createSubscriptionAsync]
+ return subscription;
+ }
+
+ /**
+ * Example of replacing the push configuration of a subscription, setting the push endpoint.
+ */
+ // [TARGET replacePushConfig(String, PushConfig)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "https://www.example.com/push"]
+ public void replacePushConfig(String subscriptionName, String endpoint) {
+ // [START replacePushConfig]
+ PushConfig pushConfig = PushConfig.of(endpoint);
+ pubsub.replacePushConfig(subscriptionName, pushConfig);
+ // [END replacePushConfig]
+ }
+
+ /**
+ * Example of replacing the push configuration of a subscription, making it a pull
+ * subscription.
+ */
+ // [TARGET replacePushConfig(String, PushConfig)]
+ // [VARIABLE "my_subscription_name"]
+ public void replacePushConfigToPull(String subscriptionName) {
+ // [START replacePushConfigToPull]
+ pubsub.replacePushConfig(subscriptionName, null);
+ // [END replacePushConfigToPull]
+ }
+
+ /**
+ * Example of asynchronously replacing the push configuration of a subscription, setting the
+ * push endpoint.
+ */
+ // [TARGET replacePushConfigAsync(String, PushConfig)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "https://www.example.com/push"]
+ public void replacePushConfigAsync(String subscriptionName, String endpoint)
+ throws ExecutionException, InterruptedException {
+ // [START replacePushConfigAsync]
+ PushConfig pushConfig = PushConfig.of(endpoint);
+ Future future = pubsub.replacePushConfigAsync(subscriptionName, pushConfig);
+ // ...
+ future.get();
+ // [END replacePushConfigAsync]
+ }
+
+ /**
+ * Example of asynchronously replacing the push configuration of a subscription, making it a
+ * pull subscription.
+ */
+ // [TARGET replacePushConfigAsync(String, PushConfig)]
+ // [VARIABLE "my_subscription_name"]
+ public void replacePushConfigToPullAsync(String subscriptionName)
+ throws ExecutionException, InterruptedException {
+ // [START replacePushConfigToPullAsync]
+ Future future = pubsub.replacePushConfigAsync(subscriptionName, null);
+ // ...
+ future.get();
+ // [END replacePushConfigToPullAsync]
+ }
+
+ /**
+ * Example of getting a subscription.
+ */
+ // [TARGET getSubscription(String)]
+ // [VARIABLE "my_subscription_name"]
+ public Subscription getSubscription(String subscriptionName) {
+ // [START getSubscription]
+ Subscription subscription = pubsub.getSubscription(subscriptionName);
+ if (subscription == null) {
+ // subscription was not found
+ }
+ // [END getSubscription]
+ return subscription;
+ }
+
+ /**
+ * Example of asynchronously getting a subscription.
+ */
+ // [TARGET getSubscriptionAsync(String)]
+ // [VARIABLE "my_subscription_name"]
+ public Subscription getSubscriptionAsync(String subscriptionName)
+ throws ExecutionException, InterruptedException {
+ // [START getSubscriptionAsync]
+ Future future = pubsub.getSubscriptionAsync(subscriptionName);
+ // ...
+ Subscription subscription = future.get();
+ if (subscription == null) {
+ // subscription was not found
+ }
+ // [END getSubscriptionAsync]
+ return subscription;
+ }
+
+ /**
+ * Example of listing subscriptions, specifying the page size.
+ */
+ // [TARGET listSubscriptions(ListOption...)]
+ public Page listSubscriptions() {
+ // [START listSubscriptions]
+ Page subscriptions = pubsub.listSubscriptions(ListOption.pageSize(100));
+ Iterator subscriptionIterator = subscriptions.iterateAll();
+ while (subscriptionIterator.hasNext()) {
+ Subscription subscription = subscriptionIterator.next();
+ // do something with the subscription
+ }
+ // [END listSubscriptions]
+ return subscriptions;
+ }
+
+ /**
+ * Example of asynchronously listing subscriptions, specifying the page size.
+ */
+ // [TARGET listSubscriptionsAsync(ListOption...)]
+ public Page listSubscriptionsAsync() throws ExecutionException, InterruptedException {
+ // [START listSubscriptionsAsync]
+ Future> future =
+ pubsub.listSubscriptionsAsync(ListOption.pageSize(100));
+ // ...
+ AsyncPage subscriptions = future.get();
+ Iterator subscriptionIterator = subscriptions.iterateAll();
+ while (subscriptionIterator.hasNext()) {
+ Subscription subscription = subscriptionIterator.next();
+ // do something with the subscription
+ }
+ // [END listSubscriptionsAsync]
+ return subscriptions;
+ }
+
+ /**
+ * Example of listing subscriptions for a topic, specifying the page size.
+ */
+ // [TARGET listSubscriptions(String, ListOption...)]
+ // [VARIABLE "my_topic_name"]
+ public Page listSubscriptionsForTopic(String topicName) {
+ // [START listSubscriptionsForTopic]
+ Page subscriptions =
+ pubsub.listSubscriptions(topicName, ListOption.pageSize(100));
+ Iterator subscriptionIterator = subscriptions.iterateAll();
+ while (subscriptionIterator.hasNext()) {
+ SubscriptionId subscription = subscriptionIterator.next();
+ // do something with the subscription identity
+ }
+ // [END listSubscriptionsForTopic]
+ return subscriptions;
+ }
+
+ /**
+ * Example of asynchronously listing subscriptions for a topic, specifying the page size.
+ */
+ // [TARGET listSubscriptionsAsync(String, ListOption...)]
+ // [VARIABLE "my_topic_name"]
+ public Page listSubscriptionsForTopicAsync(String topicName)
+ throws ExecutionException, InterruptedException {
+ // [START listSubscriptionsForTopicAsync]
+ Future> future =
+ pubsub.listSubscriptionsAsync(topicName, ListOption.pageSize(100));
+ // ...
+ AsyncPage subscriptions = future.get();
+ Iterator subscriptionIterator = subscriptions.iterateAll();
+ while (subscriptionIterator.hasNext()) {
+ SubscriptionId subscription = subscriptionIterator.next();
+ // do something with the subscription identity
+ }
+ // [END listSubscriptionsForTopicAsync]
+ return subscriptions;
+ }
+
+ /**
+ * Example of deleting a subscription.
+ */
+ // [TARGET deleteSubscription(String)]
+ // [VARIABLE "my_subscription_name"]
+ public boolean deleteSubscription(String subscriptionName) {
+ // [START deleteSubscription]
+ boolean deleted = pubsub.deleteSubscription(subscriptionName);
+ if (deleted) {
+ // the subscription was deleted
+ } else {
+ // the subscription was not found
+ }
+ // [END deleteSubscription]
+ return deleted;
+ }
+
+ /**
+ * Example of asynchronously deleting a subscription.
+ */
+ // [TARGET deleteSubscriptionAsync(String)]
+ // [VARIABLE "my_subscription_name"]
+ public boolean deleteSubscriptionAsync(String subscriptionName)
+ throws ExecutionException, InterruptedException {
+ // [START deleteSubscriptionAsync]
+ Future future = pubsub.deleteSubscriptionAsync(subscriptionName);
+ // ...
+ boolean deleted = future.get();
+ if (deleted) {
+ // the subscription was deleted
+ } else {
+ // the subscription was not found
+ }
+ // [END deleteSubscriptionAsync]
+ return deleted;
+ }
+
+ /**
+ * Example of pulling a maximum number of messages from a subscription.
+ */
+ // [TARGET pull(String, int)]
+ // [VARIABLE "my_subscription_name"]
+ public void pull(String subscriptionName) {
+ // [START pull]
+ Iterator messages = pubsub.pull(subscriptionName, 100);
+ // Ack deadline is renewed until the message is consumed
+ while (messages.hasNext()) {
+ ReceivedMessage message = messages.next();
+ // do something with message and ack/nack it
+ message.ack(); // or message.nack()
+ }
+ // [END pull]
+ }
+
+ /**
+ * Example of asynchronously pulling a maximum number of messages from a subscription.
+ */
+ // [TARGET pullAsync(String, int)]
+ // [VARIABLE "my_subscription_name"]
+ public void pullAsync(String subscriptionName) throws ExecutionException, InterruptedException {
+ // [START pullAsync]
+ Future> future = pubsub.pullAsync(subscriptionName, 100);
+ // ...
+ Iterator messages = future.get();
+ // Ack deadline is renewed until the message is consumed
+ while (messages.hasNext()) {
+ ReceivedMessage message = messages.next();
+ // do something with message and ack/nack it
+ message.ack(); // or message.nack()
+ }
+ // [END pullAsync]
+ }
+
+ /**
+ * Example of continuously pulling messages from a subscription.
+ */
+ // [TARGET pullAsync(String, MessageProcessor, PullOption...)]
+ // [VARIABLE "my_subscription_name"]
+ public void pullWithMessageConsumer(String subscriptionName) throws Exception {
+ // [START pullWithMessageConsumer]
+ MessageProcessor callback = new MessageProcessor() {
+ public void process(Message message) throws Exception {
+ // Ack deadline is renewed until this method returns
+ // Message is acked if this method returns successfully
+ // Message is nacked if this method throws an exception
+ }
+ };
+ PubSub.MessageConsumer consumer = pubsub.pullAsync(subscriptionName, callback);
+ // ...
+ // Stop pulling
+ consumer.close();
+ // [END pullWithMessageConsumer]
+ }
+
+ /**
+ * Example of acking one message.
+ */
+ // [TARGET ack(String, String, String...)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message_ack_id"]
+ public void ackOneMessage(String subscriptionName, String ackId) {
+ // [START ackOneMessage]
+ pubsub.ack(subscriptionName, ackId);
+ // [END ackOneMessage]
+ }
+
+ /**
+ * Example of asynchronously acking one message.
+ */
+ // [TARGET ackAsync(String, String, String...)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message_ack_id"]
+ public void ackOneMessageAsync(String subscriptionName, String ackId)
+ throws ExecutionException, InterruptedException {
+ // [START ackOneMessageAsync]
+ Future future = pubsub.ackAsync(subscriptionName, ackId);
+ // ...
+ future.get();
+ // [END ackOneMessageAsync]
+ }
+
+ /**
+ * Example of acking more messages.
+ */
+ // [TARGET ack(String, String, String...)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message1_ack_id"]
+ // [VARIABLE "message2_ack_id"]
+ public void ackMoreMessages(String subscriptionName, String ackId1, String ackId2) {
+ // [START ackMoreMessages]
+ pubsub.ack(subscriptionName, ackId1, ackId2);
+ // [END ackMoreMessages]
+ }
+
+ /**
+ * Example of asynchronously acking more messages.
+ */
+ // [TARGET ackAsync(String, String, String...)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message1_ack_id"]
+ // [VARIABLE "message2_ack_id"]
+ public void ackMoreMessagesAsync(String subscriptionName, String ackId1, String ackId2)
+ throws ExecutionException, InterruptedException {
+ // [START ackMoreMessagesAsync]
+ Future future = pubsub.ackAsync(subscriptionName, ackId1, ackId2);
+ // ...
+ future.get();
+ // [END ackMoreMessagesAsync]
+ }
+
+ /**
+ * Example of acking a list of messages.
+ */
+ // [TARGET ack(String, Iterable)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message1_ack_id"]
+ // [VARIABLE "message2_ack_id"]
+ public void ackMessageList(String subscriptionName, String ackId1, String ackId2) {
+ // [START ackMessageList]
+ List ackIds = new LinkedList<>();
+ ackIds.add(ackId1);
+ ackIds.add(ackId2);
+ pubsub.ack(subscriptionName, ackIds);
+ // [END ackMessageList]
+ }
+
+ /**
+ * Example of asynchronously acking a list of messages.
+ */
+ // [TARGET ackAsync(String, Iterable)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message1_ack_id"]
+ // [VARIABLE "message2_ack_id"]
+ public void ackMessageListAsync(String subscriptionName, String ackId1, String ackId2)
+ throws ExecutionException, InterruptedException {
+ // [START ackMessageListAsync]
+ List ackIds = new LinkedList<>();
+ ackIds.add(ackId1);
+ ackIds.add(ackId2);
+ Future future = pubsub.ackAsync(subscriptionName, ackIds);
+ // ...
+ future.get();
+ // [END ackMessageListAsync]
+ }
+
+ /**
+ * Example of nacking one message.
+ */
+ // [TARGET nack(String, String, String...)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message_ack_id"]
+ public void nackOneMessage(String subscriptionName, String ackId) {
+ // [START nackOneMessage]
+ pubsub.nack(subscriptionName, ackId);
+ // [END nackOneMessage]
+ }
+
+ /**
+ * Example of asynchronously nacking one message.
+ */
+ // [TARGET nackAsync(String, String, String...)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message_ack_id"]
+ public void nackOneMessageAsync(String subscriptionName, String ackId)
+ throws ExecutionException, InterruptedException {
+ // [START nackOneMessageAsync]
+ Future future = pubsub.nackAsync(subscriptionName, ackId);
+ // ...
+ future.get();
+ // [END nackOneMessageAsync]
+ }
+
+ /**
+ * Example of nacking more messages.
+ */
+ // [TARGET nack(String, String, String...)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message1_ack_id"]
+ // [VARIABLE "message2_ack_id"]
+ public void nackMoreMessages(String subscriptionName, String ackId1, String ackId2) {
+ // [START nackMoreMessages]
+ pubsub.nack(subscriptionName, ackId1, ackId2);
+ // [END nackMoreMessages]
+ }
+
+ /**
+ * Example of asynchronously nacking more messages.
+ */
+ // [TARGET nackAsync(String, String, String...)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message1_ack_id"]
+ // [VARIABLE "message2_ack_id"]
+ public void nackMoreMessagesAsync(String subscriptionName, String ackId1, String ackId2)
+ throws ExecutionException, InterruptedException {
+ // [START nackMoreMessagesAsync]
+ Future future = pubsub.nackAsync(subscriptionName, ackId1, ackId2);
+ // ...
+ future.get();
+ // [END nackMoreMessagesAsync]
+ }
+
+ /**
+ * Example of nacking a list of messages.
+ */
+ // [TARGET nack(String, Iterable)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message1_ack_id"]
+ // [VARIABLE "message2_ack_id"]
+ public void nackMessageList(String subscriptionName, String ackId1, String ackId2) {
+ // [START nackMessageList]
+ List ackIds = new LinkedList<>();
+ ackIds.add(ackId1);
+ ackIds.add(ackId2);
+ pubsub.nack(subscriptionName, ackIds);
+ // [END nackMessageList]
+ }
+
+ /**
+ * Example of asynchronously nacking a list of messages.
+ */
+ // [TARGET nackAsync(String, Iterable)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message1_ack_id"]
+ // [VARIABLE "message2_ack_id"]
+ public void nackMessageListAsync(String subscriptionName, String ackId1, String ackId2)
+ throws ExecutionException, InterruptedException {
+ // [START nackMessageListAsync]
+ List ackIds = new LinkedList<>();
+ ackIds.add(ackId1);
+ ackIds.add(ackId2);
+ Future future = pubsub.nackAsync(subscriptionName, ackIds);
+ // ...
+ future.get();
+ // [END nackMessageListAsync]
+ }
+
+ /**
+ * Example of modifying the ack deadline of one message.
+ */
+ // [TARGET modifyAckDeadline(String, int, TimeUnit, String, String...)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message_ack_id"]
+ public void modifyAckDeadlineOneMessage(String subscriptionName, String ackId) {
+ // [START modifyAckDeadlineOneMessage]
+ pubsub.modifyAckDeadline(subscriptionName, 60, TimeUnit.SECONDS, ackId);
+ // [END modifyAckDeadlineOneMessage]
+ }
+
+ /**
+ * Example of asynchronously modifying the ack deadline of one message.
+ */
+ // [TARGET modifyAckDeadlineAsync(String, int, TimeUnit, String, String...)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message_ack_id"]
+ public void modifyAckDeadlineOneMessageAsync(String subscriptionName, String ackId)
+ throws ExecutionException, InterruptedException {
+ // [START modifyAckDeadlineOneMessageAsync]
+ Future future =
+ pubsub.modifyAckDeadlineAsync(subscriptionName, 60, TimeUnit.SECONDS, ackId);
+ // ...
+ future.get();
+ // [END modifyAckDeadlineOneMessageAsync]
+ }
+
+ /**
+ * Example of modifying the ack deadline of some messages.
+ */
+ // [TARGET modifyAckDeadline(String, int, TimeUnit, String, String...)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message1_ack_id"]
+ // [VARIABLE "message2_ack_id"]
+ public void modifyAckDeadlineMoreMessages(String subscriptionName, String ackId1, String ackId2) {
+ // [START modifyAckDeadline]
+ pubsub.modifyAckDeadline(subscriptionName, 60, TimeUnit.SECONDS, ackId1, ackId2);
+ // [END modifyAckDeadline]
+ }
+
+ /**
+ * Example of asynchronously modifying the ack deadline of some messages.
+ */
+ // [TARGET modifyAckDeadlineAsync(String, int, TimeUnit, String, String...)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message1_ack_id"]
+ // [VARIABLE "message2_ack_id"]
+ public void modifyAckDeadlineMoreMessagesAsync(String subscriptionName, String ackId1,
+ String ackId2) throws ExecutionException, InterruptedException {
+ // [START modifyAckDeadlineMoreMessagesAsync]
+ Future future =
+ pubsub.modifyAckDeadlineAsync(subscriptionName, 60, TimeUnit.SECONDS, ackId1, ackId2);
+ // ...
+ future.get();
+ // [END modifyAckDeadlineMoreMessagesAsync]
+ }
+
+ /**
+ * Example of modifying the ack deadline of a list of messages.
+ */
+ // [TARGET modifyAckDeadline(String, int, TimeUnit, Iterable)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message1_ack_id"]
+ // [VARIABLE "message2_ack_id"]
+ public void modifyAckDeadlineMessageList(String subscriptionName, String ackId1, String ackId2) {
+ // [START modifyAckDeadlineMessageList]
+ List ackIds = new LinkedList<>();
+ ackIds.add(ackId1);
+ ackIds.add(ackId2);
+ pubsub.modifyAckDeadline(subscriptionName, 60, TimeUnit.SECONDS, ackIds);
+ // [END modifyAckDeadlineMessageList]
+ }
+
+ /**
+ * Example of asynchronously modifying the ack deadline of a list of messages.
+ */
+ // [TARGET modifyAckDeadlineAsync(String, int, TimeUnit, Iterable)]
+ // [VARIABLE "my_subscription_name"]
+ // [VARIABLE "message1_ack_id"]
+ // [VARIABLE "message2_ack_id"]
+ public void modifyAckDeadlineMessageListAsync(String subscriptionName, String ackId1,
+ String ackId2) throws ExecutionException, InterruptedException {
+ // [START modifyAckDeadlineMessageListAsync]
+ List ackIds = new LinkedList<>();
+ ackIds.add(ackId1);
+ ackIds.add(ackId2);
+ Future future =
+ pubsub.modifyAckDeadlineAsync(subscriptionName, 60, TimeUnit.SECONDS, ackIds);
+ // ...
+ future.get();
+ // [END modifyAckDeadlineMessageListAsync]
+ }
+
+ /**
+ * Example of getting a topic policy.
+ */
+ // [TARGET getTopicPolicy(String)]
+ // [VARIABLE "my_topic_name"]
+ public Policy getTopicPolicy(String topicName) {
+ // [START getTopicPolicy]
+ Policy policy = pubsub.getTopicPolicy(topicName);
+ if (policy == null) {
+ // topic was not found
+ }
+ // [END getTopicPolicy]
+ return policy;
+ }
+
+ /**
+ * Example of asynchronously getting a topic policy.
+ */
+ // [TARGET getTopicPolicyAsync(String)]
+ // [VARIABLE "my_topic_name"]
+ public Policy getTopicPolicyAsync(String topicName)
+ throws ExecutionException, InterruptedException {
+ // [START getTopicPolicyAsync]
+ Future future = pubsub.getTopicPolicyAsync(topicName);
+ // ...
+ Policy policy = future.get();
+ if (policy == null) {
+ // topic was not found
+ }
+ // [END getTopicPolicyAsync]
+ return policy;
+ }
+
+ /**
+ * Example of replacing a topic policy.
+ */
+ // [TARGET replaceTopicPolicy(String, Policy)]
+ // [VARIABLE "my_topic_name"]
+ public Policy replaceTopicPolicy(String topicName) {
+ // [START replaceTopicPolicy]
+ Policy policy = pubsub.getTopicPolicy(topicName);
+ Policy updatedPolicy = policy.toBuilder()
+ .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers())
+ .build();
+ updatedPolicy = pubsub.replaceTopicPolicy(topicName, updatedPolicy);
+ // [END replaceTopicPolicy]
+ return updatedPolicy;
+ }
+
+ /**
+ * Example of asynchronously replacing a topic policy.
+ */
+ // [TARGET replaceTopicPolicyAsync(String, Policy)]
+ // [VARIABLE "my_topic_name"]
+ public Policy replaceTopicPolicyAsync(String topicName)
+ throws ExecutionException, InterruptedException {
+ // [START replaceTopicPolicyAsync]
+ Policy policy = pubsub.getTopicPolicy(topicName);
+ Policy updatedPolicy = policy.toBuilder()
+ .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers())
+ .build();
+ Future future = pubsub.replaceTopicPolicyAsync(topicName, updatedPolicy);
+ // ...
+ updatedPolicy = future.get();
+ // [END replaceTopicPolicyAsync]
+ return updatedPolicy;
+ }
+
+ /**
+ * Example of testing whether the caller has the provided permissions on a topic.
+ */
+ // [TARGET testTopicPermissions(String, List)]
+ // [VARIABLE "my_topic_name"]
+ public List testTopicPermissions(String topicName) {
+ // [START testTopicPermissions]
+ List permissions = new LinkedList<>();
+ permissions.add("pubsub.topics.get");
+ List testedPermissions = pubsub.testTopicPermissions(topicName, permissions);
+ // [END testTopicPermissions]
+ return testedPermissions;
+ }
+
+ /**
+ * Example of asynchronously testing whether the caller has the provided permissions on a topic.
+ */
+ // [TARGET testTopicPermissionsAsync(String, List)]
+ // [VARIABLE "my_topic_name"]
+ public List testTopicPermissionsAsync(String topicName)
+ throws ExecutionException, InterruptedException {
+ // [START testTopicPermissionsAsync]
+ List permissions = new LinkedList<>();
+ permissions.add("pubsub.topics.get");
+ Future> future = pubsub.testTopicPermissionsAsync(topicName, permissions);
+ // ...
+ List testedPermissions = future.get();
+ // [END testTopicPermissionsAsync]
+ return testedPermissions;
+ }
+
+ /**
+ * Example of getting a subscription policy.
+ */
+ // [TARGET getSubscriptionPolicy(String)]
+ // [VARIABLE "my_subscription_name"]
+ public Policy getSubscriptionPolicy(String subscriptionName) {
+ // [START getSubscriptionPolicy]
+ Policy policy = pubsub.getSubscriptionPolicy(subscriptionName);
+ if (policy == null) {
+ // subscription was not found
+ }
+ // [END getSubscriptionPolicy]
+ return policy;
+ }
+
+ /**
+ * Example of asynchronously getting a subscription policy.
+ */
+ // [TARGET getSubscriptionPolicyAsync(String)]
+ // [VARIABLE "my_subscription_name"]
+ public Policy getSubscriptionPolicyAsync(String subscriptionName)
+ throws ExecutionException, InterruptedException {
+ // [START getSubscriptionPolicyAsync]
+ Future future = pubsub.getSubscriptionPolicyAsync(subscriptionName);
+ // ...
+ Policy policy = future.get();
+ if (policy == null) {
+ // subscription was not found
+ }
+ // [END getSubscriptionPolicyAsync]
+ return policy;
+ }
+
+ /**
+ * Example of replacing a subscription policy.
+ */
+ // [TARGET replaceSubscriptionPolicy(String, Policy)]
+ // [VARIABLE "my_subscription_name"]
+ public Policy replaceSubscriptionPolicy(String subscriptionName) {
+ // [START replaceSubscriptionPolicy]
+ Policy policy = pubsub.getSubscriptionPolicy(subscriptionName);
+ Policy updatedPolicy = policy.toBuilder()
+ .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers())
+ .build();
+ updatedPolicy = pubsub.replaceSubscriptionPolicy(subscriptionName, updatedPolicy);
+ // [END replaceSubscriptionPolicy]
+ return updatedPolicy;
+ }
+
+ /**
+ * Example of asynchronously replacing a subscription policy.
+ */
+ // [TARGET replaceSubscriptionPolicyAsync(String, Policy)]
+ // [VARIABLE "my_subscription_name"]
+ public Policy replaceSubscriptionPolicyAsync(String subscriptionName)
+ throws ExecutionException, InterruptedException {
+ // [START replaceSubscriptionPolicyAsync]
+ Policy policy = pubsub.getSubscriptionPolicy(subscriptionName);
+ Policy updatedPolicy = policy.toBuilder()
+ .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers())
+ .build();
+ Future future =
+ pubsub.replaceSubscriptionPolicyAsync(subscriptionName, updatedPolicy);
+ // ...
+ updatedPolicy = future.get();
+ // [END replaceSubscriptionPolicyAsync]
+ return updatedPolicy;
+ }
+
+ /**
+ * Example of testing whether the caller has the provided permissions on a subscription.
+ */
+ // [TARGET testSubscriptionPermissions(String, List)]
+ // [VARIABLE "my_subscription_name"]
+ public List testSubscriptionPermissions(String subscriptionName) {
+ // [START testSubscriptionPermissions]
+ List permissions = new LinkedList<>();
+ permissions.add("pubsub.subscriptions.get");
+ List testedPermissions =
+ pubsub.testSubscriptionPermissions(subscriptionName, permissions);
+ // [END testSubscriptionPermissions]
+ return testedPermissions;
+ }
+
+ /**
+ * Example of asynchronously testing whether the caller has the provided permissions on a
+ * subscription.
+ */
+ // [TARGET testSubscriptionPermissionsAsync(String, List)]
+ // [VARIABLE "my_subscription_name"]
+ public List testSubscriptionPermissionsAsync(String subscriptionName)
+ throws ExecutionException, InterruptedException {
+ // [START testSubscriptionPermissionsAsync]
+ List permissions = new LinkedList<>();
+ permissions.add("pubsub.subscriptions.get");
+ Future> future =
+ pubsub.testSubscriptionPermissionsAsync(subscriptionName, permissions);
+ // ...
+ List testedPermissions = future.get();
+ // [END testSubscriptionPermissionsAsync]
+ return testedPermissions;
+ }
+}
diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriptionSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriptionSnippets.java
new file mode 100644
index 000000000000..3e0ac0189fbb
--- /dev/null
+++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriptionSnippets.java
@@ -0,0 +1,316 @@
+/*
+ * Copyright 2016 Google Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/*
+ * EDITING INSTRUCTIONS
+ * This file is referenced in Subscription's javadoc. Any change to this file should be reflected in
+ * Subscription's javadoc.
+ */
+
+package com.google.cloud.examples.pubsub.snippets;
+
+import com.google.cloud.Identity;
+import com.google.cloud.Policy;
+import com.google.cloud.Role;
+import com.google.cloud.pubsub.Message;
+import com.google.cloud.pubsub.PubSub.MessageConsumer;
+import com.google.cloud.pubsub.PubSub.MessageProcessor;
+import com.google.cloud.pubsub.PushConfig;
+import com.google.cloud.pubsub.ReceivedMessage;
+import com.google.cloud.pubsub.Subscription;
+
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+/**
+ * This class contains a number of snippets for the {@link Subscription} class.
+ */
+public class SubscriptionSnippets {
+
+ private final Subscription subscription;
+
+ public SubscriptionSnippets(Subscription subscription) {
+ this.subscription = subscription;
+ }
+
+ /**
+ * Example of getting the subscription's latest information.
+ */
+ // [TARGET reload()]
+ public Subscription reload() {
+ // [START reload]
+ Subscription latestSubscription = subscription.reload();
+ if (latestSubscription == null) {
+ // the subscription was not found
+ }
+ // [END reload]
+ return latestSubscription;
+ }
+
+ /**
+ * Example of asynchronously getting the subscription's latest information.
+ */
+ // [TARGET reloadAsync()]
+ public Subscription reloadAsync() throws ExecutionException, InterruptedException {
+ // [START reloadAsync]
+ Future future = subscription.reloadAsync();
+ // ...
+ Subscription latestSubscription = future.get();
+ if (latestSubscription == null) {
+ // the subscription was not found
+ }
+ // [END reloadAsync]
+ return latestSubscription;
+ }
+
+ /**
+ * Example of deleting the subscription.
+ */
+ // [TARGET delete()]
+ public boolean delete() {
+ // [START delete]
+ boolean deleted = subscription.delete();
+ if (deleted) {
+ // the subscription was deleted
+ } else {
+ // the subscription was not found
+ }
+ // [END delete]
+ return deleted;
+ }
+
+ /**
+ * Example of asynchronously deleting the subscription.
+ */
+ // [TARGET deleteAsync()]
+ public boolean deleteAsync() throws ExecutionException, InterruptedException {
+ // [START deleteAsync]
+ Future future = subscription.deleteAsync();
+ // ...
+ boolean deleted = future.get();
+ if (deleted) {
+ // the subscription was deleted
+ } else {
+ // the subscription was not found
+ }
+ // [END deleteAsync]
+ return deleted;
+ }
+
+ /**
+ * Example of replacing the push configuration of the subscription, setting the push endpoint.
+ */
+ // [TARGET replacePushConfig(PushConfig)]
+ // [VARIABLE "https://www.example.com/push"]
+ public void replacePushConfig(String endpoint) {
+ // [START replacePushConfig]
+ PushConfig pushConfig = PushConfig.of(endpoint);
+ subscription.replacePushConfig(pushConfig);
+ // [END replacePushConfig]
+ }
+
+ /**
+ * Example of replacing the push configuration of the subscription, making it a pull
+ * subscription.
+ */
+ // [TARGET replacePushConfig(PushConfig)]
+ public void replacePushConfigToPull() {
+ // [START replacePushConfigToPull]
+ subscription.replacePushConfig(null);
+ // [END replacePushConfigToPull]
+ }
+
+ /**
+ * Example of asynchronously replacing the push configuration of the subscription, setting the
+ * push endpoint.
+ */
+ // [TARGET replacePushConfigAsync(PushConfig)]
+ // [VARIABLE "https://www.example.com/push"]
+ public void replacePushConfigAsync(String endpoint)
+ throws ExecutionException, InterruptedException {
+ // [START replacePushConfigAsync]
+ PushConfig pushConfig = PushConfig.of(endpoint);
+ Future future = subscription.replacePushConfigAsync(pushConfig);
+ // ...
+ future.get();
+ // [END replacePushConfigAsync]
+ }
+
+ /**
+ * Example of asynchronously replacing the push configuration of the subscription, making it a
+ * pull subscription.
+ */
+ // [TARGET replacePushConfigAsync(PushConfig)]
+ public void replacePushConfigToPullAsync()
+ throws ExecutionException, InterruptedException {
+ // [START replacePushConfigToPullAsync]
+ Future future = subscription.replacePushConfigAsync(null);
+ // ...
+ future.get();
+ // [END replacePushConfigToPullAsync]
+ }
+
+ /**
+ * Example of pulling a maximum number of messages from the subscription.
+ */
+ // [TARGET pull(int)]
+ public void pull() {
+ // [START pull]
+ Iterator messages = subscription.pull(100);
+ // Ack deadline is renewed until the message is consumed
+ while (messages.hasNext()) {
+ ReceivedMessage message = messages.next();
+ // do something with message and ack/nack it
+ message.ack(); // or message.nack()
+ }
+ // [END pull]
+ }
+
+ /**
+ * Example of asynchronously pulling a maximum number of messages from the subscription.
+ */
+ // [TARGET pullAsync(int)]
+ public void pullAsync() throws ExecutionException, InterruptedException {
+ // [START pullAsync]
+ Future> future = subscription.pullAsync(100);
+ // ...
+ Iterator messages = future.get();
+ // Ack deadline is renewed until the message is consumed
+ while (messages.hasNext()) {
+ ReceivedMessage message = messages.next();
+ // do something with message and ack/nack it
+ message.ack(); // or message.nack()
+ }
+ // [END pullAsync]
+ }
+
+ /**
+ * Example of continuously pulling messages from the subscription.
+ */
+ // [TARGET pullAsync(MessageProcessor, PullOption...)]
+ // [VARIABLE "my_subscription_name"]
+ public void pullWithMessageConsumer(String subscriptionName) throws Exception {
+ // [START pullWithMessageConsumer]
+ MessageProcessor callback = new MessageProcessor() {
+ public void process(Message message) throws Exception {
+ // Ack deadline is renewed until this method returns
+ // Message is acked if this method returns successfully
+ // Message is nacked if this method throws an exception
+ }
+ };
+ MessageConsumer consumer = subscription.pullAsync(callback);
+ // ...
+ // Stop pulling
+ consumer.close();
+ // [END pullWithMessageConsumer]
+ }
+
+ /**
+ * Example of getting the subscription's policy.
+ */
+ // [TARGET getPolicy()]
+ public Policy getPolicy() {
+ // [START getPolicy]
+ Policy policy = subscription.getPolicy();
+ if (policy == null) {
+ // subscription was not found
+ }
+ // [END getPolicy]
+ return policy;
+ }
+
+ /**
+ * Example of asynchronously getting the subscription's policy.
+ */
+ // [TARGET getPolicyAsync()]
+ public Policy getPolicyAsync() throws ExecutionException, InterruptedException {
+ // [START getPolicyAsync]
+ Future future = subscription.getPolicyAsync();
+ // ...
+ Policy policy = future.get();
+ if (policy == null) {
+ // subscription was not found
+ }
+ // [END getPolicyAsync]
+ return policy;
+ }
+
+ /**
+ * Example of replacing the subscription's policy.
+ */
+ // [TARGET replacePolicy(Policy)]
+ public Policy replacePolicy() {
+ // [START replacePolicy]
+ Policy policy = subscription.getPolicy();
+ Policy updatedPolicy = policy.toBuilder()
+ .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers())
+ .build();
+ updatedPolicy = subscription.replacePolicy(updatedPolicy);
+ // [END replacePolicy]
+ return updatedPolicy;
+ }
+
+ /**
+ * Example of asynchronously replacing the subscription's policy.
+ */
+ // [TARGET replacePolicyAsync(Policy)]
+ public Policy replacePolicyAsync()
+ throws ExecutionException, InterruptedException {
+ // [START replacePolicyAsync]
+ Policy policy = subscription.getPolicy();
+ Policy updatedPolicy = policy.toBuilder()
+ .addIdentity(Role.viewer(), Identity.allAuthenticatedUsers())
+ .build();
+ Future future = subscription.replacePolicyAsync(updatedPolicy);
+ // ...
+ updatedPolicy = future.get();
+ // [END replacePolicyAsync]
+ return updatedPolicy;
+ }
+
+ /**
+ * Example of testing whether the caller has the provided permissions on the subscription.
+ */
+ // [TARGET testPermissions(List)]
+ public List testPermissions() {
+ // [START testPermissions]
+ List permissions = new LinkedList<>();
+ permissions.add("pubsub.subscriptions.get");
+ List testedPermissions = subscription.testPermissions(permissions);
+ // [END testPermissions]
+ return testedPermissions;
+ }
+
+ /**
+ * Example of asynchronously testing whether the caller has the provided permissions on the
+ * subscription.
+ */
+ // [TARGET testPermissionsAsync(List)]
+ public List testPermissionsAsync()
+ throws ExecutionException, InterruptedException {
+ // [START testPermissionsAsync]
+ List