Example usage for com.rabbitmq.client Connection createChannel

List of usage examples for com.rabbitmq.client Connection createChannel

Introduction

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

Prototype

Channel createChannel() throws IOException;

Source Link

Document

Create a new channel, using an internally allocated channel number.

Usage

From source file:org.springframework.amqp.rabbit.connection.CachingConnectionFactoryTests.java

License:Apache License

@Test
public void testTransactionalAndNonTransactionalChannelsSegregated() throws IOException {
    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class);
    Channel mockChannel1 = mock(Channel.class);
    Channel mockChannel2 = mock(Channel.class);

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

    // Called during physical close
    when(mockChannel1.isOpen()).thenReturn(true);
    when(mockChannel2.isOpen()).thenReturn(true);

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setChannelCacheSize(1);//from w ww  . j a va 2s  .c  o  m

    Connection con = ccf.createConnection();

    Channel channel1 = con.createChannel(true);
    channel1.txSelect();
    channel1.close(); // should be ignored, and add last into channel cache.
    /*
     * When a channel is created as non-transactional we should create a new one.
     */
    Channel channel2 = con.createChannel(false);
    channel2.close(); // should be ignored, and add last into channel cache.
    assertNotSame(channel1, channel2);

    Channel ch1 = con.createChannel(true); // remove first entry in cache (channel1)
    Channel ch2 = con.createChannel(false); // create new channel

    assertNotSame(ch1, ch2);
    assertSame(ch1, channel1); // The non-transactional one
    assertSame(ch2, channel2);

    ch1.close();
    ch2.close();

    verify(mockConnection, times(2)).createChannel();

    con.close(); // should be ignored

    verify(mockConnection, never()).close();
    verify(mockChannel1, never()).close();
    verify(mockChannel2, never()).close();

    @SuppressWarnings("unchecked")
    List<Channel> notxlist = (List<Channel>) ReflectionTestUtils.getField(ccf,
            "cachedChannelsNonTransactional");
    assertEquals(1, notxlist.size());
    @SuppressWarnings("unchecked")
    List<Channel> txlist = (List<Channel>) ReflectionTestUtils.getField(ccf, "cachedChannelsTransactional");
    assertEquals(1, txlist.size());

}

From source file:org.springframework.amqp.rabbit.connection.CachingConnectionFactoryTests.java

License:Apache License

@Test
public void testWithConnectionFactoryDestroy() throws IOException {
    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class);

    Channel mockChannel1 = mock(Channel.class);
    Channel mockChannel2 = mock(Channel.class);

    assertNotSame(mockChannel1, mockChannel2);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection);
    // You can't repeat 'when' statements for stubbing consecutive calls to
    // the same method to returning different
    // values./*ww w . j  av  a2s  .  c om*/
    when(mockConnection.createChannel()).thenReturn(mockChannel1).thenReturn(mockChannel2);
    when(mockConnection.isOpen()).thenReturn(true);
    // Called during physical close
    when(mockChannel1.isOpen()).thenReturn(true);
    when(mockChannel2.isOpen()).thenReturn(true);

    CachingConnectionFactory ccf = new CachingConnectionFactory(mockConnectionFactory);
    ccf.setChannelCacheSize(2);

    Connection con = ccf.createConnection();

    // This will return a proxy that surpresses calls to close
    Channel channel1 = con.createChannel(false);
    Channel channel2 = con.createChannel(false);

    // Should be ignored, and add last into channel cache.
    channel1.close();
    channel2.close();

    // remove first entry in cache (channel1)
    Channel ch1 = con.createChannel(false);
    // remove first entry in cache (channel2)
    Channel ch2 = con.createChannel(false);

    assertSame(ch1, channel1);
    assertSame(ch2, channel2);

    Channel target1 = ((ChannelProxy) ch1).getTargetChannel();
    Channel target2 = ((ChannelProxy) ch2).getTargetChannel();

    // make sure mokito returned different mocks for the channel
    assertNotSame(target1, target2);

    ch1.close();
    ch2.close();
    con.close(); // should be ignored

    ccf.destroy(); // should call close on connection and channels in cache

    verify(mockConnection, times(2)).createChannel();

    verify(mockConnection).close(anyInt());

    // verify(mockChannel1).close();
    verify(mockChannel2).close();

    // After destroy we can get a new connection
    Connection con1 = ccf.createConnection();
    assertNotSame(con, con1);

    // This will return a proxy that surpresses calls to close
    Channel channel3 = con.createChannel(false);
    assertNotSame(channel3, channel1);
    assertNotSame(channel3, channel2);
}

