Example usage for com.rabbitmq.client Delivery Delivery

List of usage examples for com.rabbitmq.client Delivery Delivery

Introduction

In this page you can find the example usage for com.rabbitmq.client Delivery Delivery.

Prototype

public Delivery(Envelope envelope, AMQP.BasicProperties properties, byte[] body) 

Source Link

Usage

From source file:org.eclipse.ditto.services.connectivity.messaging.rabbitmq.RabbitMQConsumerActorTest.java

License:Open Source License

@Override
protected Delivery getInboundMessage(final Map.Entry<String, Object> header) {
    final Map<String, Object> headers = new HashMap<>();
    headers.put(REPLY_TO_HEADER.getKey(), REPLY_TO_HEADER.getValue());
    headers.put(header.getKey(), header.getValue());

    return new Delivery(ENVELOPE,
            new AMQP.BasicProperties.Builder().contentType(DittoConstants.DITTO_PROTOCOL_CONTENT_TYPE)
                    .headers(headers).replyTo(REPLY_TO_HEADER.getValue()).build(),
            TestConstants.modifyThing().getBytes(StandardCharsets.UTF_8));
}

From source file:reactor.rabbitmq.ConnectionRecoveryTests.java

License:Open Source License

@Test
void consumeAutoAckRetryOnAck() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);
    when(mockConnectionFactory.newConnection()).thenReturn(mockConnection);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    CountDownLatch consumerRegisteredLatch = new CountDownLatch(1);
    AtomicReference<DeliverCallback> deliverCallbackAtomicReference = new AtomicReference<>();

    when(mockChannel.basicConsume(anyString(), anyBoolean(), any(DeliverCallback.class),
            any(CancelCallback.class))).thenAnswer(answer -> {
                deliverCallbackAtomicReference.set(answer.getArgument(2));
                consumerRegisteredLatch.countDown();
                return "ctag";
            });//ww  w .j av  a2s  . co  m

    AtomicLong ackCount = new AtomicLong(0);
    AtomicLong errorAck = new AtomicLong(0);
    doAnswer(answer -> {
        ackCount.incrementAndGet();
        if (ackCount.get() == 3 || ackCount.get() == 4) {
            errorAck.incrementAndGet();
            throw new AlreadyClosedException(new ShutdownSignalException(true, false, null, null));
        }
        return null;
    }).when(mockChannel).basicAck(anyLong(), anyBoolean());

    receiver = RabbitFlux.createReceiver(new ReceiverOptions().connectionSupplier(cf -> mockConnection));

    AtomicInteger ackedMessages = new AtomicInteger(0);
    receiver.consumeAutoAck("whatever",
            new ConsumeOptions().exceptionHandler(new ExceptionHandlers.RetryAcknowledgmentExceptionHandler(
                    ofSeconds(5), ofMillis(100), ExceptionHandlers.CONNECTION_RECOVERY_PREDICATE)))
            .subscribe(msg -> {
                ackedMessages.incrementAndGet();
            });

    assertTrue(consumerRegisteredLatch.await(1, TimeUnit.SECONDS),
            "Consumer should have been registered by now");

    int nbMessages = 10;
    IntStream.range(0, nbMessages).forEach(i -> {
        try {
            deliverCallbackAtomicReference.get().handle("",
                    new Delivery(new Envelope(i, true, null, null), null, null));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    assertEquals(nbMessages, ackedMessages.get(), "All messages should have been ack-ed, as ack is retried");
    assertEquals(nbMessages + errorAck.get(), ackCount.get(),
            "There should have been nbMessages+ackInError calls to basicAck as acknowledgments are retried");
}

From source file:reactor.rabbitmq.ConnectionRecoveryTests.java

License:Open Source License

@Test
void consumeManualAckRetryOnAck() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);
    when(mockConnectionFactory.newConnection()).thenReturn(mockConnection);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    CountDownLatch consumerRegisteredLatch = new CountDownLatch(1);
    AtomicReference<DeliverCallback> deliverCallbackAtomicReference = new AtomicReference<>();

    when(mockChannel.basicConsume(anyString(), anyBoolean(), any(DeliverCallback.class),
            any(CancelCallback.class))).thenAnswer(answer -> {
                deliverCallbackAtomicReference.set(answer.getArgument(2));
                consumerRegisteredLatch.countDown();
                return "ctag";
            });/* w ww . j  a  v a  2  s .  c  o  m*/

    AtomicLong ackCount = new AtomicLong(0);
    doAnswer(answer -> {
        ackCount.incrementAndGet();
        if (ackCount.get() == 3 || ackCount.get() == 4) {
            throw new AlreadyClosedException(new ShutdownSignalException(true, false, null, null));
        }
        return null;
    }).when(mockChannel).basicAck(anyLong(), anyBoolean());

    receiver = RabbitFlux.createReceiver(new ReceiverOptions().connectionSupplier(cf -> mockConnection));

    AtomicInteger ackedMessages = new AtomicInteger(0);
    BiConsumer<Receiver.AcknowledgmentContext, Exception> exceptionHandler = new ExceptionHandlers.RetryAcknowledgmentExceptionHandler(
            ofSeconds(5), ofMillis(100), ExceptionHandlers.CONNECTION_RECOVERY_PREDICATE);
    receiver.consumeManualAck("whatever", new ConsumeOptions().exceptionHandler(exceptionHandler))
            .subscribe(msg -> {
                // do business stuff
                // ...
                // trying to ack
                msg.ack();
                ackedMessages.incrementAndGet();
            });

    assertTrue(consumerRegisteredLatch.await(1, TimeUnit.SECONDS),
            "Consumer should have been registered by now");

    int nbMessages = 10;
    IntStream.range(0, nbMessages).forEach(i -> {
        try {
            deliverCallbackAtomicReference.get().handle("",
                    new Delivery(new Envelope(i, true, null, null), null, null));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });

    assertEquals(nbMessages, ackedMessages.get(), "All messages should have been ack-ed, as ack is retried");
}

From source file:reactor.rabbitmq.RabbitFluxTests.java

License:Open Source License

@Test
public void acknowledgableDeliveryAckNackIsIdempotent() throws Exception {
    Channel channel = mock(Channel.class);
    BiConsumer<Receiver.AcknowledgmentContext, Exception> exceptionHandler = mock(
            ExceptionHandlers.RetryAcknowledgmentExceptionHandler.class);
    doNothing().doThrow(new IOException()).when(channel).basicAck(anyLong(), anyBoolean());
    doThrow(new IOException()).when(channel).basicNack(anyLong(), anyBoolean(), anyBoolean());
    AcknowledgableDelivery msg = new AcknowledgableDelivery(
            new Delivery(new Envelope(0, true, null, null), null, null), channel, exceptionHandler);

    msg.ack();//w w  w. j av a 2 s  .  c o m
    msg.ack();
    msg.nack(false);
    msg.nack(false);

    verify(channel, times(1)).basicAck(anyLong(), anyBoolean());
    verify(channel, never()).basicNack(anyLong(), anyBoolean(), anyBoolean());
    verify(exceptionHandler, never()).accept(any(Receiver.AcknowledgmentContext.class), any(Exception.class));
}

From source file:reactor.rabbitmq.RabbitFluxTests.java

License:Open Source License

@Test
public void acknowledgableDeliveryWithSuccessfulRetry() throws Exception {
    Channel channel = mock(Channel.class);
    BiConsumer<Receiver.AcknowledgmentContext, Exception> exceptionHandler = (acknowledgmentContext,
            e) -> acknowledgmentContext.ackOrNack();

    doThrow(new IOException()).doNothing().when(channel).basicAck(anyLong(), anyBoolean());

    AcknowledgableDelivery msg = new AcknowledgableDelivery(
            new Delivery(new Envelope(0, true, null, null), null, null), channel, exceptionHandler);

    msg.ack();/*from   w  w  w  . j  a va 2s.c o  m*/

    verify(channel, times(2)).basicAck(anyLong(), anyBoolean());
}

From source file:reactor.rabbitmq.RabbitFluxTests.java

License:Open Source License

@Test
public void acknowledgableDeliveryWithUnsuccessfulRetry() throws Exception {
    Channel channel = mock(Channel.class);
    BiConsumer<Receiver.AcknowledgmentContext, Exception> exceptionHandler = (acknowledgmentContext,
            e) -> acknowledgmentContext.ackOrNack();

    doThrow(new RuntimeException("exc")).when(channel).basicAck(anyLong(), anyBoolean());

    AcknowledgableDelivery msg = new AcknowledgableDelivery(
            new Delivery(new Envelope(0, true, null, null), null, null), channel, exceptionHandler);

    assertThatThrownBy(msg::ack).hasMessage("exc");

    verify(channel, times(2)).basicAck(anyLong(), anyBoolean());
}

From source file:reactor.rabbitmq.Receiver.java

License:Open Source License

public Flux<Delivery> consumeNoAck(final String queue, ReceiverOptions options) {
    // TODO track flux so it can be disposed when the sender is closed?
    // could be also developer responsibility
    return Flux.create(emitter -> {
        connectionMono.subscribe(connection -> {
            try {
                // TODO handle exception
                Channel channel = connection.createChannel();
                final DefaultConsumer consumer = new DefaultConsumer(channel) {
                    @Override//ww  w  .jav a  2  s .  co  m
                    public void handleDelivery(String consumerTag, Envelope envelope,
                            AMQP.BasicProperties properties, byte[] body) throws IOException {
                        emitter.next(new Delivery(envelope, properties, body));
                    }

                    @Override
                    public void handleCancel(String consumerTag) throws IOException {
                        LOGGER.warn("Flux consumer {} has been cancelled", consumerTag);
                    }
                };
                final String consumerTag = channel.basicConsume(queue, true, consumer);
                emitter.onDispose(() -> {
                    try {
                        if (channel.isOpen() && channel.getConnection().isOpen()) {
                            channel.basicCancel(consumerTag);
                            channel.close();
                        }
                    } catch (TimeoutException | IOException e) {
                        throw new ReactorRabbitMqException(e);
                    }
                });
            } catch (IOException e) {
                throw new ReactorRabbitMqException(e);
            }
        });

    }, options.getOverflowStrategy());
}