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:io.ventu.rpc.amqp.AmqpResponderImplTest.java

License:MIT License

@Test
public void handleDelivery_public_passThroughToHandleDeliveryInternal() throws TimeoutException, IOException {
    String routingKeyPattern = "routingKeyPattern";

    final Envelope env = new Envelope(1L, false, "rpc", "io.ventu.#");
    final BasicProperties props = new BasicProperties.Builder().build();
    final byte[] data = new byte[] {};

    final List<Boolean> invocations = Lists.newArrayList();
    AmqpResponderImpl responder = new AmqpResponderImpl(mock(ChannelProvider.class), routingKeyPattern) {
        @Override// ww  w.  j a  va 2 s. com
        CompletableFuture<Void> handleDeliveryInternal(String consumerTag, Envelope inEnv,
                BasicProperties inProps, byte[] inData) {
            invocations.add(Boolean.TRUE);
            assertSame(env, inEnv);
            assertSame(props, inProps);
            assertSame(data, inData);
            return null;
        }
    };
    responder.handleDelivery("consumerTag", env, props, data);
    assertEquals(1, invocations.size());
}

From source file:io.ventu.rpc.amqp.AmqpResponderImplTest.java

License:MIT License

@Test
public void handleDeliveryInternal_onPropagatedThrowable_apiErrorPublished()
        throws TimeoutException, IOException, EncodingException, ExecutionException, InterruptedException {
    String routingKeyPattern = "routingKeyPattern";
    String correlationId = "123456789";

    Channel channel = mock(Channel.class);
    ChannelProvider provider = mock(ChannelProvider.class);
    doReturn("replyExchange").when(provider).rpcExchange();
    doReturn(channel).when(provider).provide(anyString(), any());

    Map<String, Object> headers = Maps.newHashMap();
    headers.put("apikey", "234435345345");

    final List<Boolean> invocations = Lists.newArrayList();
    final CompletableFuture<byte[]> promise = new CompletableFuture<>();

    AmqpResponderImpl responder = new AmqpResponderImpl(provider, routingKeyPattern) {
        @Override//w w  w .  j  a v a2 s. com
        <RQ, RS> CompletableFuture<byte[]> handleDelivery(String routingKey, Map<String, Object> actualHeaders,
                byte[] payload) {
            invocations.add(Boolean.TRUE);
            promise.completeExceptionally(new IndexOutOfBoundsException("boom"));
            return promise;
        }
    };

    Envelope env = new Envelope(1L, false, "incomingEexchange", Req.class.getName());
    BasicProperties props = new Builder().correlationId(correlationId).replyTo("replyHere").headers(headers)
            .build();

    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            invocations.add(Boolean.TRUE);
            assertEquals("replyExchange", invocation.getArguments()[0]);
            assertEquals("replyHere", invocation.getArguments()[1]);
            BasicProperties respProps = (BasicProperties) invocation.getArguments()[2];
            assertEquals(correlationId, respProps.getCorrelationId());
            assertEquals(CONTENT_TYPE, respProps.getContentType());
            assertEquals(ENCODING, respProps.getContentEncoding());

            byte[] data = (byte[]) invocation.getArguments()[3];
            Map<Object, Object> payload = new DefaultSerializer().decode(data, Map.class);
            assertEquals("Unhandled internal error: boom", payload.get("error"));
            return null;
        }
    }).when(channel).basicPublish(anyString(), anyString(), any(), any());

    responder.handleDeliveryInternal("consumerTag", env, props, "ABC".getBytes()).get(1, TimeUnit.SECONDS);

    verify(channel).basicPublish(anyString(), anyString(), any(), any());
    verifyNoMoreInteractions(channel);
    assertEquals(2, invocations.size());
}

From source file:org.mule.transport.amqp.AmqpMuleMessageFactoryTestCase.java

License:Open Source License

