Java Code Examples for org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder

The following examples show how to use org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private Optional<PublisherBuilder<? extends Message<?>>> getAggregatedSource(
        List<PublisherBuilder<? extends Message<?>>> sources,
        String sourceName,
        AbstractMediator mediator,
        List<LazySource> lazy) {
    if (sources.isEmpty()) {
        return Optional.empty();
    }

    Merge.Mode merge = mediator.getConfiguration()
            .getMerge();
    if (merge != null) {
        LazySource lazySource = new LazySource(sourceName, merge);
        lazy.add(lazySource);
        return Optional.of(ReactiveStreams.fromPublisher(lazySource));
    }

    if (sources.size() > 1) {
        throw new WeavingException(sourceName, mediator.getMethodAsString(), sources.size());
    }
    return Optional.of(sources.get(0));

}
 
Example 2
@Test
public void testBlockingWhenProducingMessages() {
    addBeanClass(BeanReturningMessages.class);
    initialize();

    List<PublisherBuilder<? extends Message<?>>> producer = registry(container).getPublishers("infinite-producer");
    assertThat(producer).isNotEmpty();
    List<Integer> list = producer.get(0).map(Message::getPayload)
            .limit(5)
            .map(i -> (Integer) i)
            .toList().run().toCompletableFuture().join();
    assertThat(list).containsExactly(1, 2, 3, 4, 5);

    BeanReturningMessages bean = container.getBeanManager().createInstance().select(BeanReturningMessages.class).get();

    List<String> threadNames = bean.threads().stream().distinct().collect(Collectors.toList());
    assertThat(threadNames.contains(Thread.currentThread().getName())).isFalse();
    for (String name : threadNames) {
        assertThat(name.startsWith("vert.x-worker-thread-")).isTrue();
    }
}
 
Example 3
@Test
public void testSourceWithBinaryContent() {
    String topic = UUID.randomUUID().toString();
    Map<String, Object> config = getConfig(topic);
    provider = new AmqpConnector();
    provider.setup(executionHolder);

    List<Message<byte[]>> messages = new ArrayList<>();
    PublisherBuilder<? extends Message<?>> builder = provider.getPublisherBuilder(new MapBasedConfig(config));
    AtomicBoolean opened = new AtomicBoolean();

    builder.to(createSubscriber(messages, opened)).run();
    await().until(opened::get);

    await().until(() -> provider.isReady(config.get(CHANNEL_NAME_ATTRIBUTE).toString()));

    usage.produce(topic, 1, () -> AmqpMessage.create().withBufferAsBody(Buffer.buffer("foo".getBytes())).build());

    await().atMost(2, TimeUnit.MINUTES).until(() -> !messages.isEmpty());
    assertThat(messages.stream().map(Message::getPayload)
            .collect(Collectors.toList()))
                    .containsExactly("foo".getBytes());
}
 
Example 4
private PublisherBuilder<? extends Message<?>> createPublisherBuilder(String name, Config config) {
    // Extract the type and throw an exception if missing
    String connector = getConnectorAttribute(config);

    // Look for the factory and throw an exception if missing
    IncomingConnectorFactory mySourceFactory = incomingConnectorFactories.select(ConnectorLiteral.of(connector))
            .stream().findFirst().orElseThrow(() -> ex.illegalArgumentUnknownConnector(name));

    PublisherBuilder<? extends Message<?>> publisher = mySourceFactory.getPublisherBuilder(config);

    for (PublisherDecorator decorator : publisherDecoratorInstance) {
        publisher = decorator.decorate(publisher, name);
    }

    return publisher;
}
 
Example 5
@Test
void testSingle(io.vertx.core.Vertx vertx, VertxTestContext testContext) {
    final Map<String, String> configMap = new HashMap<>();
    configMap.put("port", "0");
    final MqttServerSource source = new MqttServerSource(new Vertx(vertx),
            new MqttServerConnectorIncomingConfiguration(TestUtils.config(configMap)));
    final PublisherBuilder<MqttMessage> mqttMessagePublisherBuilder = source.source();
    final TestMqttMessage testMessage = new TestMqttMessage("hello/topic", 1, "Hello world!",
            EXACTLY_ONCE.value(), false);
    final Checkpoint messageReceived = testContext.checkpoint();
    final Checkpoint messageAcknowledged = testContext.checkpoint();

    mqttMessagePublisherBuilder.forEach(mqttMessage -> {
        testContext.verify(() -> TestUtils.assertMqttEquals(testMessage, mqttMessage));
        messageReceived.flag();
        mqttMessage.ack().thenApply(aVoid -> {
            messageAcknowledged.flag();
            return aVoid;
        });
    }).run();
    TestUtils.sendMqttMessages(Collections.singletonList(testMessage),
            CompletableFuture.supplyAsync(() -> {
                await().until(source::port, port -> port != 0);
                return source.port();
            }), testContext);
}
 