From source file:org.springframework.amqp.rabbit.connection.CachingConnectionFactoryTests.java

License:Apache License

@Test
public void testWithChannelListener() throws IOException {

    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection = mock(com.rabbitmq.client.Connection.class);
    Channel mockChannel = mock(Channel.class);

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

    final AtomicInteger called = new AtomicInteger(0);
    AbstractConnectionFactory connectionFactory = createConnectionFactory(mockConnectionFactory);
    connectionFactory.setChannelListeners(Arrays.asList(new ChannelListener() {
        @Override/*  w ww  . ja v a  2  s .  c  o m*/
        public void onCreate(Channel channel, boolean transactional) {
            called.incrementAndGet();
        }
    }));
    ((CachingConnectionFactory) connectionFactory).setChannelCacheSize(1);

    Connection con = connectionFactory.createConnection();
    Channel channel = con.createChannel(false);
    assertEquals(1, called.get());
    channel.close();

    con.close();
    verify(mockConnection, never()).close();

    connectionFactory.createConnection();
    con.createChannel(false);
    assertEquals(1, called.get());

    connectionFactory.destroy();
    verify(mockConnection, atLeastOnce()).close(anyInt());

    verify(mockConnectionFactory).newConnection((ExecutorService) null);

}

From source file:org.springframework.amqp.rabbit.connection.CachingConnectionFactoryTests.java

License:Apache License

@Test
public void testWithConnectionListener() throws IOException {

    com.rabbitmq.client.ConnectionFactory mockConnectionFactory = mock(
            com.rabbitmq.client.ConnectionFactory.class);
    com.rabbitmq.client.Connection mockConnection1 = mock(com.rabbitmq.client.Connection.class);
    com.rabbitmq.client.Connection mockConnection2 = mock(com.rabbitmq.client.Connection.class);
    Channel mockChannel = mock(Channel.class);

    when(mockConnectionFactory.newConnection((ExecutorService) null)).thenReturn(mockConnection1,
            mockConnection2);//from   w w w  . jav a  2  s. com
    when(mockConnection1.isOpen()).thenReturn(true);
    when(mockChannel.isOpen()).thenReturn(true);
    when(mockConnection1.createChannel()).thenReturn(mockChannel);
    when(mockConnection2.createChannel()).thenReturn(mockChannel);

    final AtomicReference<Connection> created = new AtomicReference<Connection>();
    final AtomicReference<Connection> closed = new AtomicReference<Connection>();
    AbstractConnectionFactory connectionFactory = createConnectionFactory(mockConnectionFactory);
    connectionFactory.addConnectionListener(new ConnectionListener() {

        @Override
        public void onCreate(Connection connection) {
            created.set(connection);
        }

        @Override
        public void onClose(Connection connection) {
            closed.set(connection);
        }
    });
    ((CachingConnectionFactory) connectionFactory).setChannelCacheSize(1);

    Connection con = connectionFactory.createConnection();
    Channel channel = con.createChannel(false);
    assertSame(con, created.get());
    channel.close();

    con.close();
    verify(mockConnection1, never()).close();

    Connection same = connectionFactory.createConnection();
    channel = con.createChannel(false);
    assertSame(con, same);
    channel.close();

    when(mockConnection1.isOpen()).thenReturn(false);
    when(mockChannel.isOpen()).thenReturn(false); // force a connection refresh
    channel.basicCancel("foo");
    channel.close();

    Connection notSame = connectionFactory.createConnection();
    assertNotSame(con, notSame);
    assertSame(con, closed.get());
    assertSame(notSame, created.get());

    connectionFactory.destroy();
    verify(mockConnection2, atLeastOnce()).close(anyInt());
    assertSame(notSame, closed.get());

    verify(mockConnectionFactory, times(2)).newConnection((ExecutorService) null);
}

From source file:org.springframework.amqp.rabbit.connection.ClientRecoveryCompatibilityTests.java

License:Apache License

