Search in sources :

Example 1 with ApiFuture

use of com.google.api.core.ApiFuture in project google-cloud-java by GoogleCloudPlatform.

the class CreateTopicAndPublishMessages method publishMessages.

public static void publishMessages() throws Exception {
    // [START pubsub_publish]
    TopicName topicName = TopicName.create("my-project-id", "my-topic-id");
    Publisher publisher = null;
    List<ApiFuture<String>> messageIdFutures = new ArrayList<>();
    try {
        // Create a publisher instance with default settings bound to the topic
        publisher = Publisher.defaultBuilder(topicName).build();
        List<String> messages = Arrays.asList("first message", "second message");
        // schedule publishing one message at a time : messages get automatically batched
        for (String message : messages) {
            ByteString data = ByteString.copyFromUtf8(message);
            PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).build();
            // Once published, returns a server-assigned message id (unique within the topic)
            ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
            messageIdFutures.add(messageIdFuture);
        }
    } finally {
        // wait on any pending publish requests.
        List<String> messageIds = ApiFutures.allAsList(messageIdFutures).get();
        for (String messageId : messageIds) {
            System.out.println("published with message ID: " + messageId);
        }
        if (publisher != null) {
            // When finished with the publisher, shutdown to free up resources.
            publisher.shutdown();
        }
    }
// [END pubsub_publish]
}
Also used : ApiFuture(com.google.api.core.ApiFuture) ByteString(com.google.protobuf.ByteString) ArrayList(java.util.ArrayList) Publisher(com.google.cloud.pubsub.spi.v1.Publisher) ByteString(com.google.protobuf.ByteString) PubsubMessage(com.google.pubsub.v1.PubsubMessage) TopicName(com.google.pubsub.v1.TopicName)

Example 2 with ApiFuture

use of com.google.api.core.ApiFuture in project java-docs-samples by GoogleCloudPlatform.

the class QueryDataSnippets method prepareExamples.

/**
 * Creates cities collection and add sample documents to test queries.
 *
 * @return collection reference
 */
void prepareExamples() throws Exception {
    // [START fs_query_create_examples]
    CollectionReference cities = db.collection("cities");
    List<ApiFuture<WriteResult>> futures = new ArrayList<>();
    futures.add(cities.document("SF").set(new City("San Francisco", "CA", "USA", false, 860000L)));
    futures.add(cities.document("LA").set(new City("Los Angeles", "CA", "USA", false, 3900000L)));
    futures.add(cities.document("DC").set(new City("Washington D.C.", null, "USA", true, 680000L)));
    futures.add(cities.document("TOK").set(new City("Tokyo", null, "Japan", true, 9000000L)));
    futures.add(cities.document("BJ").set(new City("Beijing", null, "China", true, 21500000L)));
    // (optional) block on documents successfully added
    ApiFutures.allAsList(futures).get();
// [END fs_query_create_examples]
}
Also used : ApiFuture(com.google.api.core.ApiFuture) ArrayList(java.util.ArrayList) City(com.example.firestore.snippets.model.City) CollectionReference(com.google.cloud.firestore.CollectionReference)

Example 3 with ApiFuture

use of com.google.api.core.ApiFuture in project divolte-collector by divolte.

the class GoogleCloudPubSubFlusher method sendBatch.

