Search in sources :

Example 1 with MessageBuilder

use of com.rabbitmq.stream.MessageBuilder in project rabbitmq-stream-java-client by rabbitmq.

the class CodecsTest method codecs.

@ParameterizedTest
@MethodSource("codecsCouples")
void codecs(CodecCouple codecCouple) {
    Codec serializer = codecCouple.serializer;
    Codec deserializer = codecCouple.deserializer;
    Stream<MessageTestConfiguration> messageOperations = Stream.of(test(builder -> builder.properties().messageId(42).messageBuilder(), message -> assertThat(message.getProperties().getMessageIdAsLong()).isEqualTo(42)), test(builder -> builder.properties().messageId("foo").messageBuilder(), message -> assertThat(message.getProperties().getMessageIdAsString()).isEqualTo("foo")), test(builder -> builder.properties().messageId("bar".getBytes(CHARSET)).messageBuilder(), message -> assertThat(message.getProperties().getMessageIdAsBinary()).isEqualTo("bar".getBytes(CHARSET))), test(builder -> builder.properties().messageId(TEST_UUID).messageBuilder(), message -> assertThat(message.getProperties().getMessageIdAsUuid()).isEqualTo(TEST_UUID)), test(builder -> builder.properties().correlationId(42 + 10).messageBuilder(), message -> assertThat(message.getProperties().getCorrelationIdAsLong()).isEqualTo(42 + 10)), test(builder -> builder.properties().correlationId("correlation foo").messageBuilder(), message -> assertThat(message.getProperties().getCorrelationIdAsString()).isEqualTo("correlation foo")), test(builder -> builder.properties().correlationId("correlation bar".getBytes(CHARSET)).messageBuilder(), message -> assertThat(message.getProperties().getCorrelationIdAsBinary()).isEqualTo("correlation bar".getBytes(CHARSET))), test(builder -> builder.properties().correlationId(TEST_UUID).messageBuilder(), message -> assertThat(message.getProperties().getCorrelationIdAsUuid()).isEqualTo(TEST_UUID)), test(builder -> builder, message -> assertThat(message.getProperties().getGroupSequence()).isEqualTo(-1)), test(builder -> builder.properties().groupSequence(10).messageBuilder(), message -> assertThat(message.getProperties().getGroupSequence()).isEqualTo(10)), test(builder -> builder.properties().groupSequence((long) Integer.MAX_VALUE + 10).messageBuilder(), message -> assertThat(message.getProperties().getGroupSequence()).isEqualTo((long) Integer.MAX_VALUE + 10)));
    String body = "hello";
    String userId = "yoda";
    String to = "the to address";
    String subject = "the subject";
    String replyTo = "the reply to";
    String contentType = "text/plain";
    String contentEncoding = "gzip";
    String groupId = "the group ID";
    String replyToGroupId = "the reply to group ID";
    long now = new Date().getTime();
    UUID uuid = UUID.randomUUID();
    byte[] binary = "the binary".getBytes(CHARSET);
    String string = "a string";
    String symbol = "a symbol";
    messageOperations.forEach(messageTestConfiguration -> {
        Function<MessageBuilder, MessageBuilder> messageOperation = messageTestConfiguration.messageOperation;
        Consumer<Message> messageExpectation = messageTestConfiguration.messageExpectation;
        MessageBuilder messageBuilder = codecCouple.messageBuilderSupplier.get();
        Message outboundMessage = messageOperation.apply(messageBuilder).addData(body.getBytes(CHARSET)).properties().userId(userId.getBytes(CHARSET)).to(to).subject(subject).replyTo(replyTo).contentType(contentType).contentEncoding(contentEncoding).absoluteExpiryTime(now + 1000).creationTime(now).groupId(groupId).replyToGroupId(replyToGroupId).messageBuilder().applicationProperties().entry("boolean", Boolean.FALSE).entry("byte", (byte) 1).entry("short", (short) 2).entry("int", 3).entry("long", 4l).entryUnsigned("ubyte", (byte) 1).entryUnsigned("ushort", (short) 2).entryUnsigned("uint", 3).entryUnsigned("ulong", 4l).entryUnsigned("large.ubyte", (byte) (Byte.MAX_VALUE + 10)).entryUnsigned("large.ushort", (short) (Short.MAX_VALUE + 10)).entryUnsigned("large.uint", Integer.MAX_VALUE + 10).entryUnsigned("large.ulong", Long.MAX_VALUE + 10).entry("float", 3.14f).entry("double", 6.28).entry("char", 'c').entryTimestamp("timestamp", now).entry("uuid", uuid).entry("binary", binary).entry("string", string).entrySymbol("symbol", symbol).messageBuilder().messageAnnotations().entry("annotations.boolean", Boolean.FALSE).entry("annotations.byte", (byte) 1).entry("annotations.short", (short) 2).entry("annotations.int", 3).entry("annotations.long", 4l).entryUnsigned("annotations.ubyte", (byte) 1).entryUnsigned("annotations.ushort", (short) 2).entryUnsigned("annotations.uint", 3).entryUnsigned("annotations.ulong", 4l).entryUnsigned("annotations.large.ubyte", (byte) (Byte.MAX_VALUE + 10)).entryUnsigned("annotations.large.ushort", (short) (Short.MAX_VALUE + 10)).entryUnsigned("annotations.large.uint", Integer.MAX_VALUE + 10).entryUnsigned("annotations.large.ulong", Long.MAX_VALUE + 10).entry("annotations.float", 3.14f).entry("annotations.double", 6.28).entry("annotations.char", 'c').entryTimestamp("annotations.timestamp", now).entry("annotations.uuid", uuid).entry("annotations.binary", binary).entry("annotations.string", string).entrySymbol("annotations.symbol", symbol).messageBuilder().build();
        Codec.EncodedMessage encoded = serializer.encode(outboundMessage);
        byte[] encodedData = new byte[encoded.getSize()];
        System.arraycopy(encoded.getData(), 0, encodedData, 0, encoded.getSize());
        Message inboundMessage = deserializer.decode(encodedData);
        messageExpectation.accept(inboundMessage);
        assertThat(new String(inboundMessage.getBodyAsBinary())).isEqualTo(body);
        assertThat(inboundMessage.getProperties().getUserId()).isEqualTo(userId.getBytes(CHARSET));
        assertThat(inboundMessage.getProperties().getTo()).isEqualTo(to);
        assertThat(inboundMessage.getProperties().getSubject()).isEqualTo(subject);
        assertThat(inboundMessage.getProperties().getReplyTo()).isEqualTo(replyTo);
        assertThat(inboundMessage.getProperties().getContentType()).isEqualTo(contentType);
        assertThat(inboundMessage.getProperties().getContentEncoding()).isEqualTo(contentEncoding);
        assertThat(inboundMessage.getProperties().getAbsoluteExpiryTime()).isEqualTo(now + 1000);
        assertThat(inboundMessage.getProperties().getCreationTime()).isEqualTo(now);
        assertThat(inboundMessage.getProperties().getGroupId()).isEqualTo(groupId);
        assertThat(inboundMessage.getProperties().getReplyToGroupId()).isEqualTo(replyToGroupId);
        // application properties
        assertThat(inboundMessage.getApplicationProperties().get("boolean")).isNotNull().isInstanceOf(Boolean.class).isEqualTo(Boolean.FALSE);
        assertThat(inboundMessage.getApplicationProperties().get("byte")).isNotNull().isInstanceOf(Byte.class).isEqualTo(Byte.valueOf((byte) 1));
        assertThat(inboundMessage.getApplicationProperties().get("short")).isNotNull().isInstanceOf(Short.class).isEqualTo(Short.valueOf((short) 2));
        assertThat(inboundMessage.getApplicationProperties().get("int")).isNotNull().isInstanceOf(Integer.class).isEqualTo(Integer.valueOf(3));
        assertThat(inboundMessage.getApplicationProperties().get("long")).isNotNull().isInstanceOf(Long.class).isEqualTo(Long.valueOf(4));
        assertThat(inboundMessage.getApplicationProperties().get("ubyte")).isNotNull().isInstanceOf(UnsignedByte.class).isEqualTo(UnsignedByte.valueOf((byte) 1));
        assertThat(inboundMessage.getApplicationProperties().get("ushort")).isNotNull().isInstanceOf(UnsignedShort.class).isEqualTo(UnsignedShort.valueOf((short) 2));
        assertThat(inboundMessage.getApplicationProperties().get("uint")).isNotNull().isInstanceOf(UnsignedInteger.class).isEqualTo(UnsignedInteger.valueOf(3));
        assertThat(inboundMessage.getApplicationProperties().get("ulong")).isNotNull().isInstanceOf(UnsignedLong.class).isEqualTo(UnsignedLong.valueOf(4));
        assertThat(inboundMessage.getApplicationProperties().get("large.ubyte")).isNotNull().isInstanceOf(UnsignedByte.class).asInstanceOf(InstanceOfAssertFactories.type(UnsignedByte.class)).extracting(v -> v.intValue()).isEqualTo(Byte.MAX_VALUE + 10);
        assertThat(inboundMessage.getApplicationProperties().get("large.ushort")).isNotNull().isInstanceOf(UnsignedShort.class).asInstanceOf(InstanceOfAssertFactories.type(UnsignedShort.class)).extracting(v -> v.intValue()).isEqualTo(Short.MAX_VALUE + 10);
        assertThat(inboundMessage.getApplicationProperties().get("large.uint")).isNotNull().isInstanceOf(UnsignedInteger.class).asInstanceOf(InstanceOfAssertFactories.type(UnsignedInteger.class)).extracting(v -> v.toString()).isEqualTo(BigInteger.valueOf((long) Integer.MAX_VALUE + 10L).toString());
        assertThat(inboundMessage.getApplicationProperties().get("large.ulong")).isNotNull().isInstanceOf(UnsignedLong.class).asInstanceOf(InstanceOfAssertFactories.type(UnsignedLong.class)).extracting(v -> v.toString()).isEqualTo(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.TEN).toString());
        assertThat(inboundMessage.getApplicationProperties().get("float")).isNotNull().isInstanceOf(Float.class).isEqualTo(Float.valueOf(3.14f));
        assertThat(inboundMessage.getApplicationProperties().get("double")).isNotNull().isInstanceOf(Double.class).isEqualTo(Double.valueOf(6.28));
        assertThat(inboundMessage.getApplicationProperties().get("char")).isNotNull().isInstanceOf(Character.class).isEqualTo('c');
        assertThat(inboundMessage.getApplicationProperties().get("timestamp")).isNotNull().isInstanceOf(Long.class).isEqualTo(now);
        assertThat(inboundMessage.getApplicationProperties().get("uuid")).isNotNull().isInstanceOf(UUID.class).isEqualTo(uuid);
        assertThat(inboundMessage.getApplicationProperties().get("binary")).isNotNull().isInstanceOf(byte[].class).isEqualTo(binary);
        assertThat(inboundMessage.getApplicationProperties().get("string")).isNotNull().isInstanceOf(String.class).isEqualTo(string);
        assertThat(inboundMessage.getApplicationProperties().get("symbol")).isNotNull().isInstanceOf(String.class).isEqualTo(symbol);
        // message annotations
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.boolean")).isNotNull().isInstanceOf(Boolean.class).isEqualTo(Boolean.FALSE);
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.byte")).isNotNull().isInstanceOf(Byte.class).isEqualTo(Byte.valueOf((byte) 1));
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.short")).isNotNull().isInstanceOf(Short.class).isEqualTo(Short.valueOf((short) 2));
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.int")).isNotNull().isInstanceOf(Integer.class).isEqualTo(Integer.valueOf(3));
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.long")).isNotNull().isInstanceOf(Long.class).isEqualTo(Long.valueOf(4));
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.ubyte")).isNotNull().isInstanceOf(UnsignedByte.class).isEqualTo(UnsignedByte.valueOf((byte) 1));
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.ushort")).isNotNull().isInstanceOf(UnsignedShort.class).isEqualTo(UnsignedShort.valueOf((short) 2));
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.uint")).isNotNull().isInstanceOf(UnsignedInteger.class).isEqualTo(UnsignedInteger.valueOf(3));
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.ulong")).isNotNull().isInstanceOf(UnsignedLong.class).isEqualTo(UnsignedLong.valueOf(4));
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.large.ubyte")).isNotNull().isInstanceOf(UnsignedByte.class).asInstanceOf(InstanceOfAssertFactories.type(UnsignedByte.class)).extracting(v -> v.intValue()).isEqualTo(Byte.MAX_VALUE + 10);
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.large.ushort")).isNotNull().isInstanceOf(UnsignedShort.class).asInstanceOf(InstanceOfAssertFactories.type(UnsignedShort.class)).extracting(v -> v.intValue()).isEqualTo(Short.MAX_VALUE + 10);
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.large.uint")).isNotNull().isInstanceOf(UnsignedInteger.class).asInstanceOf(InstanceOfAssertFactories.type(UnsignedInteger.class)).extracting(v -> v.toString()).isEqualTo(BigInteger.valueOf((long) Integer.MAX_VALUE + 10L).toString());
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.large.ulong")).isNotNull().isInstanceOf(UnsignedLong.class).asInstanceOf(InstanceOfAssertFactories.type(UnsignedLong.class)).extracting(v -> v.toString()).isEqualTo(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.TEN).toString());
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.float")).isNotNull().isInstanceOf(Float.class).isEqualTo(Float.valueOf(3.14f));
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.double")).isNotNull().isInstanceOf(Double.class).isEqualTo(Double.valueOf(6.28));
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.char")).isNotNull().isInstanceOf(Character.class).isEqualTo('c');
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.timestamp")).isNotNull().isInstanceOf(Long.class).isEqualTo(now);
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.uuid")).isNotNull().isInstanceOf(UUID.class).isEqualTo(uuid);
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.binary")).isNotNull().isInstanceOf(byte[].class).isEqualTo(binary);
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.string")).isNotNull().isInstanceOf(String.class).isEqualTo(string);
        assertThat(inboundMessage.getMessageAnnotations().get("annotations.symbol")).isNotNull().isInstanceOf(String.class).isEqualTo(symbol);
    });
}
Also used : Arrays(java.util.Arrays) EncodedMessage(com.rabbitmq.stream.Codec.EncodedMessage) UnsignedInteger(com.rabbitmq.stream.amqp.UnsignedInteger) Message(com.rabbitmq.stream.Message) Date(java.util.Date) InstanceOfAssertFactories(org.assertj.core.api.InstanceOfAssertFactories) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Codec(com.rabbitmq.stream.Codec) UnsignedByte(com.rabbitmq.stream.amqp.UnsignedByte) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) BigDecimal(java.math.BigDecimal) Assertions.assertThatThrownBy(org.assertj.core.api.Assertions.assertThatThrownBy) UnsignedLong(com.rabbitmq.stream.amqp.UnsignedLong) Charset(java.nio.charset.Charset) AmqpValue(org.apache.qpid.proton.amqp.messaging.AmqpValue) BigInteger(java.math.BigInteger) MethodSource(org.junit.jupiter.params.provider.MethodSource) ThrowableAssert(org.assertj.core.api.ThrowableAssert) Mockito.when(org.mockito.Mockito.when) UUID(java.util.UUID) StandardCharsets(java.nio.charset.StandardCharsets) Consumer(java.util.function.Consumer) List(java.util.List) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Stream(java.util.stream.Stream) MessageBuilder(com.rabbitmq.stream.MessageBuilder) QpidProtonAmqpMessageWrapper(com.rabbitmq.stream.codec.QpidProtonCodec.QpidProtonAmqpMessageWrapper) UnsignedShort(com.rabbitmq.stream.amqp.UnsignedShort) Mockito.mock(org.mockito.Mockito.mock) EncodedMessage(com.rabbitmq.stream.Codec.EncodedMessage) Message(com.rabbitmq.stream.Message) Codec(com.rabbitmq.stream.Codec) MessageBuilder(com.rabbitmq.stream.MessageBuilder) UUID(java.util.UUID) UnsignedShort(com.rabbitmq.stream.amqp.UnsignedShort) UnsignedShort(com.rabbitmq.stream.amqp.UnsignedShort) UnsignedLong(com.rabbitmq.stream.amqp.UnsignedLong) UnsignedByte(com.rabbitmq.stream.amqp.UnsignedByte) Date(java.util.Date) UnsignedInteger(com.rabbitmq.stream.amqp.UnsignedInteger) BigInteger(java.math.BigInteger) UnsignedByte(com.rabbitmq.stream.amqp.UnsignedByte) UnsignedLong(com.rabbitmq.stream.amqp.UnsignedLong) UnsignedInteger(com.rabbitmq.stream.amqp.UnsignedInteger) EncodedMessage(com.rabbitmq.stream.Codec.EncodedMessage) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 2 with MessageBuilder

