Search in sources :

Example 16 with PubsubMessage

use of com.google.pubsub.v1.PubsubMessage in project java-docs-samples by GoogleCloudPlatform.

the class PubSubPublish method doPost.

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    Publisher publisher = this.publisher;
    try {
        String topicId = System.getenv("PUBSUB_TOPIC");
        // create a publisher on the topic
        if (publisher == null) {
            ProjectTopicName topicName = ProjectTopicName.newBuilder().setProject(ServiceOptions.getDefaultProjectId()).setTopic(topicId).build();
            publisher = Publisher.newBuilder(topicName).build();
        }
        // construct a pubsub message from the payload
        final String payload = req.getParameter("payload");
        PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8(payload)).build();
        publisher.publish(pubsubMessage);
        // redirect to home page
        resp.sendRedirect("/");
    } catch (Exception e) {
        resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}
Also used : Publisher(com.google.cloud.pubsub.v1.Publisher) ByteString(com.google.protobuf.ByteString) ProjectTopicName(com.google.pubsub.v1.ProjectTopicName) PubsubMessage(com.google.pubsub.v1.PubsubMessage) ServletException(javax.servlet.ServletException) IOException(java.io.IOException)

Example 17 with PubsubMessage

use of com.google.pubsub.v1.PubsubMessage in project java-docs-samples by GoogleCloudPlatform.

the class PublisherExample method main.

/**
 * Publish messages to a topic.
 * @param args topic name, number of messages
 */
public static void main(String... args) throws Exception {
    // topic id, eg. "my-topic"
    String topicId = args[0];
    int messageCount = Integer.parseInt(args[1]);
    ProjectTopicName topicName = ProjectTopicName.of(PROJECT_ID, topicId);
    Publisher publisher = null;
    try {
        // Create a publisher instance with default settings bound to the topic
        publisher = Publisher.newBuilder(topicName).build();
        for (int i = 0; i < messageCount; i++) {
            String message = "message-" + i;
            // convert message to bytes
            ByteString data = ByteString.copyFromUtf8(message);
            PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
            // schedule a message to be published, messages are automatically batched
            ApiFuture<String> future = publisher.publish(pubsubMessage);
            // add an asynchronous callback to handle success / failure
            ApiFutures.addCallback(future, new ApiFutureCallback<String>() {

                @Override
                public void onFailure(Throwable throwable) {
                    if (throwable instanceof ApiException) {
                        ApiException apiException = ((ApiException) throwable);
                        // details on the API exception
                        System.out.println(apiException.getStatusCode().getCode());
                        System.out.println(apiException.isRetryable());
                    }
                    System.out.println("Error publishing message : " + message);
                }

                @Override
                public void onSuccess(String messageId) {
                    // Once published, returns server-assigned message ids (unique within the topic)
                    System.out.println(messageId);
                }
            });
        }
    } finally {
        if (publisher != null) {
            // When finished with the publisher, shutdown to free up resources.
            publisher.shutdown();
        }
    }
}
Also used : ByteString(com.google.protobuf.ByteString) ByteString(com.google.protobuf.ByteString) ProjectTopicName(com.google.pubsub.v1.ProjectTopicName) Publisher(com.google.cloud.pubsub.v1.Publisher) PubsubMessage(com.google.pubsub.v1.PubsubMessage) ApiException(com.google.api.gax.rpc.ApiException)

Example 18 with PubsubMessage

use of com.google.pubsub.v1.PubsubMessage in project flink by apache.

the class CheckPubSubEmulatorTest method testPub.