@Override
protected ImmutableList<PubsubMessage> sendBatch(final List<PubsubMessage> batch) throws InterruptedException {
    // For Pub/Sub we assume the following:
    // - Batching behaviour is set to flush everything ASAP.
    // - Retry behaviour will retry indefinitely, so long as it seems likely to succeed.
    // First start sending the messages.
    // (This will serialize them, determine the partition and then assign them to a per-partition buffer.)
    final int batchSize = batch.size();
    final List<ApiFuture<String>> sendResults = batch.stream().map(publisher::publish).collect(Collectors.toCollection(() -> new ArrayList<>(batchSize)));
    // At this point the messages are in flight, and we assume being flushed.
    // When they eventually complete, each message can be in one of several states:
    // - Completed.
    // - An error occurred, but a retry may succeed.
    // - A fatal error occurred.
    final ImmutableList.Builder<PubsubMessage> remaining = ImmutableList.builder();
    for (int i = 0; i < batchSize; ++i) {
        final ApiFuture<String> pendingResult = sendResults.get(i);
        try {
            final String messageId = pendingResult.get();
            if (logger.isDebugEnabled()) {
                final PubsubMessage message = batch.get(i);
                logger.debug("Finished sending event (partyId={}) to Pub/Sub: messageId = {}", message.getAttributesOrThrow(MESSAGE_ATTRIBUTE_PARTYID), messageId);
            }
        } catch (final ExecutionException e) {
            final PubsubMessage message = batch.get(i);
            // The Pub/Sub publisher internally has a retry policy, but outside that we also
            // retry indefinitely unless it's a cause that we don't understand.
            final Throwable cause = e.getCause();
            if (cause instanceof ApiException) {
                final ApiException apiException = (ApiException) cause;
                if (apiException.isRetryable()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Transient error sending event (partyId=" + message.getAttributesOrThrow(MESSAGE_ATTRIBUTE_PARTYID) + ") to Pub/Sub; retrying.", cause);
                    }
                    remaining.add(message);
                } else {
                    logger.warn("Permanent error sending event (partyId=" + message.getAttributesOrThrow(MESSAGE_ATTRIBUTE_PARTYID) + ") to Pub/Sub; abandoning.", cause);
                }
            } else {
                logger.error("Unknown error sending event (partyId=" + message.getAttributesOrThrow(MESSAGE_ATTRIBUTE_PARTYID) + ") to Pub/Sub; abandoning.", cause);
            }
        }
    }
    return remaining.build();
}
Also used : ApiFuture(com.google.api.core.ApiFuture) ImmutableList(com.google.common.collect.ImmutableList) ByteString(com.google.protobuf.ByteString) ExecutionException(java.util.concurrent.ExecutionException) PubsubMessage(com.google.pubsub.v1.PubsubMessage) ApiException(com.google.api.gax.rpc.ApiException)

Example 4 with ApiFuture

use of com.google.api.core.ApiFuture in project java-docs-samples by GoogleCloudPlatform.

the class RetrieveDataSnippets method prepareExamples.

/**
 * Create cities collection and add sample documents.
 */
void prepareExamples() throws Exception {
    // [START fs_retrieve_create_examples]
    CollectionReference cities = db.collection("cities");
    List<ApiFuture<WriteResult>> futures = new ArrayList<>();
    futures.add(cities.document("SF").set(new City("San Francisco", "CA", "USA", false, 860000L)));
    futures.add(cities.document("LA").set(new City("Los Angeles", "CA", "USA", false, 3900000L)));
    futures.add(cities.document("DC").set(new City("Washington D.C.", null, "USA", true, 680000L)));
    futures.add(cities.document("TOK").set(new City("Tokyo", null, "Japan", true, 9000000L)));
    futures.add(cities.document("BJ").set(new City("Beijing", null, "China", true, 21500000L)));
    // (optional) block on operation
    ApiFutures.allAsList(futures).get();
// [END fs_retrieve_create_examples]
}
Also used : ApiFuture(com.google.api.core.ApiFuture) ArrayList(java.util.ArrayList) City(com.example.firestore.snippets.model.City) CollectionReference(com.google.cloud.firestore.CollectionReference)

Example 5 with ApiFuture

use of com.google.api.core.ApiFuture in project beam by apache.

the class TestPubsub method publish.

/**
 * Publish messages to {@link #topicPath()}.
 */