@Test
public void testDefeatRecovery() throws Exception {
    final Channel channel1 = mock(Channel.class);
    when(channel1.isOpen()).thenReturn(true);
    final Channel channel2 = mock(Channel.class);
    when(channel2.isOpen()).thenReturn(true);
    final com.rabbitmq.client.Connection rabbitConn = mock(AutorecoveringConnection.class);
    when(rabbitConn.isOpen()).thenReturn(true);
    com.rabbitmq.client.ConnectionFactory cf = mock(com.rabbitmq.client.ConnectionFactory.class);
    doAnswer(invocation -> rabbitConn).when(cf).newConnection(any(ExecutorService.class), anyString());
    when(rabbitConn.createChannel()).thenReturn(channel1).thenReturn(channel2);

    CachingConnectionFactory ccf = new CachingConnectionFactory(cf);
    Connection conn1 = ccf.createConnection();
    Channel channel = conn1.createChannel(false);
    verifyChannelIs(channel1, channel);//from  ww w  .  j  ava2 s. c o m
    channel.close();
    conn1.close();
    Connection conn2 = ccf.createConnection();
    assertSame(conn1, conn2);
    channel = conn1.createChannel(false);
    verifyChannelIs(channel1, channel);
    channel.close();
    conn2.close();

    when(rabbitConn.isOpen()).thenReturn(false).thenReturn(true);
    when(channel1.isOpen()).thenReturn(false);
    conn2 = ccf.createConnection();
    try {
        conn2.createChannel(false);
        fail("Expected AutoRecoverConnectionNotCurrentlyOpenException");
    } catch (AutoRecoverConnectionNotCurrentlyOpenException e) {
        assertThat(e.getMessage(), equalTo("Auto recovery connection is not currently open"));
    }
    channel = conn2.createChannel(false);
    verifyChannelIs(channel2, channel);
    channel.close();

    verify(rabbitConn, never()).close();
    verify(channel1).close(); // physically closed to defeat recovery
}

From source file:org.springframework.amqp.rabbit.connection.SSLConnectionTests.java

License:Apache License

@Test
@Ignore/* w  w  w.  j  av  a2s. c  o m*/
public void test() throws Exception {
    RabbitConnectionFactoryBean fb = new RabbitConnectionFactoryBean();
    fb.setUseSSL(true);
    fb.setSslPropertiesLocation(new ClassPathResource("ssl.properties"));
    fb.setClientProperties(Collections.<String, Object>singletonMap("foo", "bar"));
    fb.afterPropertiesSet();
    ConnectionFactory cf = fb.getObject();
    assertEquals("bar", cf.getClientProperties().get("foo"));
    Connection conn = cf.newConnection();
    Channel chan = conn.createChannel();
    chan.close();
    conn.close();
}

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

License:Apache License

/**
 * Verify that a queue exists using the native Rabbit API to bypass all the connection and
 * channel caching and callbacks in Spring AMQP.
 *
 * @param queue The queue to verify//w ww.j  a va2 s .  c o  m
 * @return True if the queue exists
 */
private boolean queueExists(final Queue queue) throws Exception {
    ConnectionFactory connectionFactory = new ConnectionFactory();
    connectionFactory.setHost("localhost");
    connectionFactory.setPort(BrokerTestUtils.getPort());
    Connection connection = connectionFactory.newConnection();
    Channel channel = connection.createChannel();
    try {
        DeclareOk result = channel.queueDeclarePassive(queue.getName());
        return result != null;
    } catch (IOException e) {
        return e.getCause().getMessage().contains("RESOURCE_LOCKED");
    } finally {
        connection.close();
    }
}

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

License:Apache License

private void testNoExistingReplyToOrCorrelationGuts(final boolean standardHeader) 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);

    final RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory));
    Queue replyQueue = new Queue("new.replyTo");
    template.setReplyQueue(replyQueue);//  w w  w  .ja v a  2 s  .  c  om
    if (!standardHeader) {
        template.setCorrelationKey(CORRELATION_HEADER);
    }

    MessageProperties messageProperties = new MessageProperties();
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    final AtomicReference<String> replyTo = new AtomicReference<String>();
    final AtomicReference<String> correlationId = new AtomicReference<String>();
    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            BasicProperties basicProps = (BasicProperties) invocation.getArguments()[3];
            replyTo.set(basicProps.getReplyTo());
            if (standardHeader) {
                correlationId.set(basicProps.getCorrelationId());
            } else {
                correlationId.set((String) basicProps.getHeaders().get(CORRELATION_HEADER));
            }
            MessageProperties springProps = new DefaultMessagePropertiesConverter()
                    .toMessageProperties(basicProps, null, "UTF-8");
            Message replyMessage = new Message("!dlrow olleH".getBytes(), springProps);
            template.onMessage(replyMessage);
            return null;
        }
    }).when(mockChannel).basicPublish(Mockito.any(String.class), Mockito.any(String.class),
            Mockito.anyBoolean(), Mockito.any(BasicProperties.class), Mockito.any(byte[].class));
    Message reply = template.sendAndReceive(message);
    assertNotNull(reply);

    assertNotNull(replyTo.get());
    assertEquals("new.replyTo", replyTo.get());
    assertNotNull(correlationId.get());
    assertNull(reply.getMessageProperties().getReplyTo());
    if (standardHeader) {
        assertNull(reply.getMessageProperties().getCorrelationId());
    } else {
        assertNull(reply.getMessageProperties().getHeaders().get(CORRELATION_HEADER));
    }
}

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