use of com.rabbitmq.stream.MessageBuilder in project rabbitmq-stream-java-client by rabbitmq.

the class AmqpInteroperabilityTest method publishToStreamConsumeFromStreamQueue.

@ParameterizedTest
@MethodSource("codecs")
void publishToStreamConsumeFromStreamQueue(Codec codec, TestInfo info) {
    int messageCount = 1_000;
    ConnectionFactory connectionFactory = new ConnectionFactory();
    Date timestamp = new Date();
    UUID messageIdUuid = UUID.randomUUID();
    UUID correlationIdUuid = UUID.randomUUID();
    Supplier<Stream<MessageOperation>> testMessageOperations = () -> Stream.of(mo(mb -> {
        mb.properties().messageId("the message ID");
        mb.properties().correlationId("the correlation ID");
    }, d -> {
        assertThat(d.getProperties().getMessageId()).isEqualTo("the message ID");
        assertThat(d.getProperties().getCorrelationId()).isEqualTo("the correlation ID");
    }), mo(mb -> {
        mb.properties().messageId(// larger than 091 shortstr
        StringUtils.repeat("*", 300));
        mb.properties().correlationId(// larger than 091 shortstr
        StringUtils.repeat("*", 300));
    }, d -> {
        assertThat(d.getProperties().getMessageId()).isNull();
        assertThat(d.getProperties().getCorrelationId()).isNull();
        assertThat(d.getProperties().getHeaders()).containsEntry("x-message-id", LongStringHelper.asLongString(StringUtils.repeat("*", 300))).containsEntry("x-correlation-id", LongStringHelper.asLongString(StringUtils.repeat("*", 300)));
    }), mo(mb -> {
        mb.properties().messageId(messageIdUuid);
        mb.properties().correlationId(correlationIdUuid);
    }, d -> {
        assertThat(d.getProperties().getMessageId()).isEqualTo(messageIdUuid.toString());
        assertThat(d.getProperties().getCorrelationId()).isEqualTo(correlationIdUuid.toString());
        assertThat(d.getProperties().getHeaders()).containsEntry("x-message-id-type", LongStringHelper.asLongString("uuid")).containsEntry("x-correlation-id-type", LongStringHelper.asLongString("uuid"));
    }), mo(mb -> {
        mb.properties().messageId(10);
        mb.properties().correlationId(20);
    }, d -> {
        assertThat(d.getProperties().getMessageId()).isEqualTo("10");
        assertThat(d.getProperties().getCorrelationId()).isEqualTo("20");
        assertThat(d.getProperties().getHeaders()).containsEntry("x-message-id-type", LongStringHelper.asLongString("ulong")).containsEntry("x-correlation-id-type", LongStringHelper.asLongString("ulong"));
    }), mo(mb -> {
        mb.properties().messageId("the message ID".getBytes(UTF8));
        mb.properties().correlationId("the correlation ID".getBytes(UTF8));
    }, d -> {
        assertThat(Base64.getDecoder().decode(d.getProperties().getMessageId())).isEqualTo("the message ID".getBytes(UTF8));
        assertThat(Base64.getDecoder().decode(d.getProperties().getCorrelationId())).isEqualTo("the correlation ID".getBytes(UTF8));
        assertThat(d.getProperties().getHeaders()).containsEntry("x-message-id-type", LongStringHelper.asLongString("binary")).containsEntry("x-correlation-id-type", LongStringHelper.asLongString("binary"));
    }), mo(mb -> {
        mb.properties().messageId(StringUtils.repeat("a", 300).getBytes(// larger than 091 shortstr
        UTF8));
        mb.properties().correlationId(StringUtils.repeat("b", 300).getBytes(// larger than 091 shortstr
        UTF8));
    }, d -> {
        assertThat(d.getProperties().getMessageId()).isNull();
        assertThat(d.getProperties().getCorrelationId()).isNull();
        assertThat(d.getProperties().getHeaders()).containsEntry("x-message-id", LongStringHelper.asLongString(StringUtils.repeat("a", 300).getBytes(UTF8))).containsEntry("x-correlation-id", LongStringHelper.asLongString(StringUtils.repeat("b", 300).getBytes(UTF8)));
    }));
    testMessageOperations.get().forEach(testMessageOperation -> {
        CountDownLatch confirmLatch = new CountDownLatch(messageCount);
        Client client = cf.get(new Client.ClientParameters().codec(codec).publishConfirmListener((publisherId, publishingId) -> confirmLatch.countDown()));
        String s = streamName(info);
        Client.Response response = client.create(s);
        assertThat(response.isOk()).isTrue();
        Supplier<Stream<MessageOperation>> messageOperations = () -> Stream.of(mo(mb -> mb.properties().userId("the user ID".getBytes(UTF8)), d -> assertThat(d.getProperties().getUserId()).isEqualTo("the user ID")), mo(mb -> mb.properties().to("the to address"), d -> {
        }), mo(mb -> mb.properties().subject("the subject"), d -> {
        }), mo(mb -> mb.properties().replyTo("the reply to address"), d -> assertThat(d.getProperties().getReplyTo()).isEqualTo("the reply to address")), mo(mb -> mb.properties().contentType("the content type"), d -> assertThat(d.getProperties().getContentType()).isEqualTo("the content type")), mo(mb -> mb.properties().contentEncoding("the content encoding"), d -> assertThat(d.getProperties().getContentEncoding()).isEqualTo("the content encoding")), mo(mb -> mb.properties().absoluteExpiryTime(timestamp.getTime() + 1000), d -> {
        }), mo(mb -> mb.properties().creationTime(timestamp.getTime()), d -> assertThat(d.getProperties().getTimestamp().getTime()).isEqualTo((timestamp.getTime() / 1000) * // in seconds in 091, in ms in 1.0, so losing
        1000)), mo(mb -> mb.properties().groupId("the group ID"), d -> {
        }), mo(mb -> mb.properties().groupSequence(10), d -> {
        }), mo(mb -> mb.properties().replyToGroupId("the reply to group ID"), d -> {
        }), mo(mb -> mb.applicationProperties().entry("byte", Byte.MAX_VALUE), d -> assertThat(d.getProperties().getHeaders()).containsEntry("byte", Byte.MAX_VALUE)), mo(mb -> mb.applicationProperties().entry("short", Short.MAX_VALUE), d -> assertThat(d.getProperties().getHeaders()).containsEntry("short", Short.MAX_VALUE)), mo(mb -> mb.applicationProperties().entry("integer", Integer.MAX_VALUE), d -> assertThat(d.getProperties().getHeaders()).containsEntry("integer", Integer.MAX_VALUE)), mo(mb -> mb.applicationProperties().entry("long", Long.MAX_VALUE), d -> assertThat(d.getProperties().getHeaders()).containsEntry("long", Long.MAX_VALUE)), mo(mb -> mb.applicationProperties().entry("string", "a string"), d -> assertThat(d.getProperties().getHeaders()).containsEntry("string", LongStringHelper.asLongString("a string"))), mo(mb -> mb.applicationProperties().entryTimestamp("timestamp", timestamp.getTime()), d -> assertThat(d.getProperties().getHeaders()).containsEntry("timestamp", new Date((timestamp.getTime() / 1000) * 1000))), mo(mb -> mb.applicationProperties().entry("boolean", Boolean.TRUE), d -> assertThat(d.getProperties().getHeaders()).containsEntry("boolean", Boolean.TRUE)), mo(mb -> mb.applicationProperties().entry("float", 3.14f), d -> assertThat(d.getProperties().getHeaders()).containsEntry("float", 3.14f)), mo(mb -> mb.applicationProperties().entry("binary", "hello".getBytes(UTF8)), d -> assertThat(d.getProperties().getHeaders()).containsEntry("binary", "hello".getBytes(UTF8))));
        client.declarePublisher(b(1), null, s);
        IntStream.range(0, messageCount).forEach(i -> {
            MessageBuilder messageBuilder = client.messageBuilder();
            messageBuilder.addData(("stream " + i).getBytes(UTF8));
            testMessageOperation.messageBuilderConsumer.accept(messageBuilder);
            messageOperations.get().forEach(messageOperation -> messageOperation.messageBuilderConsumer.accept(messageBuilder));
            client.publish(b(1), Collections.singletonList(messageBuilder.build()));
        });
        try (Connection c = connectionFactory.newConnection()) {
            assertThat(confirmLatch.await(10, SECONDS)).isTrue();
            Channel ch = c.createChannel();
            ch.basicQos(200);
            CountDownLatch consumedLatch = new CountDownLatch(messageCount);
            Set<String> messageBodies = ConcurrentHashMap.newKeySet(messageCount);
            Set<Delivery> messages = ConcurrentHashMap.newKeySet(messageCount);
            ch.basicConsume(s, false, Collections.singletonMap("x-stream-offset", 0), (consumerTag, message) -> {
                messages.add(message);
                messageBodies.add(new String(message.getBody(), UTF8));
                consumedLatch.countDown();
                ch.basicAck(message.getEnvelope().getDeliveryTag(), false);
            }, consumerTag -> {
            });
            assertThat(consumedLatch.await(10, SECONDS)).isTrue();
            assertThat(messageBodies).hasSize(messageCount);
            IntStream.range(0, messageCount).forEach(i -> assertThat(messageBodies.contains("stream " + i)).isTrue());
            Delivery message = messages.iterator().next();
            assertThat(message.getEnvelope().getExchange()).isEmpty();
            assertThat(message.getEnvelope().getRoutingKey()).isEqualTo(s);
            assertThat(message.getProperties().getHeaders()).containsKey("x-stream-offset");
            testMessageOperation.deliveryConsumer.accept(message);
            messageOperations.get().forEach(messageOperation -> messageOperation.deliveryConsumer.accept(message));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        response = client.delete(s);
        assertThat(response.isOk()).isTrue();
    });
}
Also used : IntStream(java.util.stream.IntStream) java.util(java.util) Message(com.rabbitmq.stream.Message) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Codec(com.rabbitmq.stream.Codec) QpidProtonCodec(com.rabbitmq.stream.codec.QpidProtonCodec) UnsignedByte(com.rabbitmq.stream.amqp.UnsignedByte) Supplier(java.util.function.Supplier) StringUtils(org.apache.commons.lang3.StringUtils) TestUtils.b(com.rabbitmq.stream.impl.TestUtils.b) TestUtils.streamName(com.rabbitmq.stream.impl.TestUtils.streamName) Charset(java.nio.charset.Charset) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) SwiftMqCodec(com.rabbitmq.stream.codec.SwiftMqCodec) MethodSource(org.junit.jupiter.params.provider.MethodSource) LongStringHelper(com.rabbitmq.client.impl.LongStringHelper) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) com.rabbitmq.client(com.rabbitmq.client) StandardCharsets(java.nio.charset.StandardCharsets) TestInfo(org.junit.jupiter.api.TestInfo) Consumer(java.util.function.Consumer) CountDownLatch(java.util.concurrent.CountDownLatch) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) Stream(java.util.stream.Stream) MessageBuilder(com.rabbitmq.stream.MessageBuilder) SECONDS(java.util.concurrent.TimeUnit.SECONDS) OffsetSpecification(com.rabbitmq.stream.OffsetSpecification) CountDownLatch(java.util.concurrent.CountDownLatch) MessageBuilder(com.rabbitmq.stream.MessageBuilder) IntStream(java.util.stream.IntStream) Stream(java.util.stream.Stream) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 3 with MessageBuilder

