org.eclipse.microprofile.reactive.messaging.Message Java Examples

The following examples show how to use org.eclipse.microprofile.reactive.messaging.Message. 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: SubscriberMediator.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
private void processMethodReturningVoid() {
    if (configuration.isBlocking()) {
        this.subscriber = ReactiveStreams.<Message<?>> builder()
                .flatMapCompletionStage(m -> Uni.createFrom().completionStage(handlePreProcessingAck(m))
                        .onItem().produceUni(msg -> invokeBlocking(msg.getPayload()))
                        .onItemOrFailure().produceUni(handleInvocationResult(m))
                        .subscribeAsCompletionStage())
                .ignore();
    } else {
        this.subscriber = ReactiveStreams.<Message<?>> builder()
                .flatMapCompletionStage(m -> Uni.createFrom().completionStage(handlePreProcessingAck(m))
                        .onItem().apply(msg -> invoke(msg.getPayload()))
                        .onItemOrFailure().produceUni(handleInvocationResult(m))
                        .subscribeAsCompletionStage())
                .ignore();
    }
}
 
Example #2
Source File: JmsSinkTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultConfigurationAgainstTopic() throws JMSException {
    MapBasedConfig config = new MapBasedConfig.Builder()
            .put("destination", "my-topic")
            .put("destination-type", "topic")
            .put("channel-name", "jms")
            .build();
    JmsSink sink = new JmsSink(jms, new JmsConnectorOutgoingConfiguration(config), json, executor);
    MyJmsClient client1 = new MyJmsClient(jms.createTopic("my-topic"));
    MyJmsClient client2 = new MyJmsClient(jms.createTopic("my-topic"));
    subscriber = sink.getSink().build();
    subscriber.onSubscribe(new Subscriptions.EmptySubscription());
    AtomicBoolean acked = new AtomicBoolean();
    subscriber.onNext(Message.of("hello",
            () -> CompletableFuture.runAsync(() -> acked.set(true))));

    await().until(() -> client1.messages.size() >= 1);
    await().until(() -> client2.messages.size() >= 1);
    assertThat(acked).isTrue();
    assertThat(client1.messages.get(0).getBody(String.class)).isEqualTo("hello");
    assertThat(client2.messages.get(0).getBody(String.class)).isEqualTo("hello");
}
 
Example #3
Source File: BeanWithStreamTransformers.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Incoming(DEFAULT_ACKNOWLEDGMENT_BUILDER)
@Outgoing("sink-" + DEFAULT_ACKNOWLEDGMENT_BUILDER)
public PublisherBuilder<Message<String>> processorWithDefaultAckWithBuilder(
        PublisherBuilder<Message<String>> input) {
    return input
            .flatMap(m -> {
                AtomicInteger counter = new AtomicInteger();
                return ReactiveStreams.of(Message.of(m.getPayload(), () -> {
                    if (counter.incrementAndGet() == 2) {
                        return m.ack();
                    } else {
                        return CompletableFuture.completedFuture(null);
                    }
                }), Message.of(m.getPayload(), () -> {
                    if (counter.incrementAndGet() == 2) {
                        return m.ack();
                    } else {
                        return CompletableFuture.completedFuture(null);
                    }
                }));
            })
            .peek(m -> processed(DEFAULT_ACKNOWLEDGMENT_BUILDER, m.getPayload()));
}
 
Example #4
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 #5
Source File: AmqpSinkTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Test
public void testSinkUsingInteger() {
    String topic = UUID.randomUUID().toString();
    AtomicInteger expected = new AtomicInteger(0);
    usage.consumeIntegers(topic,
            v -> expected.getAndIncrement());

    SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(topic);
    //noinspection unchecked
    Multi.createFrom().range(0, 10)
            .map(Message::of)
            .subscribe((Subscriber<? super Message<Integer>>) sink.build());

    await().until(() -> expected.get() == 10);
    assertThat(expected).hasValue(10);
}
 
Example #6
Source File: ProcessorMediator.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
private Uni<? extends Message<Object>> handlePostInvocation(Message<?> message, Object res, Throwable fail) {
    if (fail != null) {
        if (isPostAck()) {
            return Uni.createFrom()
                    .completionStage(message.nack(fail).thenApply(x -> (Message<Object>) null));
        } else {
            throw ex.processingException(getMethodAsString(), fail);
        }
    } else if (res != null) {
        if (isPostAck()) {
            return Uni.createFrom().item(message.withPayload(res));
        } else {
            return Uni.createFrom().item(Message.of(res, message.getMetadata()));
        }
    } else {
        // the method returned null, the message is not forwarded, but we ack the message in post ack
        if (isPostAck()) {
            return Uni.createFrom()
                    .completionStage(message.ack().thenApply(x -> (Message<Object>) null));
        } else {
            return Uni.createFrom().nullItem();
        }
    }
}
 
