Example usage for com.rabbitmq.client Envelope Envelope

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

Introduction

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

Prototype

public Envelope(long deliveryTag, boolean redeliver, String exchange, String routingKey) 

Source Link

Document

Construct an Envelope with the specified construction parameters

Usage

From source file:org.springframework.integration.amqp.inbound.AmqpMessageSourceTests.java

License:Apache License

private void testNackOrRequeue(boolean requeue) throws Exception {
    Channel channel = mock(Channel.class);
    willReturn(true).given(channel).isOpen();
    Envelope envelope = new Envelope(123L, false, "ex", "rk");
    BasicProperties props = new BasicProperties.Builder().build();
    GetResponse getResponse = new GetResponse(envelope, props, "bar".getBytes(), 0);
    willReturn(getResponse).given(channel).basicGet("foo", false);
    Connection connection = mock(Connection.class);
    willReturn(true).given(connection).isOpen();
    willReturn(channel).given(connection).createChannel();
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    willReturn(connection).given(connectionFactory).newConnection((ExecutorService) isNull(), anyString());

    CachingConnectionFactory ccf = new CachingConnectionFactory(connectionFactory);
    AmqpMessageSource source = new AmqpMessageSource(ccf, "foo");
    Message<?> received = source.receive();
    verify(connection).createChannel();//from   w w w  .j  a  v a2  s .  c  o  m
    StaticMessageHeaderAccessor.getAcknowledgmentCallback(received)
            .acknowledge(requeue ? Status.REQUEUE : Status.REJECT);
    verify(channel).basicReject(123L, requeue);
    verify(connection).createChannel();
    ccf.destroy();
    verify(channel).close();
    verify(connection).close(30000);
}

From source file:org.springframework.integration.amqp.inbound.AmqpMessageSourceTests.java

License:Apache License

@SuppressWarnings({ "unchecked" })
@Test//from  w  w w. ja  va 2 s . c o  m
public void testBatch() throws Exception {
    SimpleBatchingStrategy bs = new SimpleBatchingStrategy(2, 10_000, 10_000L);
    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setContentType("text/plain");
    org.springframework.amqp.core.Message message = new org.springframework.amqp.core.Message(
            "test1".getBytes(), messageProperties);
    bs.addToBatch("foo", "bar", message);
    message = new org.springframework.amqp.core.Message("test2".getBytes(), messageProperties);
    MessageBatch batched = bs.addToBatch("foo", "bar", message);

    Channel channel = mock(Channel.class);
    willReturn(true).given(channel).isOpen();
    Envelope envelope = new Envelope(123L, false, "ex", "rk");
    BasicProperties props = new BasicProperties.Builder()
            .headers(batched.getMessage().getMessageProperties().getHeaders()).contentType("text/plain")
            .build();
    GetResponse getResponse = new GetResponse(envelope, props, batched.getMessage().getBody(), 0);
    willReturn(getResponse).given(channel).basicGet("foo", false);
    Connection connection = mock(Connection.class);
    willReturn(true).given(connection).isOpen();
    willReturn(channel).given(connection).createChannel();
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    willReturn(connection).given(connectionFactory).newConnection((ExecutorService) isNull(), anyString());

    CachingConnectionFactory ccf = new CachingConnectionFactory(connectionFactory);
    AmqpMessageSource source = new AmqpMessageSource(ccf, "foo");
    Message<?> received = source.receive();
    assertThat(received).isNotNull();
    assertThat(((List<String>) received.getPayload())).contains("test1", "test2");
}

From source file:pl.nask.hsn2.DataStoreActiveCleanerTest.java

License:Open Source License

