Search in sources :

Example 26 with Publisher

use of com.google.cloud.pubsub.v1.Publisher in project google-cloud-java by GoogleCloudPlatform.

the class UsePubSubEmulatorSnippet method main.

public static void main(String... args) throws IOException {
    // [START pubsub_use_emulator]
    String hostport = System.getenv("PUBSUB_EMULATOR_HOST");
    ManagedChannel channel = ManagedChannelBuilder.forTarget(hostport).usePlaintext().build();
    try {
        TransportChannelProvider channelProvider = FixedTransportChannelProvider.create(GrpcTransportChannel.create(channel));
        CredentialsProvider credentialsProvider = NoCredentialsProvider.create();
        // Set the channel and credentials provider when creating a `TopicAdminClient`.
        // Similarly for SubscriptionAdminClient
        TopicAdminClient topicClient = TopicAdminClient.create(TopicAdminSettings.newBuilder().setTransportChannelProvider(channelProvider).setCredentialsProvider(credentialsProvider).build());
        TopicName topicName = TopicName.of("my-project-id", "my-topic-id");
        // Set the channel and credentials provider when creating a `Publisher`.
        // Similarly for Subscriber
        Publisher publisher = Publisher.newBuilder(topicName).setChannelProvider(channelProvider).setCredentialsProvider(credentialsProvider).build();
    } finally {
        channel.shutdown();
    }
// [END pubsub_use_emulator]
}
Also used : TopicAdminClient(com.google.cloud.pubsub.v1.TopicAdminClient) ManagedChannel(io.grpc.ManagedChannel) CredentialsProvider(com.google.api.gax.core.CredentialsProvider) NoCredentialsProvider(com.google.api.gax.core.NoCredentialsProvider) Publisher(com.google.cloud.pubsub.v1.Publisher) FixedTransportChannelProvider(com.google.api.gax.rpc.FixedTransportChannelProvider) TransportChannelProvider(com.google.api.gax.rpc.TransportChannelProvider) TopicName(com.google.pubsub.v1.TopicName)

Example 27 with Publisher

use of com.google.cloud.pubsub.v1.Publisher 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)

Example 28 with Publisher

use of com.google.cloud.pubsub.v1.Publisher in project getting-started-java by GoogleCloudPlatform.

the class BackgroundContextListener method contextInitialized.