use of com.rabbitmq.stream.MessageBuilder in project rabbitmq-stream-java-client by rabbitmq.

the class TestUtils method publishAndWaitForConfirms.

static void publishAndWaitForConfirms(TestUtils.ClientFactory cf, Function<MessageBuilder, Message> messageFactory, int publishCount, String stream) {
    CountDownLatch latchConfirm = new CountDownLatch(publishCount);
    Client.PublishConfirmListener publishConfirmListener = (publisherId, correlationId) -> latchConfirm.countDown();
    Client client = cf.get(new Client.ClientParameters().publishConfirmListener(publishConfirmListener));
    client.declarePublisher(b(1), null, stream);
    for (int i = 1; i <= publishCount; i++) {
        Message message = messageFactory.apply(client.messageBuilder());
        client.publish(b(1), Collections.singletonList(message));
    }
    try {
        assertThat(latchConfirm.await(60, SECONDS)).isTrue();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        throw new RuntimeException(e);
    }
}
Also used : Message(com.rabbitmq.stream.Message) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) LoggerFactory(org.slf4j.LoggerFactory) Connection(com.rabbitmq.client.Connection) ClientParameters(com.rabbitmq.stream.impl.Client.ClientParameters) AfterEachCallback(org.junit.jupiter.api.extension.AfterEachCallback) StreamException(com.rabbitmq.stream.StreamException) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) Duration(java.time.Duration) Map(java.util.Map) Documented(java.lang.annotation.Documented) Method(java.lang.reflect.Method) Host(com.rabbitmq.stream.Host) Tuple(io.vavr.Tuple) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) UUID(java.util.UUID) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) TestInfo(org.junit.jupiter.api.TestInfo) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Optional(java.util.Optional) MessageBuilder(com.rabbitmq.stream.MessageBuilder) Channel(com.rabbitmq.client.Channel) Constants(com.rabbitmq.stream.Constants) AnnotatedElement(java.lang.reflect.AnnotatedElement) Assertions.fail(org.junit.jupiter.api.Assertions.fail) IntStream(java.util.stream.IntStream) StreamMetadata(com.rabbitmq.stream.impl.Client.StreamMetadata) CloseableResource(org.junit.jupiter.api.extension.ExtensionContext.Store.CloseableResource) Address(com.rabbitmq.stream.Address) ExtensionContext(org.junit.jupiter.api.extension.ExtensionContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Retention(java.lang.annotation.Retention) ArrayList(java.util.ArrayList) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) AssertDelegateTarget(org.assertj.core.api.AssertDelegateTarget) ExecutorService(java.util.concurrent.ExecutorService) Namespace(org.junit.jupiter.api.extension.ExtensionContext.Namespace) EventLoopGroup(io.netty.channel.EventLoopGroup) Logger(org.slf4j.Logger) IOException(java.io.IOException) Target(java.lang.annotation.Target) Broker(com.rabbitmq.stream.impl.Client.Broker) ElementType(java.lang.annotation.ElementType) Field(java.lang.reflect.Field) InputStreamReader(java.io.InputStreamReader) BuiltinExchangeType(com.rabbitmq.client.BuiltinExchangeType) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) AtomicLong(java.util.concurrent.atomic.AtomicLong) Level(ch.qos.logback.classic.Level) ConditionEvaluationResult(org.junit.jupiter.api.extension.ConditionEvaluationResult) Tuple2(io.vavr.Tuple2) BeforeAllCallback(org.junit.jupiter.api.extension.BeforeAllCallback) ExecutionCondition(org.junit.jupiter.api.extension.ExecutionCondition) AfterAllCallback(org.junit.jupiter.api.extension.AfterAllCallback) Condition(org.assertj.core.api.Condition) BeforeEachCallback(org.junit.jupiter.api.extension.BeforeEachCallback) BufferedReader(java.io.BufferedReader) Collections(java.util.Collections) SECONDS(java.util.concurrent.TimeUnit.SECONDS) InputStream(java.io.InputStream) RetentionPolicy(java.lang.annotation.RetentionPolicy) ClientParameters(com.rabbitmq.stream.impl.Client.ClientParameters) Message(com.rabbitmq.stream.Message) CountDownLatch(java.util.concurrent.CountDownLatch)