@SuppressWarnings({ "rawtypes", "unused" })
private void mockObjects() throws Exception {
    connCloseRequested = false;/*from  ww w .j a v  a 2  s  .  co  m*/
    new NonStrictExpectations() {
        @Mocked
        ConnectionFactory cf;
        {
            // Create new connection.
            cf.newConnection();
            result = c;

            // Create channel.
            c.createChannel();
            result = ch;

            // Close connection.
            c.close();
            forEachInvocation = new Object() {
                void validate() {
                    connCloseRequested = true;
                }
            };

            // Declare exchange.
            ch.exchangeDeclare(anyString, anyString);

            // Declare queue.
            ch.queueDeclare();
            result = dok;

            // Get queue name.
            dok.getQueue();

            consumer.nextDelivery();
            result = new Delegate() {
                public Delivery nextDelivery() throws Exception {
                    Thread.sleep(100);
                    Delivery d = null;
                    Envelope envelope;
                    BasicProperties properties;
                    JobFinished jf;
                    byte[] body;
                    switch (nextAction) {
                    case TASK_ACCEPTED:
                        d = taskAcceptedMsg();
                        nextAction = CleaningActions.REMOVE_JOB_1;
                        break;
                    case REMOVE_JOB_1:
                        d = removeJobFinished(1, JobStatus.COMPLETED);
                        nextAction = CleaningActions.REMOVE_JOB_2;
                        break;
                    case REMOVE_JOB_2:
                        d = removeJobFinishedReminder(2);
                        nextAction = CleaningActions.CANCEL;
                        break;
                    case REMOVE_JOB_3:
                        d = removeJobFinished(3, JobStatus.COMPLETED);
                        nextAction = CleaningActions.REMOVE_JOB_3_AGAIN;
                        break;
                    case REMOVE_JOB_3_AGAIN:
                        d = removeJobFinished(3, JobStatus.COMPLETED);
                        nextAction = CleaningActions.CANCEL;
                        break;
                    case REMOVE_JOB_4:
                        d = removeJobFinished(4, JobStatus.COMPLETED);
                        nextAction = CleaningActions.CANCEL;
                        break;
                    case REMOVE_JOB_5:
                        d = removeJobFinished(5, JobStatus.FAILED);
                        nextAction = CleaningActions.CANCEL;
                        break;
                    case NEVER_RETURN:
                        while (true) {
                            LOGGER.debug("Never return...");
                            Thread.sleep(10000);
                        }
                    case CANCEL:
                        throw new ConsumerCancelledException();
                    case INTERRUPT:
                        throw new InterruptedException("Test interruption");
                    case SHUTDOWN:
                        throw new ShutdownSignalException(false, false, null, null);
                    case IO_EXCEPTION:
                        throw new IOException("Test I/O exception");
                    }
                    return d;
                }

                private Delivery taskAcceptedMsg() {
                    Delivery d;
                    Envelope envelope;
                    BasicProperties properties;
                    JobFinished jf;
                    byte[] body;
                    envelope = new Envelope(1, false, "", "");
                    properties = new BasicProperties.Builder().type("TaskAccepted").build();
                    body = new byte[] { 1 };
                    d = new Delivery(envelope, properties, body);
                    return d;
                }

                private Delivery removeJobFinished(long jobId, JobStatus status) {
                    Delivery d;
                    Envelope envelope;
                    BasicProperties properties;
                    JobFinished jf;
                    byte[] body;
                    envelope = new Envelope(1, false, "", "");
                    properties = new BasicProperties.Builder().type("JobFinished").build();
                    jf = JobFinished.newBuilder().setJob(jobId).setStatus(status).build();
                    body = jf.toByteArray();
                    d = new Delivery(envelope, properties, body);
                    return d;
                }

                private Delivery removeJobFinishedReminder(long jobId) {
                    Delivery d;
                    Envelope envelope;
                    BasicProperties properties;
                    byte[] body;
                    envelope = new Envelope(1, false, "", "");
                    properties = new BasicProperties.Builder().type("JobFinishedReminder").build();
                    JobFinishedReminder jfr = JobFinishedReminder.newBuilder().setJob(jobId)
                            .setStatus(JobStatus.COMPLETED).build();
                    body = jfr.toByteArray();
                    d = new Delivery(envelope, properties, body);
                    return d;
                }
            };
        }
    };
}

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";
            });/*www .j  a  va  2 s .c om*/

    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";
            });/*from   ww  w. j  av  a 2  s. co 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  ww .  j av a  2s  .  com
    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 ww  w  . j  ava2 s .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());
}