Java Code Examples for org.eclipse.microprofile.reactive.messaging.Message#getPayload()

The following examples show how to use org.eclipse.microprofile.reactive.messaging.Message#getPayload() . 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: KafkaSink.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
private ProducerRecord<?, ?> getProducerRecord(Message<?> message, OutgoingKafkaRecordMetadata<?> om,
        String actualTopic) {
    int actualPartition = om == null || om.getPartition() <= -1 ? this.partition : om.getPartition();
    Object actualKey = om == null || om.getKey() == null ? key : om.getKey();

    long actualTimestamp;
    if ((om == null) || (om.getKey() == null)) {
        actualTimestamp = -1;
    } else {
        actualTimestamp = (om.getTimestamp() != null) ? om.getTimestamp().toEpochMilli() : -1;
    }

    Iterable<Header> kafkaHeaders = om == null || om.getHeaders() == null ? Collections.emptyList() : om.getHeaders();
    return new ProducerRecord<>(
            actualTopic,
            actualPartition == -1 ? null : actualPartition,
            actualTimestamp == -1L ? null : actualTimestamp,
            actualKey,
            message.getPayload(),
            kafkaHeaders);
}
 
Example 2
Source File: StreamSkip.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("in")
@Outgoing("out-2")
public Multi<Message<String>> processMessage(Message<String> m) {
    String s = m.getPayload();
    if (s.equalsIgnoreCase("skip")) {
        return Multi.createFrom().empty();
    }
    return Multi.createFrom().item(m.withPayload(s.toUpperCase()));
}
 
Example 3
Source File: SingleSkip.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("in")
@Outgoing("out")
public Message<String> processMessage(Message<String> m) {
    String s = m.getPayload();
    if (s.equalsIgnoreCase("skip")) {
        return null;
    }
    return m.withPayload(s.toUpperCase());
}
 
Example 4
Source File: SingleSkip.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("in")
@Outgoing("out")
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 5
Source File: MessageExamples.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
public void example1() {
    Message<String> message = Message.of("hello", Metadata.of(new MyMetadata()));
    // tag::message[]
    String payload = message.getPayload();
    Optional<MyMetadata> metadata = message.getMetadata(MyMetadata.class);
    // end::message[]
}
 
Example 6
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 7
Source File: DynamicTopicProducingBean.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("dyn-data")
@Outgoing("sink")
@Acknowledgment(Acknowledgment.Strategy.MANUAL)
public MqttMessage<String> process(Message<Integer> input) {
    String topic = "T" + input.getPayload();
    topics.add(topic);
    return MqttMessage.of(topic, input.getPayload().toString(), MqttQoS.AT_LEAST_ONCE, false).withAck(input::ack);
}
 
Example 8
Source File: StreamSkipTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("in")
@Outgoing("out-2")
public Multi<Message<String>> processMessage(Message<String> m) {
    String s = m.getPayload();
    if (s.equalsIgnoreCase("skip")) {
        return Multi.createFrom().empty();
    }
    return Multi.createFrom().item(m.withPayload(s.toUpperCase()));
}
 
Example 9
Source File: SingleSkipTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Incoming("in")
@Outgoing("out-2")
public Message<String> processMessage(Message<String> m) {
    String s = m.getPayload();
    if (s.equalsIgnoreCase("skip")) {
        return null;
    }
    return m.withPayload(s.toUpperCase());
}
 
Example 10
Source File: SingleSkipTest.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: MockedReceiver.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
/**
 * Expect the next message to have the given payload.
 */
public Message<T> expectNextMessageWithPayload(T payload) {
    Message<T> msg = receiveMessageWithPayload(payload, timeout.toMillis());
    if (!msg.getPayload().equals(payload)) {
        throw new AssertionError(
                "Expected a message on topic " + topic + " with payload " + payload + " but got " + msg.getPayload());
    }
    return msg;
}
 