License:Apache License

@Test
public void testReplyToOneDeep() 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);

    final RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory));
    Queue replyQueue = new Queue("new.replyTo");
    template.setReplyQueue(replyQueue);/*  w  ww  .  j a va 2 s.  c  om*/
    template.setReplyTimeout(60000);

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setReplyTo("replyTo1");
    messageProperties.setCorrelationId("saveThis".getBytes());
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    final AtomicReference<String> replyTo = new AtomicReference<String>();
    final AtomicReference<String> correlationId = new AtomicReference<String>();
    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            BasicProperties basicProps = (BasicProperties) invocation.getArguments()[3];
            replyTo.set(basicProps.getReplyTo());
            correlationId.set(basicProps.getCorrelationId());
            MessageProperties springProps = new DefaultMessagePropertiesConverter()
                    .toMessageProperties(basicProps, null, "UTF-8");
            Message replyMessage = new Message("!dlrow olleH".getBytes(), springProps);
            template.onMessage(replyMessage);
            return null;
        }
    }).when(mockChannel).basicPublish(Mockito.any(String.class), Mockito.any(String.class),
            Mockito.anyBoolean(), Mockito.any(BasicProperties.class), Mockito.any(byte[].class));
    Message reply = template.sendAndReceive(message);
    assertNotNull(reply);

    assertNotNull(replyTo.get());
    assertEquals("new.replyTo", replyTo.get());
    assertNotNull(correlationId.get());
    assertFalse("saveThis".equals(correlationId.get()));
    assertEquals("replyTo1", reply.getMessageProperties().getReplyTo());

}

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

License:Apache License

@Test
public void testReplyToThreeDeep() 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);

    final RabbitTemplate template = new RabbitTemplate(new SingleConnectionFactory(mockConnectionFactory));
    Queue replyQueue = new Queue("replyTo2");
    template.setReplyQueue(replyQueue);/*from   ww  w  . j  a  v  a2  s .  c  om*/

    MessageProperties messageProperties = new MessageProperties();
    messageProperties.setReplyTo("replyTo1");
    messageProperties.setCorrelationId("a".getBytes());
    Message message = new Message("Hello, world!".getBytes(), messageProperties);
    final AtomicInteger count = new AtomicInteger();
    final List<String> nestedReplyTo = new ArrayList<String>();
    final List<String> nestedCorrelation = new ArrayList<String>();
    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) throws Throwable {
            BasicProperties basicProps = (BasicProperties) invocation.getArguments()[3];
            nestedReplyTo.add(basicProps.getReplyTo());
            nestedCorrelation.add(basicProps.getCorrelationId());
            MessageProperties springProps = new DefaultMessagePropertiesConverter()
                    .toMessageProperties(basicProps, null, "UTF-8");
            Message replyMessage = new Message("!dlrow olleH".getBytes(), springProps);
            if (count.incrementAndGet() < 2) {
                Message anotherMessage = new Message("Second".getBytes(), springProps);
                template.setReplyQueue(new Queue("replyTo3"));
                replyMessage = template.sendAndReceive(anotherMessage);
                nestedReplyTo.add(replyMessage.getMessageProperties().getReplyTo());
                nestedCorrelation
                        .add(new String(replyMessage.getMessageProperties().getCorrelationId(), "UTF-8"));
            }
            template.onMessage(replyMessage);
            return null;
        }
    }).when(mockChannel).basicPublish(Mockito.any(String.class), Mockito.any(String.class),
            Mockito.anyBoolean(), Mockito.any(BasicProperties.class), Mockito.any(byte[].class));
    Message reply = template.sendAndReceive(message);
    assertNotNull(reply);

    assertEquals(3, nestedReplyTo.size());
    assertEquals("replyTo2", nestedReplyTo.get(0));
    assertEquals("replyTo3", nestedReplyTo.get(1));
    assertEquals("replyTo2", nestedReplyTo.get(2)); // intermediate reply

    assertEquals("replyTo1", reply.getMessageProperties().getReplyTo());
    assertEquals("a", new String(reply.getMessageProperties().getCorrelationId(), "UTF-8"));

}