public static AmqpMessage getTestMessage() {
    final byte[] body = "payload".getBytes();

    final String consumerTag = "consumerTag";

    final Envelope envelope = new Envelope(123456L, true, "exchange", "routingKey");

    final BasicProperties amqpProperties = new BasicProperties();
    amqpProperties.setAppId("appId");
    amqpProperties.setContentEncoding("utf-16");
    amqpProperties.setContentType("application/vnd+mule.xml");
    amqpProperties.setCorrelationId("cid-951753");
    amqpProperties.setDeliveryMode(2);/*w ww  .j a  v  a  2s . c o m*/
    amqpProperties.setExpiration("expiration");
    amqpProperties.setMessageId("messageId");
    amqpProperties.setPriority(5);
    amqpProperties.setReplyTo("replyTo");
    amqpProperties.setTimestamp(new Date(100000L));
    amqpProperties.setType("type");
    amqpProperties.setUserId("userId");

    amqpProperties.setHeaders(Collections.<String, Object>singletonMap("customKey", "customValue"));

    return new AmqpMessage(consumerTag, envelope, amqpProperties, body);
}

From source file:org.mule.transport.amqp.internal.domain.AmqpMuleMessageFactoryTestCase.java

License:Open Source License

public static AmqpMessage getTestMessage(final String messageId) {
    final byte[] body = "payload".getBytes();

    final String consumerTag = "consumerTag";

    final Envelope envelope = new Envelope(123456L, true, "exchange", "routingKey");

    final AMQP.BasicProperties.Builder bob = new AMQP.BasicProperties.Builder();
    bob.appId("appId").contentEncoding("utf-16").contentType("application/vnd+mule.xml")
            .correlationId("cid-951753").clusterId("myClusterId").deliveryMode(2).expiration("expiration")
            .messageId(messageId).priority(5).replyTo("replyTo").timestamp(new Date(100000L)).type("type")
            .userId("userId");

    bob.headers(Collections.<String, Object>singletonMap("customKey", "customValue"));

    final BasicProperties amqpProperties = bob.build();
    return new AmqpMessage(consumerTag, envelope, amqpProperties, body);
}

From source file:org.mule.transport.amqp.internal.transformer.ObjectToAmqpMessage.java

License:Open Source License

@Override
public Object transformMessage(final MuleMessage message, final String outputEncoding)
        throws TransformerException {
    byte[] body;/*from   w  w  w. j  a v  a 2 s . c  om*/
    try {
        body = message.getPayloadAsBytes();
    } catch (final Exception e) {
        throw new TransformerException(
                MessageFactory.createStaticMessage("Impossible to extract bytes out of: " + message), e);
    }

    final String consumerTag = getProperty(message, AmqpConnector.MESSAGE_PROPERTY_CONSUMER_TAG);

    final long deliveryTag = getProperty(message, AmqpConnector.MESSAGE_PROPERTY_DELIVERY_TAG, 0L);
    final boolean redelivered = getProperty(message, AmqpConnector.MESSAGE_PROPERTY_REDELIVER, false);
    final String exchange = getProperty(message, AmqpConnector.EXCHANGE);
    final String routingKey = getProperty(message, AmqpConnector.MESSAGE_PROPERTY_ROUTING_KEY);
    final String clusterId = getProperty(message, AmqpConnector.MESSAGE_PROPERTY_CLUSTER_ID);
    final Envelope envelope = new Envelope(deliveryTag, redelivered, exchange, routingKey);

    final AMQP.BasicProperties.Builder bob = new AMQP.BasicProperties.Builder();
    bob.appId(this.<String>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_APP_ID))
            .contentEncoding(this.<String>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_CONTENT_ENCODING,
                    outputEncoding))
            .contentType(this.<String>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_CONTENT_TYPE))
            .correlationId(this.<String>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_CORRELATION_ID,
                    message.getCorrelationId()))
            .clusterId(this.<String>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_CLUSTER_ID, clusterId))
            .deliveryMode(this.<Integer>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_DELIVERY_MODE))
            .expiration(this.<String>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_EXPIRATION))
            .messageId(this.<String>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_MESSAGE_ID,
                    message.getUniqueId()))
            .priority(this.<Integer>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_PRIORITY))
            .replyTo(this.<String>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_REPLY_TO,
                    (String) message.getReplyTo()))
            .timestamp(this.<Date>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_TIMESTAMP, new Date()))
            .type(this.<String>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_TYPE))
            .userId(this.<String>getProperty(message, AmqpConnector.MESSAGE_PROPERTY_USER_ID));

    bob.headers(getHeaders(message));

    final BasicProperties amqpProperties = bob.build();
    return new AmqpMessage(consumerTag, envelope, amqpProperties, body);
}