@Test
public void testPub() throws Exception {
    List<PubsubMessage> receivedMessages = new ArrayList<>();
    Subscriber subscriber = pubsubHelper.subscribeToSubscription(PROJECT_NAME, SUBSCRIPTION_NAME, (message, consumer) -> {
        receivedMessages.add(message);
        consumer.ack();
    });
    subscriber.awaitRunning(5, MINUTES);
    Publisher publisher = pubsubHelper.createPublisher(PROJECT_NAME, TOPIC_NAME);
    publisher.publish(PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8("Hello World")).build()).get();
    LOG.info("Waiting a while to receive the message...");
    waitUntil(() -> receivedMessages.size() > 0);
    assertEquals(1, receivedMessages.size());
    assertEquals("Hello World", receivedMessages.get(0).getData().toStringUtf8());
    LOG.info("Received message. Shutting down ...");
    subscriber.stopAsync().awaitTerminated(5, MINUTES);
    publisher.shutdown();
}
Also used : Subscriber(com.google.cloud.pubsub.v1.Subscriber) ArrayList(java.util.ArrayList) Publisher(com.google.cloud.pubsub.v1.Publisher) PubsubMessage(com.google.pubsub.v1.PubsubMessage) Test(org.junit.Test)

Example 19 with PubsubMessage

use of com.google.pubsub.v1.PubsubMessage in project flink by apache.

the class PubSubSource method processMessage.

private void processMessage(SourceContext<OUT> sourceContext, List<ReceivedMessage> messages, PubSubCollector collector) throws Exception {
    rateLimiter.acquire(messages.size());
    synchronized (sourceContext.getCheckpointLock()) {
        for (ReceivedMessage message : messages) {
            acknowledgeOnCheckpoint.addAcknowledgeId(message.getAckId());
            PubsubMessage pubsubMessage = message.getMessage();
            deserializationSchema.deserialize(pubsubMessage, collector);
            if (collector.isEndOfStreamSignalled()) {
                cancel();
                return;
            }
        }
    }
}
Also used : ReceivedMessage(com.google.pubsub.v1.ReceivedMessage) PubsubMessage(com.google.pubsub.v1.PubsubMessage)

Example 20 with PubsubMessage

use of com.google.pubsub.v1.PubsubMessage in project flink by apache.

the class PubSubSink method invoke.

@Override
public void invoke(IN message, SinkFunction.Context context) {
    PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(ByteString.copyFrom(serializationSchema.serialize(message))).build();
    ApiFuture<String> future = publisher.publish(pubsubMessage);
    numPendingFutures.incrementAndGet();
    ApiFutures.addCallback(future, failureHandler, directExecutor());
}
Also used : ByteString(com.google.protobuf.ByteString) PubsubMessage(com.google.pubsub.v1.PubsubMessage)

Aggregations

PubsubMessage (com.google.pubsub.v1.PubsubMessage)51 ByteString (com.google.protobuf.ByteString)28 Test (org.junit.Test)26 ArrayList (java.util.ArrayList)15 Subscriber (com.google.cloud.pubsub.v1.Subscriber)12 List (java.util.List)12 AcknowledgeablePubsubMessage (org.springframework.cloud.gcp.pubsub.support.AcknowledgeablePubsubMessage)12 Publisher (com.google.cloud.pubsub.v1.Publisher)11 ConvertedAcknowledgeablePubsubMessage (org.springframework.cloud.gcp.pubsub.support.converter.ConvertedAcknowledgeablePubsubMessage)11 ProjectTopicName (com.google.pubsub.v1.ProjectTopicName)10 ProjectSubscriptionName (com.google.pubsub.v1.ProjectSubscriptionName)9 BasicAcknowledgeablePubsubMessage (org.springframework.cloud.gcp.pubsub.support.BasicAcknowledgeablePubsubMessage)9 ConvertedBasicAcknowledgeablePubsubMessage (org.springframework.cloud.gcp.pubsub.support.converter.ConvertedBasicAcknowledgeablePubsubMessage)9 SettableApiFuture (com.google.api.core.SettableApiFuture)8 ServiceOptions (com.google.cloud.ServiceOptions)8 DlpServiceClient (com.google.cloud.dlp.v2.DlpServiceClient)8 Action (com.google.privacy.dlp.v2.Action)8 BigQueryTable (com.google.privacy.dlp.v2.BigQueryTable)8 CreateDlpJobRequest (com.google.privacy.dlp.v2.CreateDlpJobRequest)8 DlpJob (com.google.privacy.dlp.v2.DlpJob)8