Example 6
@Test
public void testBlockingWhenProducingPayload() {
    addBeanClass(BeanReturningPayloads.class);
    initialize();

    List<PublisherBuilder<? extends Message<?>>> producer = registry(container).getPublishers("infinite-producer");
    assertThat(producer).isNotEmpty();
    List<Integer> list = producer.get(0).map(Message::getPayload)
            .limit(5)
            .map(i -> (Integer) i)
            .toList().run().toCompletableFuture().join();
    assertThat(list).containsExactly(1, 2, 3, 4, 5);

    BeanReturningPayloads bean = container.getBeanManager().createInstance().select(BeanReturningPayloads.class).get();

    List<String> threadNames = bean.threads().stream().distinct().collect(Collectors.toList());
    assertThat(threadNames.contains(Thread.currentThread().getName())).isFalse();
    for (String name : threadNames) {
        assertThat(name.startsWith("vert.x-worker-thread-")).isTrue();
    }
}
 
Example 7
@SuppressWarnings("unchecked")
@Override
protected Exception getFailure(PublisherBuilder instance) {
    AtomicReference<Throwable> reference = new AtomicReference<>();
    try {
        instance.forEach(x -> {
            // Do nothing.
        }).run().toCompletableFuture().join();
    } catch (Exception e) {
        reference.set((e instanceof CompletionException ? e.getCause() : e));
    }
    return (Exception) reference.get();
}
 
Example 8
@Override
public PublisherBuilder<? extends Message<?>> getPublisherBuilder(final Config config) {
    final PubSubConfig pubSubConfig = new PubSubConfig(projectId, getTopic(config), getCredentialPath(config),
            getSubscription(config), mockPubSubTopics, host.orElse(null), port.orElse(null));

    return ReactiveStreams.fromCompletionStage(CompletableFuture.supplyAsync(() -> {
        createTopic(pubSubConfig);
        createSubscription(pubSubConfig);
        return pubSubConfig;
    }, executorService))
            .flatMapRsPublisher(
                    cfg -> Multi.createFrom().emitter(new PubSubSource(cfg, pubSubManager)));
}
 
Example 9
@Outgoing("publisher-builder-payload")
public PublisherBuilder<String> getAPublisherBuilderProducingPayload() {
    increment("publisher-builder-payload");
    return ReactiveStreams.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
        .flatMap(i -> ReactiveStreams.of(i, i))
        .map(i -> Integer.toString(i));
}
 
Example 10
@Incoming("hello")
@Outgoing("out")
public PublisherBuilder<String> consume(final PublisherBuilder<String> values) {
    return values.via(ReactiveStreams.<String>builder().flatMapCompletionStage(s -> CompletableFuture.supplyAsync(()-> s, executor)))
    .onError(err -> downstreamFailure = err);
    
}
 
Example 11
@Test
public void builderShouldBeImmutable() {
    PublisherBuilder<Integer> builder = builder();
    PublisherBuilder<Integer> mapped = builder.map(Function.identity());
    PublisherBuilder<Integer> distinct = builder.distinct();
    CompletionRunner<Void> cancelled = builder.cancel();
    getAddedStage(Stage.Map.class, graphFor(mapped));
    getAddedStage(Stage.Distinct.class, graphFor(distinct));
    getAddedStage(Stage.Cancel.class, graphFor(cancelled));
}
 
Example 12
/**
 * An infinite stream of integers starting from one.
 */
PublisherBuilder<Integer> infiniteStream() {
    return rs.fromIterable(() -> {
        AtomicInteger value = new AtomicInteger();
        return IntStream.generate(value::incrementAndGet).boxed().iterator();
    });
}
 
Example 13
@Test
public void flatMapStageBuilderShouldBeReusable() {
    ProcessorBuilder<PublisherBuilder<Integer>, Integer> flatMap =
        rs.<PublisherBuilder<Integer>>builder().flatMap(Function.identity());

    assertEquals(await(rs.of(rs.of(1, 2)).via(flatMap).toList().run(getEngine())), Arrays.asList(1, 2));
    assertEquals(await(rs.of(rs.of(3, 4)).via(flatMap).toList().run(getEngine())), Arrays.asList(3, 4));
}
 
Example 14
Source Project: quarkus   Source File: SomeConnector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public PublisherBuilder<? extends Message<?>> getPublisherBuilder(Config config) {
    Integer increment = config.getOptionalValue("increment", Integer.class).orElse(1);

    return ReactiveStreams.of(1, 2, 3, 4, 5, 6, 7, 8, 9)
            .map(i -> i + increment)
            .map(Message::of);
}
 
Example 15
public void generate() {
    // tag::generate[]
    AtomicInteger counter = new AtomicInteger();
    PublisherBuilder<Integer> stream = ReactiveStreams
            .generate(() -> counter.getAndIncrement());
    // The resulting stream is an infinite stream.
    // end::generate[]
}
 