From source file:org.mule.transport.amqp.transformers.ObjectToAmqpMessage.java

License:Open Source License

@Override
public Object transformMessage(final MuleMessage message, final String outputEncoding)
        throws TransformerException {
    byte[] body;//from w w w .  j ava2 s .com
    try {
        body = message.getPayloadAsBytes();
    } catch (final Exception e) {
        throw new TransformerException(
                MessageFactory.createStaticMessage("Impossible to extract bytes out of: " + message), e);
    }

    final String consumerTag = getProperty(message, AmqpConstants.CONSUMER_TAG);

    final long deliveryTag = getProperty(message, AmqpConstants.DELIVERY_TAG, 0L);
    final boolean redelivered = getProperty(message, AmqpConstants.REDELIVER, false);
    final String exchange = getProperty(message, AmqpConstants.EXCHANGE);
    final String routingKey = getProperty(message, AmqpConstants.ROUTING_KEY);
    final Envelope envelope = new Envelope(deliveryTag, redelivered, exchange, routingKey);

    final BasicProperties amqpProperties = new BasicProperties();
    amqpProperties.setAppId(this.<String>getProperty(message, AmqpConstants.APP_ID));
    amqpProperties.setContentEncoding(
            this.<String>getProperty(message, AmqpConstants.CONTENT_ENCODING, outputEncoding));
    amqpProperties.setContentType(this.<String>getProperty(message, AmqpConstants.CONTENT_TYPE));
    amqpProperties.setCorrelationId(
            this.<String>getProperty(message, AmqpConstants.CORRELATION_ID, message.getCorrelationId()));
    amqpProperties.setDeliveryMode(this.<Integer>getProperty(message, AmqpConstants.DELIVERY_MODE));
    amqpProperties.setExpiration(this.<String>getProperty(message, AmqpConstants.EXPIRATION));
    amqpProperties
            .setMessageId(this.<String>getProperty(message, AmqpConstants.MESSAGE_ID, message.getUniqueId()));
    amqpProperties.setPriority(this.<Integer>getProperty(message, AmqpConstants.PRIORITY));
    amqpProperties.setReplyTo(
            this.<String>getProperty(message, AmqpConstants.REPLY_TO, (String) message.getReplyTo()));
    amqpProperties.setTimestamp(this.<Date>getProperty(message, AmqpConstants.TIMESTAMP, new Date()));
    amqpProperties.setType(this.<String>getProperty(message, AmqpConstants.TYPE));
    amqpProperties.setUserId(this.<String>getProperty(message, AmqpConstants.USER_ID));

    amqpProperties.setHeaders(getHeaders(message));

    return new AmqpMessage(consumerTag, envelope, amqpProperties, body);
}

From source file:org.springframework.amqp.rabbit.core.RabbitTemplateTests.java

License:Apache License

