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

The following examples show how to use org.eclipse.microprofile.reactive.messaging.Message. 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
Source Project: smallrye-reactive-messaging   Source File: JmsSinkTest.java    License: 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 2
Source Project: smallrye-reactive-messaging   Source File: AmqpSinkTest.java    License: 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 3
Source Project: smallrye-reactive-messaging   Source File: JmsSinkTest.java    License: 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 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
@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 6
Source Project: smallrye-reactive-messaging   Source File: AmqpSinkTest.java    License: 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 7
Source Project: smallrye-reactive-messaging   Source File: AmqpSinkTest.java    License: 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 8
@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 9
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 10
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 11
Source Project: smallrye-reactive-messaging   Source File: KafkaSink.java    License: 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 12
@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 13
@Incoming("in")
@Outgoing("out-4")
public Uni<Message<String>> processMessageAsync(Message<String> m) {
    String s = m.getPayload();
    if (s.equalsIgnoreCase("skip")) {
        return Uni.createFrom().nullItem();
    }
    return Uni.createFrom().item(m.withPayload(s.toUpperCase()));
}
 
Example 14
public void sendWithAcknowledgement(MockPayload payload) {
    System.out.println("Sending with ACK " + payload);
    AtomicReference<Message<MockPayload>> reference = new AtomicReference<>();
    Message<MockPayload> msg = Message.of(payload, () -> {
        System.out.println("Acknowledging " + payload);
        inflights.remove(reference.get());
        return CompletableFuture.completedFuture(null);
    });
    reference.set(msg);
    send(msg);
}
 
Example 15
@Incoming("count")
@Outgoing("sink")
public PublisherBuilder<Message<String>> process(PublisherBuilder<Message<Integer>> source) {
    return source
            .map(Message::getPayload)
            .map(i -> i + 1)
            .flatMapRsPublisher(i -> Flowable.just(i, i))
            .map(i -> Integer.toString(i))
            .map(Message::of);
}
 
Example 16
@Outgoing(MANUAL_ACKNOWLEDGMENT)
public Publisher<Message<String>> sourceToManualAck() {
    return ReactiveStreams.of("a", "b", "c", "d", "e")
            .map(payload -> Message.of(payload, () -> CompletableFuture.runAsync(() -> {
                nap();
                acknowledged(MANUAL_ACKNOWLEDGMENT, payload);
            }))).buildRs();
}
 
Example 17
@Test
@SuppressWarnings("unchecked")
public void testExpectReply() {
    String topic = UUID.randomUUID().toString();

    List<Integer> integers = new ArrayList<>();
    AtomicReference<io.vertx.mutiny.core.eventbus.Message<Integer>> last = new AtomicReference<>();
    vertx.eventBus().<Integer> consumer(topic, m -> {
        last.set(m);
        if (m.body() < 8) {
            integers.add(m.body());
            m.replyAndForget("foo");
        }
    });

    Map<String, Object> config = new HashMap<>();
    config.put("address", topic);
    config.put("expect-reply", true);
    EventBusSink sink = new EventBusSink(vertx,
            new VertxEventBusConnectorOutgoingConfiguration(new MapBasedConfig(config)));

    SubscriberBuilder<? extends Message<?>, Void> subscriber = sink.sink();
    Multi.createFrom().range(0, 10)
            .map(Message::of)
            .subscribe((Subscriber<Message<?>>) subscriber.build());

    await().until(() -> integers.size() == 8 && last.get().body() == 8);
    last.get().replyAndForget("bar");
    await().until(() -> last.get().body() == 9);
    assertThat(last.get().body()).isEqualTo(9);
    last.get().replyAndForget("baz");
}
 
Example 18
@Incoming("count")
@Outgoing("sink")
public Publisher<Message<String>> process(Flowable<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 19
@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 20
@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 21
@Outgoing(POST_ACKNOWLEDGMENT)
public Publisher<Message<String>> sourceToPostAck() {
    return Multi.createFrom().items("a", "b", "c", "d", "e")
            .map(payload -> Message.of(payload, () -> {
                nap();
                acknowledged(POST_ACKNOWLEDGMENT, payload);
                return CompletableFuture.completedFuture(null);
            }));
}
 
Example 22
@Incoming(NO_ACKNOWLEDGMENT)
@Acknowledgment(Acknowledgment.Strategy.NONE)
@Outgoing("sink")
public Message<String> processorWithNoAck(Message<String> input) {
    processed(NO_ACKNOWLEDGMENT, input);
    return Message.of(input.getPayload() + "1");
}
 
Example 23
@Outgoing(PRE_ACKNOWLEDGMENT_UNI)
public Publisher<Message<String>> sourceToPreAckUNI() {
    return Multi.createFrom().items("a", "b", "c", "d", "e")
            .map(payload -> Message.of(payload, () -> {
                nap();
                acknowledged(PRE_ACKNOWLEDGMENT_UNI, payload);
                return CompletableFuture.completedFuture(null);
            }));
}
 
Example 24
@Incoming(MANUAL_ACKNOWLEDGMENT)
@Acknowledgment(Acknowledgment.Strategy.MANUAL)
public CompletionStage<Void> subWithAck(Message<String> message) {
    processed(MANUAL_ACKNOWLEDGMENT, message.getPayload());
    // We cannot return a value or void by spec
    // So we return the CompletionStage<Void>.
    return message.ack();
}
 
Example 25
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 26
Source Project: smallrye-reactive-messaging   Source File: StreamSkip.java    License: 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 27
@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 28
@Incoming("a")
@Incoming("b")
@Incoming("c")
@Outgoing("out")
public Message<String> process(Message<String> s) {
    return Message.of(s.getPayload().toUpperCase());
}
 
Example 29
@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 30
@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);
            }));
}