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

The following examples show how to use org.eclipse.microprofile.reactive.streams.operators.PublisherBuilder. 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
Source File: AmqpSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: BlockingPublisherTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@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
Source File: ConfiguredChannelFactory.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: MqttServerSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: MediatorManager.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: BlockingPublisherTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@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
Source File: PublisherBuilderFromRSPublisherTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@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 #8
Source File: BeanWithStreamTransformers.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming(PAYLOAD_PRE_ACKNOWLEDGMENT_BUILDER)
@Acknowledgment(Acknowledgment.Strategy.PRE_PROCESSING)
@Outgoing("sink-" + PAYLOAD_PRE_ACKNOWLEDGMENT_BUILDER)
public PublisherBuilder<String> processorWithPreAckWithBuilderWithPayload(PublisherBuilder<String> input) {
    return input
            .flatMap(p -> ReactiveStreams.of(p, p))
            .peek(m -> processed(PAYLOAD_PRE_ACKNOWLEDGMENT_BUILDER, m));
}
 
Example #9
Source File: MqttServerConnectorTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
void test(@Any MqttServerConnector connector, VertxTestContext testContext) {
    final AtomicBoolean opened = new AtomicBoolean();
    final Map<String, String> configMap = new HashMap<>();
    configMap.put("port", "0");
    final List<TestMqttMessage> testMessages = new CopyOnWriteArrayList<>();
    testMessages.add(
            new TestMqttMessage("hello/topic", 1, "Hello world!", EXACTLY_ONCE.value(), false));
    testMessages.add(
            new TestMqttMessage("foo/bar", 2, "dkufhdspkjfosdjfs;", AT_LEAST_ONCE.value(),
                    true));
    testMessages.add(
            new TestMqttMessage("foo/bar", -1, "Hello world!", AT_MOST_ONCE.value(), false));
    testMessages
            .add(new TestMqttMessage("sa/srt/tgvbc", 3, "Yeah", EXACTLY_ONCE.value(), true));
    final PublisherBuilder<MqttMessage> builder = (PublisherBuilder<MqttMessage>) connector
            .getPublisherBuilder(TestUtils.config(configMap));

    // The source is the same for every call
    assertEquals(builder, connector.getPublisherBuilder(TestUtils.config(configMap)));

    builder.buildRs().subscribe(createSubscriber(testContext, opened, testMessages));

    TestUtils.sendMqttMessages(testMessages, CompletableFuture.supplyAsync(() -> {
        await().until(opened::get);
        await().until(() -> connector.port() != 0);
        return connector.port();
    }), testContext);
}
 
Example #10
Source File: AmqpSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@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 #11
Source File: BeanWithProcessorsProducingPayloadStreams.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: EventBusSource.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
PublisherBuilder<? extends Message<?>> source() {
    MessageConsumer<Message<?>> consumer = vertx.eventBus().consumer(address);
    Multi<io.vertx.mutiny.core.eventbus.Message<Message<?>>> multi = consumer.toMulti();
    if (broadcast) {
        multi = multi.broadcast().toAllSubscribers();
    }
    return ReactiveStreams.fromPublisher(multi)
            .map(this::adapt);
}
 
Example #13
Source File: PublisherBuilderVerification.java    From microprofile-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@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 #14
Source File: Operators.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
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 #15
Source File: SomeConnector.java    From quarkus with 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 #16
Source File: AbstractStageVerification.java    From microprofile-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #17
Source File: PublisherBuilderToRSPublisherTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Override
protected PublisherBuilder createInstanceFailingAsynchronously(RuntimeException e) {
    return ReactiveStreams.fromPublisher(Single.just("x")
            .delay(10, TimeUnit.MILLISECONDS)
            .observeOn(Schedulers.computation())
            .map(s -> {
                throw e;
            })
            .toFlowable());
}
 
Example #18
Source File: ChannelProducer.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@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 #19
Source File: KafkaSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@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 #20
Source File: BeanWithProcessorsProducingPayloadStreams.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@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 #21
Source File: PublisherBuilderFromCompletionStageTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@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 #22
Source File: PublisherShapeTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
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 #23
Source File: MetricsTestBean.java    From microprofile-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming(CHANNEL_APP_A)
@Outgoing(CHANNEL_APP_B)
public PublisherBuilder<String> split(String input) {
    List<String> messages = new ArrayList<>();
    for (int i = 1; i <=2; i++) {
        messages.add(input + "-" + i);
    }
    return ReactiveStreams.fromIterable(messages);
}
 
Example #24
Source File: JmsSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Test
public void testBroadcast() {
    JmsSource source = new JmsSource(jms,
            new JmsConnectorIncomingConfiguration(new MapBasedConfig.Builder()
                    .put("channel-name", "queue").put("broadcast", true).build()),
            null, null);
    PublisherBuilder<IncomingJmsMessage<?>> publisher = source.getSource();

    List<IncomingJmsMessage<?>> list1 = new ArrayList<>();
    List<IncomingJmsMessage<?>> list2 = new ArrayList<>();

    publisher.peek(list1::add).ignore().run();

    new Thread(() -> {
        JMSContext context = factory.createContext();
        JMSProducer producer = context.createProducer();
        Queue q = context.createQueue("queue");
        for (int i = 0; i < 50; i++) {
            producer.send(q, i);
        }
    }).start();

    publisher.peek(list2::add).ignore().run();

    await().until(() -> list1.size() == 50);
    await().until(() -> list2.size() == 50);

    assertThat(list1.stream().map(r -> (Integer) r.getPayload()).collect(Collectors.toList()))
            .containsAll(IntStream.of(49).boxed().collect(Collectors.toList()));
    assertThat(list2.stream().map(r -> (Integer) r.getPayload()).collect(Collectors.toList()))
            .containsAll(IntStream.of(49).boxed().collect(Collectors.toList()));
}
 
Example #25
Source File: PublisherBuilderFromRSPublisherTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected void consume(PublisherBuilder instance) {
    instance.forEach(x -> {
        // Do nothing.
    }).run().toCompletableFuture().join();
}
 
Example #26
Source File: MetricsTestBean.java    From microprofile-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@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
Source File: BeanUsingBufferOverflowStrategy.java    From microprofile-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@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);
    
    
}
 
Example #28
Source File: BeanWithStreamTransformers.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@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 #29
Source File: PublisherBuilderFromRSPublisherTest.java    From smallrye-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@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 #30
Source File: TransformerBean.java    From microprofile-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@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));
}