Example 4 with MessageBuilder

use of com.rabbitmq.stream.MessageBuilder in project spring-amqp by spring-projects.

the class DefaultStreamMessageConverter method fromMessage.

@Override
public com.rabbitmq.stream.Message fromMessage(Message message) throws MessageConversionException {
    MessageBuilder builder = this.builderSupplier.get();
    PropertiesBuilder propsBuilder = builder.properties();
    MessageProperties props = message.getMessageProperties();
    Assert.isInstanceOf(StreamMessageProperties.class, props);
    StreamMessageProperties mProps = (StreamMessageProperties) props;
    JavaUtils.INSTANCE.acceptIfNotNull(mProps.getMessageId(), // TODO different types
    propsBuilder::messageId).acceptIfNotNull(mProps.getUserId(), usr -> propsBuilder.userId(usr.getBytes(this.charset))).acceptIfNotNull(mProps.getTo(), propsBuilder::to).acceptIfNotNull(mProps.getSubject(), propsBuilder::subject).acceptIfNotNull(mProps.getReplyTo(), propsBuilder::replyTo).acceptIfNotNull(mProps.getCorrelationId(), // TODO different types
    propsBuilder::correlationId).acceptIfNotNull(mProps.getContentType(), propsBuilder::contentType).acceptIfNotNull(mProps.getContentEncoding(), propsBuilder::contentEncoding).acceptIfNotNull(mProps.getExpiration(), exp -> propsBuilder.absoluteExpiryTime(Long.parseLong(exp))).acceptIfNotNull(mProps.getCreationTime(), propsBuilder::creationTime).acceptIfNotNull(mProps.getGroupId(), propsBuilder::groupId).acceptIfNotNull(mProps.getGroupSequence(), propsBuilder::groupSequence).acceptIfNotNull(mProps.getReplyToGroupId(), propsBuilder::replyToGroupId);
    if (mProps.getHeaders().size() > 0) {
        ApplicationPropertiesBuilder appPropsBuilder = builder.applicationProperties();
        mProps.getHeaders().forEach((key, val) -> {
            mapProp(key, val, appPropsBuilder);
        });
    }
    builder.addData(message.getBody());
    return builder.build();
}
Also used : StreamMessageProperties(org.springframework.rabbit.stream.support.StreamMessageProperties) Properties(com.rabbitmq.stream.Properties) ApplicationPropertiesBuilder(com.rabbitmq.stream.MessageBuilder.ApplicationPropertiesBuilder) PropertiesBuilder(com.rabbitmq.stream.MessageBuilder.PropertiesBuilder) Codec(com.rabbitmq.stream.Codec) MessageProperties(org.springframework.amqp.core.MessageProperties) UUID(java.util.UUID) Supplier(java.util.function.Supplier) StandardCharsets(java.nio.charset.StandardCharsets) WrapperMessageBuilder(com.rabbitmq.stream.codec.WrapperMessageBuilder) Charset(java.nio.charset.Charset) Map(java.util.Map) Message(org.springframework.amqp.core.Message) JavaUtils(org.springframework.amqp.utils.JavaUtils) Nullable(org.springframework.lang.Nullable) MessageBuilder(com.rabbitmq.stream.MessageBuilder) MessageConversionException(org.springframework.amqp.support.converter.MessageConversionException) Assert(org.springframework.util.Assert) WrapperMessageBuilder(com.rabbitmq.stream.codec.WrapperMessageBuilder) MessageBuilder(com.rabbitmq.stream.MessageBuilder) StreamMessageProperties(org.springframework.rabbit.stream.support.StreamMessageProperties) MessageProperties(org.springframework.amqp.core.MessageProperties) StreamMessageProperties(org.springframework.rabbit.stream.support.StreamMessageProperties) ApplicationPropertiesBuilder(com.rabbitmq.stream.MessageBuilder.ApplicationPropertiesBuilder) ApplicationPropertiesBuilder(com.rabbitmq.stream.MessageBuilder.ApplicationPropertiesBuilder) PropertiesBuilder(com.rabbitmq.stream.MessageBuilder.PropertiesBuilder)

Aggregations

MessageBuilder (com.rabbitmq.stream.MessageBuilder)4 StandardCharsets (java.nio.charset.StandardCharsets)4 Supplier (java.util.function.Supplier)4 Codec (com.rabbitmq.stream.Codec)3 Message (com.rabbitmq.stream.Message)3 Charset (java.nio.charset.Charset)3 UUID (java.util.UUID)3 Consumer (java.util.function.Consumer)3 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)3 UnsignedByte (com.rabbitmq.stream.amqp.UnsignedByte)2 Map (java.util.Map)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 SECONDS (java.util.concurrent.TimeUnit.SECONDS)2 IntStream (java.util.stream.IntStream)2 TestInfo (org.junit.jupiter.api.TestInfo)2 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)2 Level (ch.qos.logback.classic.Level)1 com.rabbitmq.client (com.rabbitmq.client)1 BuiltinExchangeType (com.rabbitmq.client.BuiltinExchangeType)1