Example #7
Source File: JmsSinkTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Test
public void testDefaultConfiguration() throws JMSException {
    MapBasedConfig config = new MapBasedConfig.Builder()
            .put("destination", "queue-one")
            .put("channel-name", "jms")
            .build();
    JmsSink sink = new JmsSink(jms, new JmsConnectorOutgoingConfiguration(config), json, executor);
    MyJmsClient client = new MyJmsClient(jms.createQueue("queue-one"));
    subscriber = sink.getSink().build();
    subscriber.onSubscribe(new Subscriptions.EmptySubscription());
    AtomicBoolean acked = new AtomicBoolean();
    subscriber.onNext(Message.of("hello",
            () -> CompletableFuture.runAsync(() -> acked.set(true))));

    await().until(() -> client.messages.size() >= 1);
    assertThat(acked).isTrue();
    assertThat(client.messages.get(0).getBody(String.class)).isEqualTo("hello");
}
 
Example #8
Source File: KafkaSourceTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSource() {
    KafkaUsage usage = new KafkaUsage();
    String topic = UUID.randomUUID().toString();
    Map<String, Object> config = newCommonConfig();
    config.put("topic", topic);
    config.put("value.deserializer", IntegerDeserializer.class.getName());
    config.put("bootstrap.servers", SERVERS);
    config.put("channel-name", topic);
    KafkaConnectorIncomingConfiguration ic = new KafkaConnectorIncomingConfiguration(new MapBasedConfig(config));
    KafkaSource<String, Integer> source = new KafkaSource<>(vertx, UUID.randomUUID().toString(), ic,
            getConsumerRebalanceListeners());

    List<Message<?>> messages = new ArrayList<>();
    source.getStream().subscribe().with(messages::add);

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

    await().atMost(2, TimeUnit.MINUTES).until(() -> messages.size() >= 10);
    assertThat(messages.stream().map(m -> ((KafkaRecord<String, Integer>) m).getPayload())
            .collect(Collectors.toList())).containsExactly(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
}
 
Example #9
Source File: KafkaSink.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
private void handleWriteResult(AsyncResult<?> ar, Message<?> message, ProducerRecord<?, ?> record,
        UniEmitter<? super Void> emitter) {
    String actualTopic = record.topic();
    if (ar.succeeded()) {
        log.successfullyToTopic(message, actualTopic);
        message.ack().whenComplete((x, f) -> {
            if (f != null) {
                emitter.fail(f);
            } else {
                emitter.complete(null);
            }
        });
    } else {
        // Fail, there will be retry.
        emitter.fail(ar.cause());
    }
}
 
Example #10
Source File: AmqpSinkTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Test
public void testSinkUsingIntegerUsingNonAnonymousSender() {
    String topic = UUID.randomUUID().toString();
    AtomicInteger expected = new AtomicInteger(0);
    usage.consumeIntegers(topic,
            v -> expected.getAndIncrement());

    SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndNonAnonymousSink(topic);
    //noinspection unchecked
    Multi.createFrom().range(0, 10)
            .map(Message::of)
            .subscribe((Subscriber<? super Message<Integer>>) sink.build());

    await().until(() -> expected.get() == 10);
    assertThat(expected).hasValue(10);
}
 
Example #11
Source File: AmqpSinkTest.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreditBasedFlowControl() {
    String topic = UUID.randomUUID().toString();
    AtomicInteger expected = new AtomicInteger(0);
    usage.consumeIntegers(topic,
            v -> expected.getAndIncrement());

    SubscriberBuilder<? extends Message<?>, Void> sink = createProviderAndSink(topic);
    //noinspection unchecked
    Multi.createFrom().range(0, 5000)
            .map(Message::of)
            .subscribe((Subscriber<? super Message<Integer>>) sink.build());

    await().until(() -> expected.get() == 5000);
    assertThat(expected).hasValue(5000);
}
 
Example #12
Source File: StreamSkip.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("in")
@Outgoing("out-4")
public Multi<Message<String>> processMessageStream(Multi<Message<String>> stream) {
    return stream
        .transform().byFilteringItemsWith(m -> !m.getPayload().equalsIgnoreCase("skip"))
        .onItem().apply(m -> m.withPayload(m.getPayload().toUpperCase()));
}
 
Example #13
Source File: InternalChannelRegistry.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized SubscriberBuilder<? extends Message<?>, Void> register(String name,
        SubscriberBuilder<? extends Message<?>, Void> subscriber) {
    Objects.requireNonNull(name, msg.nameMustBeSet());
    Objects.requireNonNull(subscriber, msg.subscriberMustBeSet());
    register(subscribers, name, subscriber);
    return subscriber;
}
 
Example #14
Source File: AmqpCreditBasedSender.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
private Uni<Message<?>> send(AmqpSender sender, Message<?> msg, boolean durable, long ttl, String configuredAddress,
        boolean isAnonymousSender, AmqpConnectorCommonConfiguration configuration) {
    int retryAttempts = configuration.getReconnectAttempts();
    int retryInterval = configuration.getReconnectInterval();
    io.vertx.mutiny.amqp.AmqpMessage amqp;
    if (msg instanceof AmqpMessage) {
        amqp = ((AmqpMessage<?>) msg).getAmqpMessage();
    } else if (msg.getPayload() instanceof io.vertx.mutiny.amqp.AmqpMessage) {
        amqp = (io.vertx.mutiny.amqp.AmqpMessage) msg.getPayload();
    } else if (msg.getPayload() instanceof io.vertx.amqp.AmqpMessage) {
        amqp = new io.vertx.mutiny.amqp.AmqpMessage((io.vertx.amqp.AmqpMessage) msg.getPayload());
    } else {
        amqp = AmqpMessageConverter.convertToAmqpMessage(msg, durable, ttl);
    }

    String actualAddress = getActualAddress(msg, amqp, configuredAddress, isAnonymousSender);
    if (connector.getClients().isEmpty()) {
        log.messageNoSend(actualAddress);
        return Uni.createFrom().item(msg);
    }

    if (!actualAddress.equals(amqp.address())) {
        amqp = new io.vertx.mutiny.amqp.AmqpMessage(
                new AmqpMessageBuilderImpl(amqp.getDelegate()).address(actualAddress).build());
    }

    log.sendingMessageToAddress(actualAddress);
    return sender.sendWithAck(amqp)
            .onFailure().retry().withBackOff(ofSeconds(1), ofSeconds(retryInterval)).atMost(retryAttempts)
            .onItemOrFailure().produceUni((success, failure) -> {
                if (failure != null) {
                    return Uni.createFrom().completionStage(msg.nack(failure));
                } else {
                    return Uni.createFrom().completionStage(msg.ack());
                }
            })
            .onItem().apply(x -> msg);
}
 
Example #15
Source File: HeaderPropagationTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("source")
@Outgoing("p1")
public Message<Integer> processMessage(Message<Integer> input) {
    JmsProperties properties = new JmsPropertiesBuilder().with("prop", "bar").build();
    return Message.of(input.getPayload())
            .withMetadata(Metadata.of(OutgoingJmsMessageMetadata.builder()
                    .withProperties(properties)
                    .withCorrelationId("my-correlation-" + input.getPayload())
                    .withDestination(queue)
                    .build()));
}
 
Example #16
Source File: BeanConsumingMsgAsFluxAndPublishingMsgAsFlux.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("count")
@Outgoing("sink")
public Flux<Message<String>> process(Flux<Message<Integer>> source) {
    return source
            .map(Message::getPayload)
            .map(i -> i + 1)
            .flatMap(i -> Flowable.just(i, i))
            .map(i -> Integer.toString(i))
            .map(Message::of);
}
 
Example #17
Source File: ProducingBeanUsingOutboundMetadata.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("data")
@Outgoing("sink")
@Acknowledgment(Acknowledgment.Strategy.MANUAL)
public Message<Integer> process(Message<Integer> input) {
    OutgoingAmqpMetadata metadata = OutgoingAmqpMetadata.builder()
            .withSubject("subject")
            .withAddress("sink")
            .build();

    return Message.of(input.getPayload() + 1, input::ack).addMetadata(metadata);
}
 
Example #18
Source File: MultiLevelIncomingsTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("a")
@Incoming("b")
@Incoming("c")
@Outgoing("out")
public Message<String> process(Message<String> s) {
    return Message.of(s.getPayload().toUpperCase());
}
 
Example #19
Source File: BeanWithProcessorsManipulatingPayloads.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Outgoing(PRE_ACKNOWLEDGMENT_CS)
public Publisher<Message<String>> sourceToPreAckCS() {
    return Multi.createFrom().items("a", "b", "c", "d", "e")
            .map(payload -> Message.of(payload, () -> {
                nap();
                acknowledged(PRE_ACKNOWLEDGMENT_CS, payload);
                return CompletableFuture.completedFuture(null);
            }));
}
 
Example #20
Source File: KafkaConnector.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Override
public SubscriberBuilder<? extends Message<?>, Void> getSubscriberBuilder(Config config) {
    Config c = config;
    if (!defaultKafkaConfiguration.isUnsatisfied()) {
        c = merge(config, defaultKafkaConfiguration.get());
    }
    KafkaConnectorOutgoingConfiguration oc = new KafkaConnectorOutgoingConfiguration(c);
    KafkaSink sink = new KafkaSink(vertx, oc);
    sinks.add(sink);
    return sink.getSink();
}
 
Example #21
Source File: PublisherBean.java    From microprofile-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Outgoing("publisher-message")
public Publisher<Message<String>> getAPublisherProducingMessage() {
    increment("publisher-message");
    return ReactiveStreams.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
        .flatMap(i -> ReactiveStreams.of(i, i))
        .map(i -> Integer.toString(i))
        .map(Message::of)
        .buildRs();
}
 
Example #22
Source File: ConsumptionBean.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("data")
@Outgoing("sink")
@Acknowledgment(Acknowledgment.Strategy.MANUAL)
public Message<Integer> process(AmqpMessage<Integer> input) {
    int value = input.getPayload();
    return Message.of(value + 1, input::ack);
}
 
Example #23
Source File: BeanWithProcessorsManipulatingMessages.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Outgoing(DEFAULT_ACKNOWLEDGMENT)
public Publisher<Message<String>> sourceToDefaultAck() {
    return Multi.createFrom().items("a", "b", "c", "d", "e")
            .map(payload -> Message.of(payload, () -> {
                nap();
                acknowledged(DEFAULT_ACKNOWLEDGMENT, payload);
                return CompletableFuture.completedFuture(null);
            }));
}
 
Example #24
Source File: MessageExamples.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
public void creation() {
    Price price = new Price(20.5);
    // tag::creation[]

    // Create a simple message wrapping a payload
    Message<Price> m1 = Message.of(price);

    // Create a message with metadata
    Message<Price> m2 = Message.of(price, Metadata.of(new PriceMetadata()));

    // Create a message with several metadata
    Message<Price> m3 = Message.of(price,
        Metadata.of(new PriceMetadata(), new MyMetadata()));

    // Create a message with an acknowledgement callback
    Message<Price> m4 = Message.of(price, () -> {
        // Called when the message is acknowledged by the next consumer.
        return CompletableFuture.completedFuture(null);
    });

    // Create a message with both metadata and acknowledgement callback
    Message<Price> m5 = Message.of(price,
        Metadata.of(new PriceMetadata()),
        () -> {
            // Called when the message is acknowledged by the next consumer.
            return CompletableFuture.completedFuture(null);
        });
    // end::creation[]
}
 
Example #25
Source File: TransformerBean.java    From microprofile-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("publisher-for-publisher-message")
@Outgoing("publisher-message")
public Publisher<Message<String>> processorOfMessages(Publisher<Message<Integer>> stream) {
  increment("publisher-message");
  return ReactiveStreams.fromPublisher(stream)
    .map(Message::getPayload)
    .map(i -> i + 1)
    .flatMap(i -> ReactiveStreams.of(i, i))
    .map(i -> Integer.toString(i))
    .map(Message::of)
    .buildRs();
}
 
Example #26
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 #27
Source File: SubscriberBeanWithMethodsReturningUni.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming(NO_ACKNOWLEDGMENT_MESSAGE)
@Acknowledgment(Acknowledgment.Strategy.NONE)
public Uni<Void> subWithNoAckMessage(Message<String> message) {
    return Uni.createFrom().item(message)
            .emitOn(EXECUTOR)
            .onItem().invoke((m) -> processed(NO_ACKNOWLEDGMENT_MESSAGE, message))
            .onItem().delayIt().by(Duration.ofMillis(10))
            .onItem().ignore().andContinueWithNull();
}
 
Example #28
Source File: BeanWithPayloadProcessors.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Outgoing(NO_ACKNOWLEDGMENT_BUILDER)
public Publisher<Message<String>> sourceToNoAckWithBuilder() {
    return Multi.createFrom().items("a", "b", "c", "d", "e")
            .map(payload -> Message.of(payload, () -> {
                nap();
                acknowledged(NO_ACKNOWLEDGMENT_BUILDER, payload);
                return CompletableFuture.completedFuture(null);
            }));
}
 
Example #29
Source File: BeanWithPayloadProcessors.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Outgoing(DEFAULT_ACKNOWLEDGMENT)
public Publisher<Message<String>> sourceToAutoAck() {
    return Multi.createFrom().items("a", "b", "c", "d", "e")
            .map(payload -> Message.of(payload, () -> {
                nap();
                acknowledged(DEFAULT_ACKNOWLEDGMENT, payload);
                return CompletableFuture.completedFuture(null);
            }));
}
 
Example #30
Source File: BeanWithProcessorsManipulatingMessages.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Outgoing(NO_ACKNOWLEDGMENT_CS)
public Publisher<Message<String>> sourceToNoAckCS() {
    return Multi.createFrom().items("a", "b", "c", "d", "e")
            .map(payload -> Message.of(payload, () -> {
                nap();
                acknowledged(NO_ACKNOWLEDGMENT_CS, payload);
                return CompletableFuture.completedFuture(null);
            }));
}