@SuppressWarnings("unchecked")
@Test // AMQP-249
public void dontHangConsumerThread() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);
    when(mockConnection.createChannel()).thenReturn(mockChannel);

    when(mockChannel.queueDeclare()).thenReturn(new AMQImpl.Queue.DeclareOk("foo", 0, 0));

    final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>();
    doAnswer(new Answer<Object>() {
        @Override/*from  w ww  . jav  a  2 s.co m*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            consumer.set((Consumer) invocation.getArguments()[6]);
            return null;
        }
    }).when(mockChannel).basicConsume(Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyString(),
            Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyMap(), Mockito.any(Consumer.class));
    RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory));
    template.setReplyTimeout(1);
    Message input = new Message("Hello, world!".getBytes(), new MessageProperties());
    template.doSendAndReceiveWithTemporary("foo", "bar", input);
    Envelope envelope = new Envelope(1, false, "foo", "bar");
    // used to hang here because of the SynchronousQueue and doSendAndReceive() already exited
    consumer.get().handleDelivery("foo", envelope, new AMQP.BasicProperties(), new byte[0]);
}

From source file:org.springframework.amqp.rabbit.listener.DirectMessageListenerContainerMockTests.java

License:Apache License

private Envelope envelope(long tag) {
    return new Envelope(tag, false, "", "");
}

From source file:org.springframework.amqp.rabbit.listener.ExternalTxManagerTests.java

License:Apache License

/**
 * Verifies that an up-stack RabbitTemplate uses the listener's
 * channel (MessageListener).//  w ww.j  ava  2 s. c  o m
 */
@SuppressWarnings("unchecked")
@Test
public void testMessageListener() throws Exception {
    ConnectionFactory mockConnectionFactory = mock(ConnectionFactory.class);
    Connection mockConnection = mock(Connection.class);
    final Channel onlyChannel = mock(Channel.class);
    when(onlyChannel.isOpen()).thenReturn(true);

    final CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(
            mockConnectionFactory);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    when(mockConnection.isOpen()).thenReturn(true);

    final AtomicReference<Exception> tooManyChannels = new AtomicReference<Exception>();

    doAnswer(new Answer<Channel>() {
        boolean done;

        @Override
        public Channel answer(InvocationOnMock invocation) throws Throwable {
            if (!done) {
                done = true;
                return onlyChannel;
            }
            tooManyChannels.set(new Exception("More than one channel requested"));
            Channel channel = mock(Channel.class);
            when(channel.isOpen()).thenReturn(true);
            return channel;
        }
    }).when(mockConnection).createChannel();

    final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>();

    doAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            consumer.set((Consumer) invocation.getArguments()[6]);
            return null;
        }
    }).when(onlyChannel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(),
            anyMap(), any(Consumer.class));

    final CountDownLatch commitLatch = new CountDownLatch(1);
    doAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            commitLatch.countDown();
            return null;
        }
    }).when(onlyChannel).txCommit();

    final CountDownLatch latch = new CountDownLatch(1);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cachingConnectionFactory);
    container.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
            rabbitTemplate.setChannelTransacted(true);
            // should use same channel as container
            rabbitTemplate.convertAndSend("foo", "bar", "baz");
            latch.countDown();
        }
    });
    container.setQueueNames("queue");
    container.setChannelTransacted(true);
    container.setShutdownTimeout(100);
    container.setTransactionManager(new DummyTxManager());
    container.afterPropertiesSet();
    container.start();

    consumer.get().handleDelivery("qux", new Envelope(1, false, "foo", "bar"), new BasicProperties(),
            new byte[] { 0 });

    assertTrue(latch.await(10, TimeUnit.SECONDS));

    Exception e = tooManyChannels.get();
    if (e != null) {
        throw e;
    }

    verify(mockConnection, Mockito.times(1)).createChannel();
    assertTrue(commitLatch.await(10, TimeUnit.SECONDS));
    verify(onlyChannel).txCommit();
    verify(onlyChannel).basicPublish(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(),
            Mockito.any(BasicProperties.class), Mockito.any(byte[].class));

    // verify close() was never called on the channel
    DirectFieldAccessor dfa = new DirectFieldAccessor(cachingConnectionFactory);
    List<?> channels = (List<?>) dfa.getPropertyValue("cachedChannelsTransactional");
    assertEquals(0, channels.size());

    container.stop();

}

From source file:org.springframework.amqp.rabbit.listener.ExternalTxManagerTests.java

License:Apache License

/**
 * Verifies that an up-stack RabbitTemplate does not use the listener's
 * channel when it has its own connection factory.
 *//*w ww  .j av a  2s.  c o m*/