Example 16
private void processMethodConsumingAPublisherBuilderOfMessages() {
    function = publisher -> {
        PublisherBuilder<Message<?>> prependedWithAck = publisher
                .flatMapCompletionStage(managePreProcessingAck());

        PublisherBuilder<Message<?>> builder = invoke(prependedWithAck);
        Objects.requireNonNull(builder, msg.methodReturnedNull(configuration.methodAsString()));
        return builder;
    };
}
 
Example 17
@Incoming("count")
@Outgoing("sink")
public PublisherBuilder<Message<String>> process(Message<Integer> message) {
    return ReactiveStreams.of(message)
            .map(Message::getPayload)
            .map(i -> i + 1)
            .flatMapRsPublisher(i -> Flowable.just(i, i))
            .map(i -> Integer.toString(i))
            .map(Message::of);
}
 
Example 18
@SuppressWarnings("unchecked")
@Override
protected List<String> getAll(PublisherBuilder instance) {
    try {
        return (List<String>) instance.toList().run().toCompletableFuture().join();
    } catch (Exception e) {
        if (e instanceof CompletionException && e.getCause() instanceof RuntimeException) {
            throw (RuntimeException) e.getCause();
        } else {
            throw (RuntimeException) e;
        }
    }
}
 
Example 19
@Test
public void testSourceUsingChannelName() {
    String topic = UUID.randomUUID().toString();
    Map<String, Object> config = getConfigUsingChannelName(topic);
    config.put("ttl", 10000);
    config.put("durable", false);

    provider = new AmqpConnector();
    provider.setup(executionHolder);
    PublisherBuilder<? extends Message<?>> builder = provider.getPublisherBuilder(new MapBasedConfig(config));

    List<Message<Integer>> messages = new ArrayList<>();

    AtomicBoolean opened = new AtomicBoolean();
    builder.buildRs().subscribe(createSubscriber(messages, opened));
    await().until(opened::get);

    await().until(() -> provider.isReady(config.get(CHANNEL_NAME_ATTRIBUTE).toString()));

    AtomicInteger counter = new AtomicInteger();
    new Thread(() -> usage.produceTenIntegers(topic,
            counter::getAndIncrement)).start();

    await().atMost(2, TimeUnit.MINUTES).until(() -> messages.size() >= 10);
    assertThat(messages.stream()
            .peek(m -> m.ack().toCompletableFuture().join())
            .map(Message::getPayload)
            .collect(Collectors.toList()))
                    .containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
}
 