@Override
public void contextInitialized(ServletContextEvent event) {
    String firestoreProjectId = System.getenv("FIRESTORE_CLOUD_PROJECT");
    Firestore firestore = (Firestore) event.getServletContext().getAttribute("firestore");
    if (firestore == null) {
        firestore = FirestoreOptions.getDefaultInstance().toBuilder().setProjectId(firestoreProjectId).build().getService();
        event.getServletContext().setAttribute("firestore", firestore);
    }
    Translate translate = (Translate) event.getServletContext().getAttribute("translate");
    if (translate == null) {
        translate = TranslateOptions.getDefaultInstance().getService();
        event.getServletContext().setAttribute("translate", translate);
    }
    String topicId = System.getenv("PUBSUB_TOPIC");
    TopicName topicName = TopicName.of(firestoreProjectId, topicId);
    Publisher publisher = (Publisher) event.getServletContext().getAttribute("publisher");
    if (publisher == null) {
        try {
            publisher = Publisher.newBuilder(topicName).build();
            event.getServletContext().setAttribute("publisher", publisher);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Also used : Firestore(com.google.cloud.firestore.Firestore) Publisher(com.google.cloud.pubsub.v1.Publisher) IOException(java.io.IOException) Translate(com.google.cloud.translate.Translate) TopicName(com.google.pubsub.v1.TopicName)

Example 29 with Publisher

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

the class EmulatedFullTopologyTest method testFullTopology.

// ======================================================================================================
// IMPORTANT: This test makes use of things that happen in the emulated PubSub that
// are GUARANTEED to be different in the real Google hosted PubSub.
// So running these tests against the real thing will have a very high probability of
// failing.
// The assumptions:
// 1) The ordering of the messages is maintained.
// We are inserting a STOP_MARKER _after_ the set of test measurements and we assume this
// STOP event will
// arrive after the actual test data so we can stop the processing. In the real PubSub this
// is NOT true.
// 2) Exactly once: We assume that every message we put in comes out exactly once.
// In the real PubSub there are a lot of situations (mostly failure/retry) where this is not
// true.
@Test
public void testFullTopology() throws Exception {
    // ===============================================================================
    // Step 0: The test data
    List<String> input = new ArrayList<>(Arrays.asList("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"));
    List<String> messagesToSend = new ArrayList<>(input);
    // Now add some stream termination messages.
    // NOTE: Messages are pulled from PubSub in batches by the source.
    // So we need enough STOP_MARKERs to ensure ALL parallel tasks get at least one
    // STOP_MARKER
    // If not then at least one task will not terminate and the test will not end.
    // We pull 3 at a time, have 4 parallel: We need at least 12 STOP_MARKERS
    IntStream.rangeClosed(1, 20).forEach(i -> messagesToSend.add(STOP_MARKER));
    // IMPORTANT NOTE: This way of testing uses an effect of the PubSub emulator that is
    // absolutely
    // guaranteed NOT to work in the real PubSub: The ordering of the messages is maintained in
    // the topic.
    // So here we can assume that if we add a stop message LAST we can terminate the test stream
    // when we see it.
    // ===============================================================================
    // Step 1: We put test data into the topic
    // Publish the test messages into the input topic
    Publisher publisher = pubsubHelper.createPublisher(PROJECT_NAME, INPUT_TOPIC_NAME);
    for (String s : messagesToSend) {
        publisher.publish(PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8(s)).build()).get();
    }
    publisher.shutdown();
    // ===============================================================================
    // Step 2: Now we run our topology
    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    env.enableCheckpointing(100);
    env.setParallelism(4);
    env.setRestartStrategy(RestartStrategies.noRestart());
    // Silly topology
    env.addSource(// a self termination feature.
    PubSubSource.newBuilder().withDeserializationSchema(new SimpleStringSchemaWithStopMarkerDetection()).withProjectName(PROJECT_NAME).withSubscriptionName(INPUT_SUBSCRIPTION_NAME).withCredentials(EmulatorCredentials.getInstance()).withPubSubSubscriberFactory(new PubSubSubscriberFactoryForEmulator(getPubSubHostPort(), PROJECT_NAME, INPUT_SUBSCRIPTION_NAME, 1, Duration.ofSeconds(1), 3)).build()).map((MapFunction<String, String>) StringUtils::reverse).addSink(PubSubSink.newBuilder().withSerializationSchema(new SimpleStringSchema()).withProjectName(PROJECT_NAME).withTopicName(OUTPUT_TOPIC_NAME).withCredentials(EmulatorCredentials.getInstance()).withHostAndPortForEmulator(getPubSubHostPort()).build());
    env.execute("Running unit test");
    // ===============================================================================
    // Now we should have all the resulting data in the output topic.
    // Step 3: Get the result from the output topic and verify if everything is there
    List<ReceivedMessage> receivedMessages = pubsubHelper.pullMessages(PROJECT_NAME, OUTPUT_SUBSCRIPTION_NAME, 100);
    assertEquals("Wrong number of elements", input.size(), receivedMessages.size());
    // Check output strings
    List<String> output = new ArrayList<>();
    // Extract the actual Strings from the ReceivedMessages
    receivedMessages.forEach(msg -> output.add(msg.getMessage().getData().toStringUtf8()));
    for (String test : input) {
        String reversedTest = org.apache.commons.lang3.StringUtils.reverse(test);
        LOG.info("Checking if \"{}\" --> \"{}\" exists", test, reversedTest);
        assertTrue("Missing " + test, output.contains(reversedTest));
    }
// ===============================================================================
}
Also used : StringUtils(org.apache.commons.lang3.StringUtils) PubSubSubscriberFactoryForEmulator(org.apache.flink.streaming.connectors.gcp.pubsub.emulator.PubSubSubscriberFactoryForEmulator) ArrayList(java.util.ArrayList) SimpleStringSchema(org.apache.flink.api.common.serialization.SimpleStringSchema) StreamExecutionEnvironment(org.apache.flink.streaming.api.environment.StreamExecutionEnvironment) ByteString(com.google.protobuf.ByteString) Publisher(com.google.cloud.pubsub.v1.Publisher) MapFunction(org.apache.flink.api.common.functions.MapFunction) ReceivedMessage(com.google.pubsub.v1.ReceivedMessage) Test(org.junit.Test)

Example 30 with Publisher

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

the class EmulatedPubSubSourceTest method testFlinkSource.

// IMPORTANT: This test makes use of things that happen in the emulated PubSub that
// are GUARANTEED to be different in the real Google hosted PubSub.
// So running these tests against the real thing will have a very high probability of
// failing.
// The assumptions:
// 1) The ordering of the messages is maintained.
// We are inserting a STOP_MARKER _after_ the set of test measurements and we assume this
// STOP event will
// arrive after the actual test data so we can stop the processing. In the real PubSub this
// is NOT true.
// 2) Exactly once: We assume that every message we put in comes out exactly once.
// In the real PubSub there are a lot of situations (mostly failure/retry) where this is not
// true.
@Test
public void testFlinkSource() throws Exception {
    // Create some messages and put them into pubsub
    List<String> input = Arrays.asList("One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten");
    List<String> messagesToSend = new ArrayList<>(input);
    // Now add some stream termination messages.
    // NOTE: Messages are pulled from PubSub in batches by the source.
    // So we need enough STOP_MARKERs to ensure ALL parallel tasks get at least one
    // STOP_MARKER
    // If not then at least one task will not terminate and the test will not end.
    // We pull 3 at a time, have 4 parallel: We need at least 12 STOP_MARKERS
    IntStream.rangeClosed(1, 20).forEach(i -> messagesToSend.add(STOP_MARKER));
    // IMPORTANT NOTE: This way of testing uses an effect of the PubSub emulator that is
    // absolutely
    // guaranteed NOT to work in the real PubSub: The ordering of the messages is maintained in
    // the topic.
    // So here we can assume that if we add a stop message LAST we can terminate the test stream
    // when we see it.
    // Publish the messages into PubSub
    Publisher publisher = pubsubHelper.createPublisher(PROJECT_NAME, TOPIC_NAME);
    messagesToSend.forEach(s -> {
        try {
            publisher.publish(PubsubMessage.newBuilder().setData(ByteString.copyFromUtf8(s)).build()).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    });
    StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
    env.enableCheckpointing(100);
    env.setParallelism(4);
    env.setRestartStrategy(RestartStrategies.noRestart());
    DataStream<String> fromPubSub = env.addSource(PubSubSource.newBuilder().withDeserializationSchema(new SimpleStringSchemaWithStopMarkerDetection()).withProjectName(PROJECT_NAME).withSubscriptionName(SUBSCRIPTION_NAME).withCredentials(EmulatorCredentials.getInstance()).withPubSubSubscriberFactory(new PubSubSubscriberFactoryForEmulator(getPubSubHostPort(), PROJECT_NAME, SUBSCRIPTION_NAME, 10, Duration.ofSeconds(1), 3)).build()).name("PubSub source");
    List<String> output = new ArrayList<>();
    DataStreamUtils.collect(fromPubSub).forEachRemaining(output::add);
    assertEquals("Wrong number of elements", input.size(), output.size());
    for (String test : input) {
        assertTrue("Missing " + test, output.contains(test));
    }
}
Also used : PubSubSubscriberFactoryForEmulator(org.apache.flink.streaming.connectors.gcp.pubsub.emulator.PubSubSubscriberFactoryForEmulator) ArrayList(java.util.ArrayList) StreamExecutionEnvironment(org.apache.flink.streaming.api.environment.StreamExecutionEnvironment) ByteString(com.google.protobuf.ByteString) Publisher(com.google.cloud.pubsub.v1.Publisher) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Aggregations

Publisher (com.google.cloud.pubsub.v1.Publisher)25 PubsubMessage (com.google.pubsub.v1.PubsubMessage)18 ByteString (com.google.protobuf.ByteString)11 Test (org.junit.Test)11 Publisher (com.google.cloud.pubsub.spi.v1.Publisher)9 IOException (java.io.IOException)7 TopicName (com.google.pubsub.v1.TopicName)6 ProjectTopicName (com.google.pubsub.v1.ProjectTopicName)4 ArrayList (java.util.ArrayList)4 ApiException (com.google.api.gax.rpc.ApiException)3 Subscriber (com.google.cloud.pubsub.v1.Subscriber)3 ExecutionException (java.util.concurrent.ExecutionException)3 ServletException (javax.servlet.ServletException)3 ApiFuture (com.google.api.core.ApiFuture)2 CredentialsProvider (com.google.api.gax.core.CredentialsProvider)2 ExecutorProvider (com.google.api.gax.core.ExecutorProvider)2 FixedTransportChannelProvider (com.google.api.gax.rpc.FixedTransportChannelProvider)2 TransportChannelProvider (com.google.api.gax.rpc.TransportChannelProvider)2 TopicAdminClient (com.google.cloud.pubsub.v1.TopicAdminClient)2 ReceivedMessage (com.google.pubsub.v1.ReceivedMessage)2