public void publish(List<PubsubMessage> messages) {
    Preconditions.checkNotNull(eventsTopicPath);
    Publisher eventPublisher;
    try {
        eventPublisher = Publisher.newBuilder(eventsTopicPath.getPath()).setCredentialsProvider(pipelineOptions::getGcpCredential).setChannelProvider(channelProvider).setEndpoint(pubsubEndpoint).build();
    } catch (IOException e) {
        throw new RuntimeException("Error creating event publisher", e);
    }
    List<ApiFuture<String>> futures = messages.stream().map((message) -> {
        com.google.pubsub.v1.PubsubMessage.Builder builder = com.google.pubsub.v1.PubsubMessage.newBuilder().setData(ByteString.copyFrom(message.getPayload())).putAllAttributes(message.getAttributeMap());
        return eventPublisher.publish(builder.build());
    }).collect(Collectors.toList());
    try {
        ApiFutures.allAsList(futures).get();
    } catch (ExecutionException e) {
        throw new RuntimeException("Error publishing a test message", e);
    } catch (InterruptedException e) {
        throw new RuntimeException("Interrupted while waiting for messages to publish", e);
    }
    eventPublisher.shutdown();
}
Also used : Statement(org.junit.runners.model.Statement) TopicPath(org.apache.beam.sdk.io.gcp.pubsub.PubsubClient.TopicPath) TestPipelineOptions(org.apache.beam.sdk.testing.TestPipelineOptions) ManagedChannel(io.grpc.ManagedChannel) TestRule(org.junit.rules.TestRule) Duration(org.joda.time.Duration) TimeoutException(java.util.concurrent.TimeoutException) Subscriber(com.google.cloud.pubsub.v1.Subscriber) Streams(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Streams) AckReplyConsumer(com.google.cloud.pubsub.v1.AckReplyConsumer) Publisher(com.google.cloud.pubsub.v1.Publisher) Seconds(org.joda.time.Seconds) FixedTransportChannelProvider(com.google.api.gax.rpc.FixedTransportChannelProvider) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) TestPipeline(org.apache.beam.sdk.testing.TestPipeline) Iterables(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Iterables) SubscriptionAdminClient(com.google.cloud.pubsub.v1.SubscriptionAdminClient) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) PipelineOptions(org.apache.beam.sdk.options.PipelineOptions) Nullable(org.checkerframework.checker.nullness.qual.Nullable) DateTimeFormat(org.joda.time.format.DateTimeFormat) MessageReceiver(com.google.cloud.pubsub.v1.MessageReceiver) ApiFutures(com.google.api.core.ApiFutures) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) SubscriptionPath(org.apache.beam.sdk.io.gcp.pubsub.PubsubClient.SubscriptionPath) DateTime(org.joda.time.DateTime) IOException(java.io.IOException) BlockingQueue(java.util.concurrent.BlockingQueue) Description(org.junit.runner.Description) TopicAdminSettings(com.google.cloud.pubsub.v1.TopicAdminSettings) Collectors(java.util.stream.Collectors) ApiFuture(com.google.api.core.ApiFuture) ByteString(com.google.protobuf.ByteString) ExecutionException(java.util.concurrent.ExecutionException) GrpcTransportChannel(com.google.api.gax.grpc.GrpcTransportChannel) ManagedChannelBuilder(io.grpc.ManagedChannelBuilder) List(java.util.List) Matchers.containsInAnyOrder(org.hamcrest.Matchers.containsInAnyOrder) TransportChannelProvider(com.google.api.gax.rpc.TransportChannelProvider) TopicAdminClient(com.google.cloud.pubsub.v1.TopicAdminClient) Preconditions(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions) Matcher(org.hamcrest.Matcher) Instant(org.joda.time.Instant) LinkedBlockingDeque(java.util.concurrent.LinkedBlockingDeque) SubscriptionAdminSettings(com.google.cloud.pubsub.v1.SubscriptionAdminSettings) PushConfig(com.google.pubsub.v1.PushConfig) ApiFuture(com.google.api.core.ApiFuture) ManagedChannelBuilder(io.grpc.ManagedChannelBuilder) Publisher(com.google.cloud.pubsub.v1.Publisher) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException)

Aggregations

ApiFuture (com.google.api.core.ApiFuture)6 ByteString (com.google.protobuf.ByteString)3 ExecutionException (java.util.concurrent.ExecutionException)3 City (com.example.firestore.snippets.model.City)2 CollectionReference (com.google.cloud.firestore.CollectionReference)2 ArrayList (java.util.ArrayList)2 List (java.util.List)2 TimeoutException (java.util.concurrent.TimeoutException)2 Collectors (java.util.stream.Collectors)2 ApiFutures (com.google.api.core.ApiFutures)1 GrpcTransportChannel (com.google.api.gax.grpc.GrpcTransportChannel)1 ApiException (com.google.api.gax.rpc.ApiException)1 FixedTransportChannelProvider (com.google.api.gax.rpc.FixedTransportChannelProvider)1 TransportChannelProvider (com.google.api.gax.rpc.TransportChannelProvider)1 QueryDocumentSnapshot (com.google.cloud.firestore.QueryDocumentSnapshot)1 QuerySnapshot (com.google.cloud.firestore.QuerySnapshot)1 Publisher (com.google.cloud.pubsub.spi.v1.Publisher)1 AckReplyConsumer (com.google.cloud.pubsub.v1.AckReplyConsumer)1 MessageReceiver (com.google.cloud.pubsub.v1.MessageReceiver)1 Publisher (com.google.cloud.pubsub.v1.Publisher)1