Example 12
Source File: AppendingDecorator.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
private Message<?> appendString(Message<?> message, String string) {
    if (message.getPayload() instanceof String) {
        String payload = (String) message.getPayload();
        return Message.of(payload + "-" + string, message::ack);
    } else {
        return message;
    }
}
 
Example 13
Source File: OutgoingKafkaRecord.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static <K, T> OutgoingKafkaRecord<K, T> from(Message<T> message) {
    OutgoingKafkaRecordMetadata<K> kafkaMetadata = message
            .getMetadata(OutgoingKafkaRecordMetadata.class)
            .orElse(new OutgoingKafkaRecordMetadata<>(null, null, -1, null, null));

    return new OutgoingKafkaRecord<>(kafkaMetadata.getTopic(), kafkaMetadata.getKey(), message.getPayload(),
            kafkaMetadata.getTimestamp(), kafkaMetadata.getPartition(),
            kafkaMetadata.getHeaders(), message.getAck(), message.getNack(), message.getMetadata());
}
 
Example 14
Source File: AmqpMessageConverter.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
static io.vertx.mutiny.amqp.AmqpMessage convertToAmqpMessage(Message<?> message, boolean durable, long ttl) {
    Object payload = message.getPayload();
    Optional<OutgoingAmqpMetadata> metadata = message.getMetadata(OutgoingAmqpMetadata.class);
    AmqpMessageBuilder builder = io.vertx.mutiny.amqp.AmqpMessage.create();

    if (durable) {
        builder.durable(true);
    } else {
        builder.durable(metadata.map(OutgoingAmqpMetadata::isDurable).orElse(false));
    }

    if (ttl > 0) {
        builder.ttl(ttl);
    } else {
        long t = metadata.map(OutgoingAmqpMetadata::getTtl).orElse(-1L);
        if (t > 0) {
            builder.ttl(t);
        }
    }

    if (payload instanceof String) {
        builder.withBody((String) payload);
    } else if (payload instanceof Boolean) {
        builder.withBooleanAsBody((Boolean) payload);
    } else if (payload instanceof Buffer) {
        builder.withBufferAsBody((Buffer) payload);
    } else if (payload instanceof Byte) {
        builder.withByteAsBody((Byte) payload);
    } else if (payload instanceof Character) {
        builder.withCharAsBody((Character) payload);
    } else if (payload instanceof Double) {
        builder.withDoubleAsBody((Double) payload);
    } else if (payload instanceof Float) {
        builder.withFloatAsBody((Float) payload);
    } else if (payload instanceof Instant) {
        builder.withInstantAsBody((Instant) payload);
    } else if (payload instanceof Integer) {
        builder.withIntegerAsBody((Integer) payload);
    } else if (payload instanceof JsonArray) {
        builder.withJsonArrayAsBody((JsonArray) payload)
                .contentType(JSON_CONTENT_TYPE);
    } else if (payload instanceof JsonObject) {
        builder.withJsonObjectAsBody((JsonObject) payload)
                .contentType(JSON_CONTENT_TYPE);
    } else if (payload instanceof Long) {
        builder.withLongAsBody((Long) payload);
    } else if (payload instanceof Short) {
        builder.withShortAsBody((Short) payload);
    } else if (payload instanceof UUID) {
        builder.withUuidAsBody((UUID) payload);
    } else if (payload instanceof byte[]) {
        builder.withBufferAsBody(Buffer.buffer((byte[]) payload));
    } else {
        builder.withBufferAsBody(new Buffer(Json.encodeToBuffer(payload)))
                .contentType(JSON_CONTENT_TYPE);
    }

    metadata.ifPresent(new Consumer<OutgoingAmqpMetadata>() {
        @Override
        public void accept(OutgoingAmqpMetadata meta) {
            if (meta.getAddress() != null) {
                builder.address(meta.getAddress());
            }
            if (meta.getProperties() != null && !meta.getProperties().isEmpty()) {
                builder.applicationProperties(meta.getProperties());
            }
            if (meta.getContentEncoding() != null) {
                builder.contentEncoding(meta.getContentEncoding());
            }
            if (meta.getContentType() != null) {
                builder.contentType(meta.getContentType());
            }
            if (meta.getCorrelationId() != null) {
                builder.correlationId(meta.getCorrelationId());
            }
            if (meta.getId() != null) {
                builder.id(meta.getId());
            }
            if (meta.getGroupId() != null) {
                builder.groupId(meta.getGroupId());
            }
            if (meta.getPriority() >= 0) {
                builder.priority((short) meta.getPriority());
            }
            if (meta.getSubject() != null) {
                builder.subject(meta.getSubject());
            }
        }
    });
    return builder.build();
}
 