@SuppressWarnings("unchecked")
@Test
public void testMessageListenerTemplateUsesDifferentConnectionFactory() throws Exception {
    ConnectionFactory listenerConnectionFactory = mock(ConnectionFactory.class);
    ConnectionFactory templateConnectionFactory = mock(ConnectionFactory.class);
    Connection listenerConnection = mock(Connection.class);
    Connection templateConnection = mock(Connection.class);
    final Channel listenerChannel = mock(Channel.class);
    Channel templateChannel = mock(Channel.class);
    when(listenerChannel.isOpen()).thenReturn(true);
    when(templateChannel.isOpen()).thenReturn(true);

    final CachingConnectionFactory cachingConnectionFactory = new CachingConnectionFactory(
            listenerConnectionFactory);
    final CachingConnectionFactory cachingTemplateConnectionFactory = new CachingConnectionFactory(
            templateConnectionFactory);

    when(listenerConnectionFactory.newConnection((ExecutorService) null)).thenReturn(listenerConnection);
    when(listenerConnection.isOpen()).thenReturn(true);
    when(templateConnectionFactory.newConnection((ExecutorService) null)).thenReturn(templateConnection);
    when(templateConnection.isOpen()).thenReturn(true);
    when(templateConnection.createChannel()).thenReturn(templateChannel);

    final AtomicReference<Exception> tooManyChannels = new AtomicReference<Exception>();

    doAnswer(new Answer<Channel>() {
        boolean done;

        @Override
        public Channel answer(InvocationOnMock invocation) throws Throwable {
            if (!done) {
                done = true;
                return listenerChannel;
            }
            tooManyChannels.set(new Exception("More than one channel requested"));
            Channel channel = mock(Channel.class);
            when(channel.isOpen()).thenReturn(true);
            return channel;
        }
    }).when(listenerConnection).createChannel();

    final AtomicReference<Consumer> consumer = new AtomicReference<Consumer>();

    doAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            consumer.set((Consumer) invocation.getArguments()[6]);
            return null;
        }
    }).when(listenerChannel).basicConsume(anyString(), anyBoolean(), anyString(), anyBoolean(), anyBoolean(),
            anyMap(), any(Consumer.class));

    final CountDownLatch commitLatch = new CountDownLatch(2);
    doAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            commitLatch.countDown();
            return null;
        }
    }).when(listenerChannel).txCommit();
    doAnswer(new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            commitLatch.countDown();
            return null;
        }
    }).when(templateChannel).txCommit();

    final CountDownLatch latch = new CountDownLatch(1);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(cachingConnectionFactory);
    container.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingTemplateConnectionFactory);
            rabbitTemplate.setChannelTransacted(true);
            // should use same channel as container
            rabbitTemplate.convertAndSend("foo", "bar", "baz");
            latch.countDown();
        }
    });
    container.setQueueNames("queue");
    container.setChannelTransacted(true);
    container.setShutdownTimeout(100);
    container.setTransactionManager(new DummyTxManager());
    container.afterPropertiesSet();
    container.start();

    consumer.get().handleDelivery("qux", new Envelope(1, false, "foo", "bar"), new BasicProperties(),
            new byte[] { 0 });

    assertTrue(latch.await(10, TimeUnit.SECONDS));

    Exception e = tooManyChannels.get();
    if (e != null) {
        throw e;
    }

    verify(listenerConnection, Mockito.times(1)).createChannel();
    verify(templateConnection, Mockito.times(1)).createChannel();
    assertTrue(commitLatch.await(10, TimeUnit.SECONDS));
    verify(listenerChannel).txCommit();
    verify(templateChannel).basicPublish(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean(),
            Mockito.any(BasicProperties.class), Mockito.any(byte[].class));
    verify(templateChannel).txCommit();

    // verify close() was never called on the channel
    DirectFieldAccessor dfa = new DirectFieldAccessor(cachingConnectionFactory);
    List<?> channels = (List<?>) dfa.getPropertyValue("cachedChannelsTransactional");
    assertEquals(0, channels.size());

    container.stop();

}