diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/MessageReceiverSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/MessageReceiverSnippets.java index cfedfb8cea42..160980558e92 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/MessageReceiverSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/MessageReceiverSnippets.java @@ -16,8 +16,8 @@ /* * EDITING INSTRUCTIONS - * This file is referenced in Subscriber's javadoc. Any change to this file should be reflected in - * PubSub's javadoc. + * This file is referenced in MessageReceiver's javadoc. + * Any change to this file should be reflected in MessageReceiver's javadoc. */ package com.google.cloud.examples.pubsub.snippets; @@ -28,6 +28,8 @@ import com.google.pubsub.v1.PubsubMessage; import java.util.concurrent.BlockingQueue; +/** This class contains snippets for the {@link MessageReceiver} interface. */ + public class MessageReceiverSnippets { private final BlockingQueue blockingQueue; diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherClientSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherClientSnippets.java new file mode 100644 index 000000000000..9737bf4a3087 --- /dev/null +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherClientSnippets.java @@ -0,0 +1,169 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.examples.pubsub.snippets; + +import com.google.cloud.Identity; +import com.google.cloud.Role; +import com.google.cloud.ServiceOptions; +import com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicSubscriptionsPagedResponse; +import com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicsPagedResponse; +import com.google.cloud.pubsub.spi.v1.PublisherClient; +import com.google.iam.v1.Binding; +import com.google.iam.v1.Policy; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.pubsub.v1.ListTopicSubscriptionsRequest; +import com.google.pubsub.v1.ListTopicsRequest; +import com.google.pubsub.v1.ProjectName; +import com.google.pubsub.v1.Topic; +import com.google.pubsub.v1.TopicName; +import java.util.LinkedList; +import java.util.List; + +/** This class contains a number of snippets for the {@link PublisherClient} interface. */ +public class PublisherClientSnippets { + + private final String projectId; + + public PublisherClientSnippets() { + this.projectId = ServiceOptions.getDefaultProjectId(); + } + + public String getProjectId() { + return projectId; + } + + /** Example of creating a topic. */ + public Topic createTopic(String topicId) throws Exception { + try (PublisherClient publisherClient = PublisherClient.create()) { + // [START createTopic] + TopicName topicName = TopicName.create(projectId, topicId); + Topic topic = publisherClient.createTopic(topicName); + // [END createTopic] + return topic; + } + } + + /** Example of listing topics. */ + public ListTopicsPagedResponse listTopics() throws Exception { + try (PublisherClient publisherClient = PublisherClient.create()) { + // [START listTopics] + ListTopicsRequest listTopicsRequest = + ListTopicsRequest.newBuilder() + .setProjectWithProjectName(ProjectName.create(projectId)) + .build(); + ListTopicsPagedResponse response = publisherClient.listTopics(listTopicsRequest); + Iterable topics = response.iterateAllElements(); + for (Topic topic : topics) { + // do something with the topic + } + // [END listTopics] + return response; + } + } + + /** Example of listing topics for a subscription. */ + public ListTopicSubscriptionsPagedResponse listTopicSubscriptions(String topicId) + throws Exception { + try (PublisherClient publisherClient = PublisherClient.create()) { + // [START listTopicSubscriptions] + TopicName topicName = TopicName.create(projectId, topicId); + ListTopicSubscriptionsRequest request = + ListTopicSubscriptionsRequest.newBuilder() + .setTopicWithTopicName(topicName) + .build(); + ListTopicSubscriptionsPagedResponse response = + publisherClient.listTopicSubscriptions(request); + Iterable subscriptionNames = response.iterateAllElements(); + for (String subscriptionName : subscriptionNames) { + // do something with the subscription name + } + // [END listTopicSubscriptions] + return response; + } + } + + /** Example of deleting a topic. */ + public TopicName deleteTopic(String topicId) throws Exception { + try (PublisherClient publisherClient = PublisherClient.create()) { + // [START deleteTopic] + TopicName topicName = TopicName.create(projectId, topicId); + publisherClient.deleteTopic(topicName); + // [END deleteTopic] + return topicName; + } + } + + /** Example of getting a topic policy. */ + public Policy getTopicPolicy(String topicId) throws Exception { + try (PublisherClient publisherClient = PublisherClient.create()) { + // [START getTopicPolicy] + TopicName topicName = TopicName.create(projectId, topicId); + Policy policy = publisherClient.getIamPolicy(topicName.toString()); + if (policy == null) { + // topic iam policy was not found + } + // [END getTopicPolicy] + return policy; + } + } + + /** Example of replacing a topic policy. */ + public Policy replaceTopicPolicy(String topicId) throws Exception { + try (PublisherClient publisherClient = PublisherClient.create()) { + // [START replaceTopicPolicy] + String topicName = TopicName.create(projectId, topicId).toString(); + Policy policy = publisherClient.getIamPolicy(topicName); + // add role -> members binding + Binding binding = + Binding.newBuilder() + .setRole(Role.viewer().toString()) + .addMembers(Identity.allAuthenticatedUsers().toString()) + .build(); + // create updated policy + Policy updatedPolicy = Policy.newBuilder(policy).addBindings(binding).build(); + updatedPolicy = publisherClient.setIamPolicy(topicName, updatedPolicy); + // [END replaceTopicPolicy] + return updatedPolicy; + } + } + + /** Example of testing whether the caller has the provided permissions on a topic. + * Only viewer, editor or admin/owner can view results of pubsub.topics.get */ + public TestIamPermissionsResponse testTopicPermissions(String topicId) throws Exception { + try (PublisherClient publisherClient = PublisherClient.create()) { + // [START testTopicPermissions] + List permissions = new LinkedList<>(); + permissions.add("pubsub.topics.get"); + TopicName topicName = TopicName.create(projectId, topicId); + TestIamPermissionsResponse testedPermissions = + publisherClient.testIamPermissions(topicName.toString(), permissions); + // [END testTopicPermissions] + return testedPermissions; + } + } + + /** Example of getting a topic. */ + public Topic getTopic(String topicId) throws Exception { + try (PublisherClient publisherClient = PublisherClient.create()) { + // [START getTopic] + TopicName topicName = TopicName.create(projectId, topicId); + Topic topic = publisherClient.getTopic(topicName); + // [END createTopic] + return topic; + } + } +} diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherSnippets.java index 28cb71f615ea..77d26eb1da35 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/PublisherSnippets.java @@ -14,6 +14,12 @@ * limitations under the License. */ +/* + * EDITING INSTRUCTIONS + * This file is referenced in Publisher's javadoc. Any change to this file should be reflected in + * Publisher's javadoc. + */ + package com.google.cloud.examples.pubsub.snippets; import com.google.api.gax.core.RpcFuture; @@ -23,6 +29,7 @@ import com.google.pubsub.v1.PubsubMessage; import com.google.pubsub.v1.TopicName; +/** This class contains snippets for the {@link Publisher} interface. */ public class PublisherSnippets { private final Publisher publisher; @@ -30,9 +37,7 @@ public PublisherSnippets(Publisher publisher) { this.publisher = publisher; } - /** - * Example of publishing a message. - */ + /** Example of publishing a message. */ // [TARGET publish(PubsubMessage)] // [VARIABLE "my_message"] public RpcFuture publish(String message) { @@ -40,22 +45,21 @@ public RpcFuture publish(String message) { ByteString data = ByteString.copyFromUtf8(message); PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build(); RpcFuture messageIdFuture = publisher.publish(pubsubMessage); - messageIdFuture.addCallback(new RpcFutureCallback() { - public void onSuccess(String messageId) { - System.out.println("published with message id: " + messageId); - } + messageIdFuture.addCallback( + new RpcFutureCallback() { + public void onSuccess(String messageId) { + System.out.println("published with message id: " + messageId); + } - public void onFailure(Throwable t) { - System.out.println("failed to publish: " + t); - } - }); + public void onFailure(Throwable t) { + System.out.println("failed to publish: " + t); + } + }); // [END publish] return messageIdFuture; } - /** - * Example of creating a {@code Publisher}. - */ + /** Example of creating a {@code Publisher}. */ // [TARGET newBuilder(TopicName)] // [VARIABLE "my_project"] // [VARIABLE "my_topic"] diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberClientSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberClientSnippets.java new file mode 100644 index 000000000000..bee70a1a118b --- /dev/null +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberClientSnippets.java @@ -0,0 +1,187 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** This class contains snippets for the {@link SubscriberClient} interface. */ + +package com.google.cloud.examples.pubsub.snippets; + +import com.google.cloud.Identity; +import com.google.cloud.Role; +import com.google.cloud.ServiceOptions; +import com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListSubscriptionsPagedResponse; +import com.google.cloud.pubsub.spi.v1.PublisherClient; +import com.google.cloud.pubsub.spi.v1.SubscriberClient; +import com.google.iam.v1.Binding; +import com.google.iam.v1.Policy; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.pubsub.v1.ListSubscriptionsRequest; +import com.google.pubsub.v1.ProjectName; +import com.google.pubsub.v1.PullResponse; +import com.google.pubsub.v1.PushConfig; +import com.google.pubsub.v1.ReceivedMessage; +import com.google.pubsub.v1.Subscription; +import com.google.pubsub.v1.SubscriptionName; +import com.google.pubsub.v1.TopicName; +import edu.emory.mathcs.backport.java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +/** This class contains a number of snippets for the {@link SubscriberClient} interface. */ +public class SubscriberClientSnippets { + + private final String projectId; + + public SubscriberClientSnippets() { + this.projectId = ServiceOptions.getDefaultProjectId(); + } + + public String getProjectId() { + return projectId; + } + + /** Example of creating a pull subscription for a topic. */ + public Subscription createSubscription(String topic, String subscriptionId) throws Exception { + try (SubscriberClient subscriberClient = SubscriberClient.create()) { + // [START createSubscription] + TopicName topicName = TopicName.create(projectId, topic); + SubscriptionName subscriptionName = + SubscriptionName.create(projectId, subscriptionId); + Subscription subscription = + subscriberClient.createSubscription( + subscriptionName, topicName, PushConfig.getDefaultInstance(), 0); + // [END createSubscription] + return subscription; + } + } + + /** Example of pulling a maximum number of messages from a subscription. */ + public PullResponse pull(String subscriptionId) throws Exception { + try (SubscriberClient subscriberClient = SubscriberClient.create()) { + // [START pull] + SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId); + PullResponse response = subscriberClient.pull(subscriptionName, true, 100); + for (ReceivedMessage message : response.getReceivedMessagesList()) { + // do something with message, then ack or nack + subscriberClient.acknowledge( + subscriptionName, Collections.singletonList(message.getAckId())); + } + // [END pull] + return response; + } + } + + /** Example of replacing the push configuration of a subscription, setting the push endpoint. */ + public void replacePushConfig(String subscriptionId, String endpoint) throws Exception { + try (SubscriberClient subscriberClient = SubscriberClient.create()) { + // [START replacePushConfig] + SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId); + PushConfig pushConfig = PushConfig.newBuilder().setPushEndpoint(endpoint).build(); + subscriberClient.modifyPushConfig(subscriptionName, pushConfig); + // [END replacePushConfig] + } + } + + /** Example of listing subscriptions. */ + public ListSubscriptionsPagedResponse listSubscriptions() throws Exception { + try (SubscriberClient subscriberClient = SubscriberClient.create()) { + // [START listSubscriptions] + ListSubscriptionsRequest listSubscriptionsRequest = + ListSubscriptionsRequest.newBuilder() + .setProjectWithProjectName(ProjectName.create(projectId)) + .build(); + ListSubscriptionsPagedResponse response = + subscriberClient.listSubscriptions(listSubscriptionsRequest); + Iterable subscriptions = response.iterateAllElements(); + for (Subscription subscription : subscriptions) { + // do something with the subscription + } + // [END listSubscriptions] + return response; + } + } + + /** Example of deleting a subscription. */ + public SubscriptionName deleteSubscription(String subscriptionId) throws Exception { + try (SubscriberClient subscriberClient = SubscriberClient.create()) { + // [START deleteSubscription] + SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId); + subscriberClient.deleteSubscription(subscriptionName); + // [END deleteSubscription] + return subscriptionName; + } + } + + /** Example of getting a subscription policy. */ + public Policy getSubscriptionPolicy(String subscriptionId) throws Exception { + try (SubscriberClient subscriberClient = SubscriberClient.create()) { + // [START getSubscriptionPolicy] + SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId); + Policy policy = subscriberClient.getIamPolicy(subscriptionName.toString()); + if (policy == null) { + // subscription was not found + } + // [END getSubscriptionPolicy] + return policy; + } + } + + /** Example of replacing a subscription policy. */ + public Policy replaceSubscriptionPolicy(String subscriptionId) throws Exception { + try (SubscriberClient subscriberClient = SubscriberClient.create()) { + // [START replaceSubscriptionPolicy] + SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId); + Policy policy = subscriberClient.getIamPolicy(subscriptionName.toString()); + // Create a role => members binding + Binding binding = + Binding.newBuilder() + .setRole(Role.viewer().toString()) + .addMembers(Identity.allAuthenticatedUsers().toString()) + .build(); + //Update policy + Policy updatedPolicy = policy.toBuilder().addBindings(binding).build(); + + updatedPolicy = subscriberClient.setIamPolicy(subscriptionName.toString(), updatedPolicy); + // [END replaceSubscriptionPolicy] + return updatedPolicy; + } + } + + /** Example of testing whether the caller has the provided permissions on a subscription. */ + public TestIamPermissionsResponse testSubscriptionPermissions(String subscriptionId) + throws Exception { + try (PublisherClient publisherClient = PublisherClient.create()) { + // [START testSubscriptionPermissions] + List permissions = new LinkedList<>(); + permissions.add("pubsub.subscriptions.get"); + SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId); + TestIamPermissionsResponse testedPermissions = + publisherClient.testIamPermissions(subscriptionName.toString(), permissions); + // [END testSubscriptionPermissions] + return testedPermissions; + } + } + + /** Example of getting a subscription. */ + public Subscription getSubscription(String subscriptionId) throws Exception { + try (SubscriberClient subscriberClient = SubscriberClient.create()) { + // [START getSubscription] + SubscriptionName subscriptionName = SubscriptionName.create(projectId, subscriptionId); + Subscription subscription = subscriberClient.getSubscription(subscriptionName); + // [END getSubscription] + return subscription; + } + } +} diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberSnippets.java index 8ca753fc266e..167e1bb11fa1 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/pubsub/snippets/SubscriberSnippets.java @@ -17,7 +17,7 @@ /* * EDITING INSTRUCTIONS * This file is referenced in Subscriber's javadoc. Any change to this file should be reflected in - * PubSub's javadoc. + * Subscriber's javadoc. */ package com.google.cloud.examples.pubsub.snippets; @@ -28,6 +28,7 @@ import com.google.pubsub.v1.SubscriptionName; import java.util.concurrent.Executor; +/** This class contains snippets for the {@link Subscriber} interface. */ public class SubscriberSnippets { private final SubscriptionName subscription; diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/Cleanup.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/Cleanup.java new file mode 100644 index 000000000000..c9911fd392a3 --- /dev/null +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/Cleanup.java @@ -0,0 +1,59 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.examples.pubsub.snippets; + +import com.google.cloud.pubsub.spi.v1.PublisherClient; +import com.google.cloud.pubsub.spi.v1.SubscriberClient; +import com.google.pubsub.v1.SubscriptionName; +import com.google.pubsub.v1.TopicName; + +class Cleanup { + + protected static void deleteTestTopicsAndSubscriptions( + String projectId, String[] topics, String[] subscriptions) throws Exception { + deleteTestTopics(projectId, topics); + deleteTestSubscriptions(projectId, subscriptions); + } + + private static void deleteTestTopics(String projectId, String[] testTopics) throws Exception { + try (PublisherClient publisherClient = PublisherClient.create()) { + for (String topicId : testTopics) { + try { + publisherClient.deleteTopic(TopicName.create(projectId, topicId)); + System.out.println("Topic deleted : " + topicId); + } catch (Exception e) { + //do nothing catch clause + } + } + } + } + + private static void deleteTestSubscriptions(String projectId, String[] subscriptions) + throws Exception { + try (SubscriberClient subscriberClient = SubscriberClient.create()) { + for (String subscriptionId : subscriptions) { + try { + subscriberClient.deleteSubscription( + SubscriptionName.create(projectId, subscriptionId)); + System.out.println("Subscription deleted : " + subscriptionId); + } catch (Exception e) { + //do nothing catch clause + } + } + } + } +} diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITPublisherClientSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITPublisherClientSnippets.java new file mode 100644 index 000000000000..d607a1568d45 --- /dev/null +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITPublisherClientSnippets.java @@ -0,0 +1,183 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.examples.pubsub.snippets; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import com.google.api.gax.grpc.ApiException; +import com.google.cloud.Identity; +import com.google.cloud.Role; +import com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicSubscriptionsPagedResponse; +import com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListTopicsPagedResponse; +import com.google.cloud.pubsub.spi.v1.SubscriberClient; +import com.google.common.collect.Iterables; +import com.google.iam.v1.Policy; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.pubsub.v1.PushConfig; +import com.google.pubsub.v1.Subscription; +import com.google.pubsub.v1.SubscriptionName; +import com.google.pubsub.v1.Topic; +import com.google.pubsub.v1.TopicName; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.Timeout; + +public class ITPublisherClientSnippets { + + private static final String NAME_SUFFIX = UUID.randomUUID().toString(); + + private static String projectId; + + private static PublisherClientSnippets publisherClientSnippets; + + private static String[] topics = { + formatForTest("topic-1"), + formatForTest("topic-2"), + }; + private static String[] subscriptions = { + formatForTest("subscription-1"), + formatForTest("subscription-2") + }; + + @Rule + public Timeout globalTimeout = Timeout.seconds(300); + + private static String formatForTest(String resourceName) { + return resourceName + "-" + NAME_SUFFIX; + } + + @BeforeClass + public static void beforeClass() { + publisherClientSnippets = new PublisherClientSnippets(); + projectId = publisherClientSnippets.getProjectId(); + } + + @Before + public void setUp() throws Exception { + Cleanup.deleteTestTopicsAndSubscriptions(projectId, topics, subscriptions); + } + + @Test + public void topicAddedIsSameAsRetrieved() throws Exception { + String topicName = topics[0]; + Topic topicAdded = publisherClientSnippets.createTopic(topicName); + assertNotNull(topicAdded); + Topic topicRetrieved = publisherClientSnippets.getTopic(topicName); + assertEquals(topicAdded, topicRetrieved); + } + + @Test + public void listTopicsRetreivesAddedTopics() throws Exception { + List addedTopics = new ArrayList<>(); + String topicName1 = topics[0]; + addedTopics.add(publisherClientSnippets.createTopic(topicName1)); + String topicName2 = topics[1]; + addedTopics.add(publisherClientSnippets.createTopic(topicName2)); + + boolean[] topicFound = {false, false}; + ListTopicsPagedResponse response = publisherClientSnippets.listTopics(); + + assertNotNull(response); + Iterable topics = response.iterateAllElements(); + for (int i = 0; i < 2; i++) { + if (!topicFound[i]) { + topicFound[i] = Iterables.contains(topics, addedTopics.get(i)); + } + } + + assertTrue(topicFound[0] && topicFound[1]); + } + + @Test + public void listTopicSubscriptionsRetrievesAddedSubscriptions() throws Exception { + List addedSubscriptions = new ArrayList<>(); + String topicName1 = topics[0]; + publisherClientSnippets.createTopic(topicName1); + String subscriptionName1 = subscriptions[0]; + String subscriptionName2 = subscriptions[1]; + addedSubscriptions.add(createSubscription(topicName1, subscriptionName1)); + addedSubscriptions.add(createSubscription(topicName1, subscriptionName2)); + + boolean[] subFound = {false, false}; + + ListTopicSubscriptionsPagedResponse response = + publisherClientSnippets.listTopicSubscriptions(topicName1); + + + assertNotNull(response); + Iterable subscriptions = response.iterateAllElements(); + for (int i = 0; i < 2; i++) { + if (!subFound[i]) { + subFound[i] = Iterables.contains(subscriptions, addedSubscriptions.get(i)); + } + } + assertTrue(subFound[0] && subFound[1]); + } + + @Test(expected = ApiException.class) + public void deletedTopicIsNotRetrievableAndThrowsException() throws Exception { + String topicName = topics[0]; + Topic topicAdded = publisherClientSnippets.createTopic(topicName); + assertNotNull(topicAdded); + TopicName formattedName = publisherClientSnippets.deleteTopic(topicName); + assertNotNull(formattedName); + publisherClientSnippets.getTopic(topicName); + } + + @Test + public void topicPolicyIsCorrectlyRetrieved() throws Exception { + String topicName = topics[0]; + publisherClientSnippets.createTopic(topicName); + Policy policy = publisherClientSnippets.getTopicPolicy(topicName); + assertNotNull(policy); + } + + @Test + public void replaceTopicPolicyAndTestPermissionsIsSuccessful() throws Exception { + String topicName = topics[0]; + publisherClientSnippets.createTopic(topicName); + Policy policy = publisherClientSnippets.replaceTopicPolicy(topicName); + assertNotNull(policy.getBindingsCount()); + assertTrue(policy.getBindings(0).getRole().equalsIgnoreCase(Role.viewer().toString())); + assertTrue(policy.getBindings(0).getMembers(0) + .equalsIgnoreCase(Identity.allAuthenticatedUsers().toString())); + TestIamPermissionsResponse response = publisherClientSnippets.testTopicPermissions(topicName); + assertTrue(response.getPermissionsList().contains("pubsub.topics.get")); + } + + private String createSubscription(String topic, String subscriptionName) throws Exception { + try (SubscriberClient subscriberClient = SubscriberClient.create()) { + Subscription subscription = subscriberClient.createSubscription( + SubscriptionName.create(projectId, subscriptionName), + TopicName.create(projectId, topic), PushConfig.getDefaultInstance(), 0); + return subscription.getName(); + } + } + + @After + public void tearDown() throws Exception { + Cleanup.deleteTestTopicsAndSubscriptions(projectId, topics, subscriptions); + } +} diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriberClientSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriberClientSnippets.java new file mode 100644 index 000000000000..50fc5b52ac93 --- /dev/null +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/pubsub/snippets/ITSubscriberClientSnippets.java @@ -0,0 +1,208 @@ +/* + * Copyright 2017 Google Inc. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.cloud.examples.pubsub.snippets; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +import com.google.api.gax.grpc.ApiException; +import com.google.cloud.Identity; +import com.google.cloud.Role; +import com.google.cloud.pubsub.spi.v1.PagedResponseWrappers.ListSubscriptionsPagedResponse; +import com.google.cloud.pubsub.spi.v1.Publisher; +import com.google.cloud.pubsub.spi.v1.PublisherClient; +import com.google.common.collect.Iterables; +import com.google.iam.v1.Policy; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.ByteString; +import com.google.pubsub.v1.PubsubMessage; +import com.google.pubsub.v1.PullResponse; +import com.google.pubsub.v1.ReceivedMessage; +import com.google.pubsub.v1.Subscription; +import com.google.pubsub.v1.TopicName; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.Timeout; + +public class ITSubscriberClientSnippets { + + private static final String NAME_SUFFIX = UUID.randomUUID().toString(); + + private static String projectId; + + private static SubscriberClientSnippets subscriberClientSnippets; + + private static String[] topics = { + formatForTest("topic-1"), + formatForTest("topic-2"), + }; + private static String[] subscriptions = { + formatForTest("subscription-1"), + formatForTest("subscription-2") + }; + + @Rule + public Timeout globalTimeout = Timeout.seconds(300); + + private static String formatForTest(String resourceName) { + return resourceName + "-" + NAME_SUFFIX; + } + + @BeforeClass + public static void beforeClass() { + subscriberClientSnippets = new SubscriberClientSnippets(); + projectId = subscriberClientSnippets.getProjectId(); + } + + @Before + public void setUp() throws Exception { + Cleanup.deleteTestTopicsAndSubscriptions(projectId, topics, subscriptions); + } + + private Subscription createSubscription(String topicName, String subscriptionName) + throws Exception { + createTopic(topicName); + Subscription subscription = + subscriberClientSnippets.createSubscription(topicName, subscriptionName); + assertNotNull(subscription); + Subscription retrievedSubscription = subscriberClientSnippets.getSubscription(subscriptionName); + assertNotNull(retrievedSubscription); + assertEquals(subscription.getName(), retrievedSubscription.getName()); + return subscription; + } + + @Test + public void publishAndPullMessagesIsSuccessful() throws Exception { + String topicName = topics[0]; + String subscriptionName = subscriptions[0]; + createSubscription(topicName, subscriptionName); + Set messages = publishMessages(topicName, 5); + //pulls max 100 messages + PullResponse response = subscriberClientSnippets.pull(subscriptionName); + assertNotNull(response); + //remove messages that match sent + for (ReceivedMessage receivedMessage : response.getReceivedMessagesList()) { + String message = receivedMessage.getMessage().getData().toStringUtf8(); + if (messages.contains(message)) { + messages.remove(message); + } + } + //all messages published were received + assertTrue(messages.isEmpty()); + } + + @Test + public void replacePushConfigIsSuccessful() throws Exception { + String topicName = topics[0]; + String subscriptionName = subscriptions[0]; + createSubscription(topicName, subscriptionName); + String endpoint = "https://" + projectId + ".appspot.com/push"; + subscriberClientSnippets.replacePushConfig(subscriptionName, endpoint); + Subscription subscription = subscriberClientSnippets.getSubscription(subscriptionName); + assertNotNull(subscription.getPushConfig()); + assertEquals(subscription.getPushConfig().getPushEndpoint(), endpoint); + } + + @Test + public void listSubscriptionsRetrievesAllAddedSubscriptions() throws Exception { + List addedSubscriptions = new ArrayList<>(); + String topicName1 = topics[0]; + String subscriptionName1 = subscriptions[0]; + String topicName2 = topics[1]; + String subscriptionName2 = subscriptions[1]; + addedSubscriptions.add(createSubscription(topicName1, subscriptionName1)); + addedSubscriptions.add(createSubscription(topicName2, subscriptionName2)); + + boolean[] subFound = {false, false}; + ListSubscriptionsPagedResponse response = subscriberClientSnippets.listSubscriptions(); + assertNotNull(response); + Iterable subscriptions = response.iterateAllElements(); + for (int i = 0; i < 2; i++) { + if (!subFound[i]) { + subFound[i] = Iterables.contains(subscriptions, addedSubscriptions.get(i)); + } + } + assertTrue(subFound[0] && subFound[1]); + } + + @Test(expected = ApiException.class) + public void deleteSubscriptionThrowsExceptionWhenRetrieved() throws Exception { + String topicName = topics[0]; + String subscriptionName = subscriptions[0]; + createSubscription(topicName, subscriptionName); + subscriberClientSnippets.deleteSubscription(subscriptionName); + //expected to throw exception on retrieval + subscriberClientSnippets.getSubscription(subscriptionName); + } + + @Test + public void subscriptionHasValidIamPolicy() throws Exception { + String topicName = topics[0]; + String subscriptionName = subscriptions[0]; + createSubscription(topicName, subscriptionName); + Policy policy = subscriberClientSnippets.getSubscriptionPolicy(subscriptionName); + assertNotNull(policy); + } + + @Test + public void replaceSubscriptionPolicyAndTestPermissionsIsSuccessful() throws Exception { + String topicName = topics[0]; + String subscriptionName = subscriptions[0]; + createSubscription(topicName, subscriptionName); + Policy policy = subscriberClientSnippets.replaceSubscriptionPolicy(subscriptionName); + assertNotNull(policy.getBindingsCount()); + assertTrue(policy.getBindings(0).getRole().equalsIgnoreCase(Role.viewer().toString())); + assertTrue(policy.getBindings(0).getMembers(0) + .equalsIgnoreCase(Identity.allAuthenticatedUsers().toString())); + TestIamPermissionsResponse response = + subscriberClientSnippets.testSubscriptionPermissions(subscriptionName); + assertTrue(response.getPermissionsList().contains("pubsub.subscriptions.get")); + } + + private void createTopic(String name) throws Exception { + try (PublisherClient publisherClient = PublisherClient.create()) { + publisherClient.createTopic(TopicName.create(projectId, name)); + } + } + + private Set publishMessages(String topicName, int numMessages) throws Exception { + Set messages = new HashSet<>(); + Publisher publisher = Publisher.newBuilder(TopicName.create(projectId, topicName)).build(); + for (int i = 1; i<= numMessages; i++) { + String message = formatForTest("message-" + i); + PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData( + ByteString.copyFromUtf8(message)).build(); + publisher.publish(pubsubMessage); + messages.add(message); + } + return messages; + } + + @After + public void tearDown() throws Exception { + Cleanup.deleteTestTopicsAndSubscriptions(projectId, topics, subscriptions); + } +}