Example 15
Source File: JmsSink.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
private CompletionStage<Message<?>> send(Message<?> message) throws JMSException {
    Object payload = message.getPayload();

    // If the payload is a JMS Message, send it as it is, ignoring metadata.
    if (payload instanceof javax.jms.Message) {
        return dispatch(message, () -> producer.send(destination, (javax.jms.Message) payload));
    }

    javax.jms.Message outgoing;
    if (payload instanceof String || payload.getClass().isPrimitive() || isPrimitiveBoxed(payload.getClass())) {
        outgoing = context.createTextMessage(payload.toString());
        outgoing.setStringProperty("_classname", payload.getClass().getName());
        outgoing.setJMSType(payload.getClass().getName());
    } else if (payload.getClass().isArray() && payload.getClass().getComponentType().equals(Byte.TYPE)) {
        BytesMessage o = context.createBytesMessage();
        o.writeBytes((byte[]) payload);
        outgoing = o;
    } else {
        outgoing = context.createTextMessage(json.toJson(payload));
        outgoing.setJMSType(payload.getClass().getName());
        outgoing.setStringProperty("_classname", payload.getClass().getName());
    }

    OutgoingJmsMessageMetadata metadata = message.getMetadata(OutgoingJmsMessageMetadata.class).orElse(null);
    Destination actualDestination;
    if (metadata != null) {
        String correlationId = metadata.getCorrelationId();
        Destination replyTo = metadata.getReplyTo();
        Destination dest = metadata.getDestination();
        int deliveryMode = metadata.getDeliveryMode();
        String type = metadata.getType();
        JmsProperties properties = metadata.getProperties();
        if (correlationId != null) {
            outgoing.setJMSCorrelationID(correlationId);
        }
        if (replyTo != null) {
            outgoing.setJMSReplyTo(replyTo);
        }
        if (dest != null) {
            outgoing.setJMSDestination(dest);
        }
        if (deliveryMode != -1) {
            outgoing.setJMSDeliveryMode(deliveryMode);
        }
        if (type != null) {
            outgoing.setJMSType(type);
        }
        if (type != null) {
            outgoing.setJMSType(type);
        }

        if (properties != null) {
            if (!(properties instanceof JmsPropertiesBuilder.OutgoingJmsProperties)) {
                throw ex.illegalStateUnableToMapProperties(properties.getClass().getName());
            }
            JmsPropertiesBuilder.OutgoingJmsProperties op = ((JmsPropertiesBuilder.OutgoingJmsProperties) properties);
            op.getProperties().forEach(p -> p.apply(outgoing));
        }
        actualDestination = dest != null ? dest : this.destination;
    } else {
        actualDestination = this.destination;
    }

    return dispatch(message, () -> producer.send(actualDestination, outgoing));
}
 
Example 16
Source File: BeanConsumingMessagesAndReturningSomething.java    From smallrye-reactive-messaging with Apache License 2.0 4 votes vote down vote up
@Incoming("count")
public String consume(Message<String> message) {
    list.add(message.getPayload());
    return message.getPayload();
}