Example 20
@SuppressWarnings("rawtypes")
@Test
public void testBroadcastWithPartitions() {
    KafkaUsage usage = new KafkaUsage();
    String topic = UUID.randomUUID().toString();
    kafka.createTopic(topic, 2, 1);
    Map<String, Object> config = newCommonConfig();
    config.put("topic", topic);
    config.put("value.deserializer", IntegerDeserializer.class.getName());
    config.put("broadcast", true);
    config.put("bootstrap.servers", SERVERS);
    config.put("channel-name", topic);
    config.put("partitions", 2);
    KafkaConnector connector = new KafkaConnector();
    connector.executionHolder = new ExecutionHolder(vertx);
    connector.defaultKafkaConfiguration = UnsatisfiedInstance.instance();
    connector.consumerRebalanceListeners = getConsumerRebalanceListeners();
    connector.init();
    PublisherBuilder<? extends KafkaRecord> builder = (PublisherBuilder<? extends KafkaRecord>) connector
            .getPublisherBuilder(new MapBasedConfig(config));

    List<KafkaRecord> messages1 = new ArrayList<>();
    List<KafkaRecord> messages2 = new ArrayList<>();
    builder.forEach(messages1::add).run();
    builder.forEach(messages2::add).run();

    AtomicInteger counter = new AtomicInteger();
    new Thread(() -> usage.produceIntegers(10, null,
            () -> new ProducerRecord<>(topic, counter.getAndIncrement()))).start();

    await().atMost(2, TimeUnit.MINUTES).until(() -> messages1.size() >= 10);
    await().atMost(2, TimeUnit.MINUTES).until(() -> messages2.size() >= 10);
    assertThat(messages1.stream().map(KafkaRecord::getPayload).collect(Collectors.toList()))
            .containsExactlyInAnyOrder(0, 1, 2, 3, 4,
                    5, 6, 7, 8, 9);
    assertThat(messages2.stream().map(KafkaRecord::getPayload).collect(Collectors.toList()))
            .containsExactlyInAnyOrder(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
}
 
Example 21
@SuppressWarnings("rawtypes")
private Publisher<? extends Message> getPublisher(InjectionPoint injectionPoint) {
    String name = getChannelName(injectionPoint);
    List<PublisherBuilder<? extends Message<?>>> list = channelRegistry.getPublishers(name);
    if (list.isEmpty()) {
        throw ex.illegalStateForStream(name, channelRegistry.getIncomingNames());
    }
    // TODO Manage merge.
    return list.get(0).buildRs();
}
 
Example 22
@Incoming(PRE_ACKNOWLEDGMENT_BUILDER)
@Acknowledgment(Acknowledgment.Strategy.PRE_PROCESSING)
@Outgoing("sink-" + PRE_ACKNOWLEDGMENT_BUILDER)
public PublisherBuilder<String> processorWithPreAckBuilder(String input) {
    return ReactiveStreams.of(input)
            .flatMap(m -> ReactiveStreams.of(m, m))
            .peek(m -> processed(PRE_ACKNOWLEDGMENT_BUILDER, m));
}
 
Example 23
@Incoming(NO_ACKNOWLEDGMENT_BUILDER)
@Acknowledgment(Acknowledgment.Strategy.NONE)
@Outgoing("sink-" + NO_ACKNOWLEDGMENT_BUILDER)
public PublisherBuilder<String> processorWithNoAckWithBuilder(String message) {
    return ReactiveStreams.of(message)
            .flatMap(m -> ReactiveStreams.of(m, m))
            .peek(m -> processed(NO_ACKNOWLEDGMENT_BUILDER, message));
}
 
Example 24
@Override
protected Exception getFailure(PublisherBuilder instance) {
    AtomicReference<Throwable> reference = new AtomicReference<>();
    try {
        instance.forEach(x -> {
            // Do nothing.
        }).run().toCompletableFuture().join();
    } catch (Exception e) {
        reference.set((e instanceof CompletionException ? e.getCause() : e));
    }
    return (Exception) reference.get();
}
 
Example 25
private void assertThatProducerWasPublished(SeContainer container) {
    assertThat(registry(container).getIncomingNames()).contains("producer");
    List<PublisherBuilder<? extends Message<?>>> producer = registry(container).getPublishers("producer");
    assertThat(producer).isNotEmpty();
    List<String> list = producer.get(0).map(Message::getPayload)
            .map(i -> (String) i)
            .toList().run().toCompletableFuture().join();
    assertThat(list).containsExactly("a", "b", "c");
}
 
Example 26
@Incoming(CONNECTOR_PROCESS)
@Outgoing(CONNECTOR_OUT)
@Acknowledgment(Strategy.PRE_PROCESSING)
public PublisherBuilder<Message<String>> split(Message<String> a) {
    List<Message<String>> messages = new ArrayList<>();
    for (int i = 1; i <=2; i++) {
        messages.add(Message.of(a.getPayload() + "-" + i));
    }
    return ReactiveStreams.fromIterable(messages);
}
 
Example 27
@Incoming(PRE_ACKNOWLEDGMENT_BUILDER)
@Acknowledgment(Acknowledgment.Strategy.PRE_PROCESSING)
@Outgoing("sink-" + PRE_ACKNOWLEDGMENT_BUILDER)
public PublisherBuilder<Message<String>> processorWithPreAckWithBuilder(PublisherBuilder<Message<String>> input) {
    return input
            .flatMap(m -> ReactiveStreams.of(Message.of(m.getPayload()), Message.of(m.getPayload())))
            .peek(m -> processed(PRE_ACKNOWLEDGMENT_BUILDER, m.getPayload()));
}
 
Example 28
@SuppressWarnings("unchecked")
@Override
protected String getOne(PublisherBuilder instance) {
    try {
        return ((Optional<String>) instance.findFirst().run().toCompletableFuture().join()).orElse(null);
    } catch (Exception e) {
        if (e instanceof CompletionException && e.getCause() instanceof RuntimeException) {
            throw (RuntimeException) e.getCause();
        } else {
            throw (RuntimeException) e;
        }
    }
}
 
Example 29
@Incoming("publisher-for-publisher-builder-payload")
@Outgoing("publisher-builder-payload")
public PublisherBuilder<String> processorBuilderOfPayloads(PublisherBuilder<Integer> stream) {
  increment("publisher-builder-payload");
  return stream
    .map(i -> i + 1)
    .flatMap(i -> ReactiveStreams.of(i, i))
    .map(i -> Integer.toString(i));
}
 
Example 30
@Incoming("hello")
@Outgoing("out")
public PublisherBuilder<String> consume(final PublisherBuilder<String> values) {
    return values.via(ReactiveStreams.<String>builder().flatMapCompletionStage(s -> CompletableFuture.supplyAsync(()-> {
        try {
            Thread.sleep(1); 
        } 
        catch (InterruptedException ignored) {
            Thread.currentThread().interrupt();
        }
        return s;
    }, executor))).onError(err -> downstreamFailure = err);
    
    
}