/** * Adds one or more messages to the topic. Returns `NOT_FOUND` if the topic does not exist. * * <p>Sample code: * * <pre><code> * try (TopicAdminClient topicAdminClient = TopicAdminClient.create()) { * ProjectTopicName topic = ProjectTopicName.of("[PROJECT]", "[TOPIC]"); * ByteString data = ByteString.copyFromUtf8(""); * PubsubMessage messagesElement = PubsubMessage.newBuilder() * .setData(data) * .build(); * List<PubsubMessage> messages = Arrays.asList(messagesElement); * PublishResponse response = topicAdminClient.publish(topic.toString(), messages); * } * </code></pre> * * @param topic The messages in the request will be published on this topic. Format is * `projects/{project}/topics/{topic}`. * @param messages The messages to publish. * @throws com.google.api.gax.rpc.ApiException if the remote call fails */ /* package-private */ final PublishResponse publish(String topic, List<PubsubMessage> messages) { PublishRequest request = PublishRequest.newBuilder().setTopic(topic).addAllMessages(messages).build(); return publish(request); }
.addAllMessages(messages) .build(); return publish(request);
@Test @SuppressWarnings("all") public void publishExceptionTest() throws Exception { StatusRuntimeException exception = new StatusRuntimeException(Status.INVALID_ARGUMENT); mockPublisher.addException(exception); try { ProjectTopicName topic = ProjectTopicName.of("[PROJECT]", "[TOPIC]"); ByteString data = ByteString.copyFromUtf8("-86"); PubsubMessage messagesElement = PubsubMessage.newBuilder().setData(data).build(); List<PubsubMessage> messages = Arrays.asList(messagesElement); client.publish(topic, messages); Assert.fail("No exception raised"); } catch (InvalidArgumentException e) { // Expected exception } }
@Test @SuppressWarnings("all") public void publishTest() { String messageIdsElement = "messageIdsElement-744837059"; List<String> messageIds = Arrays.asList(messageIdsElement); PublishResponse expectedResponse = PublishResponse.newBuilder().addAllMessageIds(messageIds).build(); mockPublisher.addResponse(expectedResponse); ProjectTopicName topic = ProjectTopicName.of("[PROJECT]", "[TOPIC]"); ByteString data = ByteString.copyFromUtf8("-86"); PubsubMessage messagesElement = PubsubMessage.newBuilder().setData(data).build(); List<PubsubMessage> messages = Arrays.asList(messagesElement); PublishResponse actualResponse = client.publish(topic, messages); Assert.assertEquals(expectedResponse, actualResponse); List<GeneratedMessageV3> actualRequests = mockPublisher.getRequests(); Assert.assertEquals(1, actualRequests.size()); PublishRequest actualRequest = (PublishRequest) actualRequests.get(0); Assert.assertEquals(topic, ProjectTopicName.parse(actualRequest.getTopic())); Assert.assertEquals(messages, actualRequest.getMessagesList()); Assert.assertTrue( channelProvider.isHeaderSent( ApiClientHeaderProvider.getDefaultApiClientHeaderKey(), GaxGrpcProperties.getDefaultApiClientHeaderPattern())); }