Example usage for com.rabbitmq.client Channel queueDeclare

List of usage examples for com.rabbitmq.client Channel queueDeclare

Introduction

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

Prototype

Queue.DeclareOk queueDeclare(String queue, boolean durable, boolean exclusive, boolean autoDelete,
        Map<String, Object> arguments) throws IOException;

Source Link

Document

Declare a queue

Usage

From source file:org.smartdeveloperhub.harvesters.scm.backend.notification.CollectorControllerTest.java

License:Apache License

@SuppressWarnings("unchecked")
@Test//  w w  w .  j a v a 2  s  . com
public void testConnect$shouldCleanUpOnConsumerRegistrationFailure(@Mocked final Channel channel,
        @Mocked final Queue.DeclareOk ok) throws Exception {
    new MockUp<ConnectionManager>() {
        private boolean connected = false;

        @Mock(invocations = 1)
        void connect() {
            this.connected = true;
        }

        @Mock(invocations = 1)
        void disconnect() {
        }

        @Mock
        boolean isConnected() {
            return this.connected;
        }

        @Mock
        Channel channel() {
            return channel;
        }
    };
    final Collector defaultCollector = defaultCollector();
    new Expectations() {
        {
            channel.queueDeclare((String) this.any, true, true, true, (Map<String, Object>) this.any);
            this.result = ok;
            ok.getQueue();
            this.result = "actualQueueName";
            channel.basicConsume("actualQueueName", false, (Consumer) this.any);
            this.result = new IOException("Failure");
        }
    };
    final CollectorController sut = collectorController(defaultCollector);
    try {
        sut.connect();
        fail("Should not connect on failure");
    } catch (final ControllerException e) {
        assertThat(e.getMessage(), equalTo("Could not register consumer for queue 'actualQueueName'"));
        assertThat(e.getCause(), instanceOf(IOException.class));
        assertThat(e.getCause().getMessage(), equalTo("Failure"));
    }
}

From source file:org.smartdeveloperhub.harvesters.scm.backend.notification.CollectorControllerTest.java

License:Apache License

@SuppressWarnings("unchecked")
@Test/* w w  w.ja  v  a2 s  . c o  m*/
public void testDisconnect$ignoreCleanerFailures(@Mocked final Channel channel,
        @Mocked final Queue.DeclareOk ok) throws Exception {
    new MockUp<ConnectionManager>() {
        private boolean connected = false;

        @Mock(invocations = 1)
        void connect() {
            this.connected = true;
        }

        @Mock(invocations = 1)
        void disconnect() {
        }

        @Mock
        boolean isConnected() {
            return this.connected;
        }

        @Mock
        Channel channel() {
            return channel;
        }
    };
    final Collector defaultCollector = defaultCollector();
    final CollectorController sut = collectorController(defaultCollector);
    new Expectations() {
        {
            channel.queueDeclare((String) this.any, true, true, true, (Map<String, Object>) this.any);
            this.result = ok;
            ok.getQueue();
            this.result = "actualQueueName";
            channel.basicConsume("actualQueueName", false, (Consumer) this.any);
            channel.queueUnbind("actualQueueName", defaultCollector.getExchangeName(), (String) this.any);
            this.result = new IOException("failure");
        }
    };
    sut.connect();
    sut.disconnect();
}

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

License:Apache License

private DeclareOk[] declareQueues(final Channel channel, final Queue... queues) throws IOException {
    DeclareOk[] declareOks = new DeclareOk[queues.length];
    for (int i = 0; i < queues.length; i++) {
        Queue queue = queues[i];//from  ww  w  . j  ava  2s.  c  o m
        if (!queue.getName().startsWith("amq.")) {
            if (logger.isDebugEnabled()) {
                logger.debug("declaring Queue '" + queue.getName() + "'");
            }
            try {
                DeclareOk declareOk = channel.queueDeclare(queue.getName(), queue.isDurable(),
                        queue.isExclusive(), queue.isAutoDelete(), queue.getArguments());
                declareOks[i] = declareOk;
            } catch (IOException e) {
                if (this.ignoreDeclarationExceptions) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Failed to declare queue:" + queue + ", continuing...", e);
                    }
                } else {
                    throw e;
                }
            }
        } else if (logger.isDebugEnabled()) {
            logger.debug("Queue with name that starts with 'amq.' cannot be declared.");
        }
    }
    return declareOks;
}

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

License:Apache License

@Test
public void testUnconditional() throws Exception {
    ConnectionFactory cf = mock(ConnectionFactory.class);
    Connection conn = mock(Connection.class);
    Channel channel = mock(Channel.class);
    when(cf.createConnection()).thenReturn(conn);
    when(conn.createChannel(false)).thenReturn(channel);
    when(channel.queueDeclare("foo", true, false, false, null))
            .thenReturn(new AMQImpl.Queue.DeclareOk("foo", 0, 0));
    final AtomicReference<ConnectionListener> listener = new AtomicReference<ConnectionListener>();
    doAnswer(new Answer<Object>() {

        @Override/* ww w  .  j av a2  s  .co m*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            listener.set((ConnectionListener) invocation.getArguments()[0]);
            return null;
        }
    }).when(cf).addConnectionListener(any(ConnectionListener.class));
    RabbitAdmin admin = new RabbitAdmin(cf);
    GenericApplicationContext context = new GenericApplicationContext();
    Queue queue = new Queue("foo");
    context.getBeanFactory().registerSingleton("foo", queue);
    DirectExchange exchange = new DirectExchange("bar");
    context.getBeanFactory().registerSingleton("bar", exchange);
    Binding binding = new Binding("foo", DestinationType.QUEUE, "bar", "foo", null);
    context.getBeanFactory().registerSingleton("baz", binding);
    context.refresh();
    admin.setApplicationContext(context);
    admin.afterPropertiesSet();
    assertNotNull(listener.get());
    listener.get().onCreate(conn);

    verify(channel).queueDeclare("foo", true, false, false, null);
    verify(channel).exchangeDeclare("bar", "direct", true, false, new HashMap<String, Object>());
    verify(channel).queueBind("foo", "bar", "foo", null);
}

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

License:Apache License

@Test
public void testUnconditionalWithExplicitFactory() throws Exception {
    ConnectionFactory cf = mock(ConnectionFactory.class);
    Connection conn = mock(Connection.class);
    Channel channel = mock(Channel.class);
    when(cf.createConnection()).thenReturn(conn);
    when(conn.createChannel(false)).thenReturn(channel);
    when(channel.queueDeclare("foo", true, false, false, null))
            .thenReturn(new AMQImpl.Queue.DeclareOk("foo", 0, 0));
    final AtomicReference<ConnectionListener> listener = new AtomicReference<ConnectionListener>();
    doAnswer(new Answer<Object>() {

        @Override// w ww . jav a  2s .  com
        public Object answer(InvocationOnMock invocation) throws Throwable {
            listener.set((ConnectionListener) invocation.getArguments()[0]);
            return null;
        }
    }).when(cf).addConnectionListener(any(ConnectionListener.class));
    RabbitAdmin admin = new RabbitAdmin(cf);
    GenericApplicationContext context = new GenericApplicationContext();
    Queue queue = new Queue("foo");
    queue.setAdminsThatShouldDeclare(admin);
    context.getBeanFactory().registerSingleton("foo", queue);
    DirectExchange exchange = new DirectExchange("bar");
    exchange.setAdminsThatShouldDeclare(admin);
    context.getBeanFactory().registerSingleton("bar", exchange);
    Binding binding = new Binding("foo", DestinationType.QUEUE, "bar", "foo", null);
    binding.setAdminsThatShouldDeclare(admin);
    context.getBeanFactory().registerSingleton("baz", binding);
    context.refresh();
    admin.setApplicationContext(context);
    admin.afterPropertiesSet();
    assertNotNull(listener.get());
    listener.get().onCreate(conn);

    verify(channel).queueDeclare("foo", true, false, false, null);
    verify(channel).exchangeDeclare("bar", "direct", true, false, new HashMap<String, Object>());
    verify(channel).queueBind("foo", "bar", "foo", null);
}

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

License:Apache License

@Test
public void testSkipBecauseDifferentFactory() throws Exception {
    ConnectionFactory cf = mock(ConnectionFactory.class);
    Connection conn = mock(Connection.class);
    Channel channel = mock(Channel.class);
    when(cf.createConnection()).thenReturn(conn);
    when(conn.createChannel(false)).thenReturn(channel);
    when(channel.queueDeclare("foo", true, false, false, null))
            .thenReturn(new AMQImpl.Queue.DeclareOk("foo", 0, 0));
    final AtomicReference<ConnectionListener> listener = new AtomicReference<ConnectionListener>();
    doAnswer(new Answer<Object>() {

        @Override/*from  ww w . ja  va  2s.  c  o  m*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            listener.set((ConnectionListener) invocation.getArguments()[0]);
            return null;
        }
    }).when(cf).addConnectionListener(any(ConnectionListener.class));
    RabbitAdmin admin = new RabbitAdmin(cf);
    RabbitAdmin other = new RabbitAdmin(cf);
    GenericApplicationContext context = new GenericApplicationContext();
    Queue queue = new Queue("foo");
    queue.setAdminsThatShouldDeclare(other);
    context.getBeanFactory().registerSingleton("foo", queue);
    DirectExchange exchange = new DirectExchange("bar");
    exchange.setAdminsThatShouldDeclare(other);
    context.getBeanFactory().registerSingleton("bar", exchange);
    Binding binding = new Binding("foo", DestinationType.QUEUE, "bar", "foo", null);
    binding.setAdminsThatShouldDeclare(other);
    context.getBeanFactory().registerSingleton("baz", binding);
    context.refresh();
    admin.setApplicationContext(context);
    admin.afterPropertiesSet();
    assertNotNull(listener.get());
    listener.get().onCreate(conn);

    verify(channel, times(0)).queueDeclare("foo", true, false, false, null);
    verify(channel, times(0)).exchangeDeclare("bar", "direct", true, false, new HashMap<String, Object>());
    verify(channel, times(0)).queueBind("foo", "bar", "foo", null);
}

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

License:Apache License

@Test
public void testSkipBecauseShouldntDeclare() throws Exception {
    ConnectionFactory cf = mock(ConnectionFactory.class);
    Connection conn = mock(Connection.class);
    Channel channel = mock(Channel.class);
    when(cf.createConnection()).thenReturn(conn);
    when(conn.createChannel(false)).thenReturn(channel);
    when(channel.queueDeclare("foo", true, false, false, null))
            .thenReturn(new AMQImpl.Queue.DeclareOk("foo", 0, 0));
    final AtomicReference<ConnectionListener> listener = new AtomicReference<ConnectionListener>();
    doAnswer(new Answer<Object>() {

        @Override//  ww  w  . j av a2s . c o m
        public Object answer(InvocationOnMock invocation) throws Throwable {
            listener.set((ConnectionListener) invocation.getArguments()[0]);
            return null;
        }
    }).when(cf).addConnectionListener(any(ConnectionListener.class));
    RabbitAdmin admin = new RabbitAdmin(cf);
    GenericApplicationContext context = new GenericApplicationContext();
    Queue queue = new Queue("foo");
    queue.setShouldDeclare(false);
    context.getBeanFactory().registerSingleton("foo", queue);
    DirectExchange exchange = new DirectExchange("bar");
    exchange.setShouldDeclare(false);
    context.getBeanFactory().registerSingleton("bar", exchange);
    Binding binding = new Binding("foo", DestinationType.QUEUE, "bar", "foo", null);
    binding.setShouldDeclare(false);
    context.getBeanFactory().registerSingleton("baz", binding);
    context.refresh();
    admin.setApplicationContext(context);
    admin.afterPropertiesSet();
    assertNotNull(listener.get());
    listener.get().onCreate(conn);

    verify(channel, times(0)).queueDeclare("foo", true, false, false, null);
    verify(channel, times(0)).exchangeDeclare("bar", "direct", true, false, new HashMap<String, Object>());
    verify(channel, times(0)).queueBind("foo", "bar", "foo", null);
}

From source file:org.springframework.amqp.rabbit.junit.BrokerRunning.java

License:Apache License

@Override
public Statement apply(Statement base, Description description) {

    // Check at the beginning, so this can be used as a static field
    if (this.assumeOnline) {
        Assume.assumeTrue(brokerOnline.get(this.port));
    } else {/*ww w  .  j a va 2 s  .  c o  m*/
        Assume.assumeTrue(brokerOffline.get(this.port));
    }

    ConnectionFactory connectionFactory = getConnectionFactory();

    Connection connection = null; // NOSONAR (closeResources())
    Channel channel = null;

    try {
        connection = connectionFactory.newConnection();
        connection.setId(generateId());
        channel = connection.createChannel();

        for (String queueName : this.queues) {

            if (this.purge) {
                logger.debug("Deleting queue: " + queueName);
                // Delete completely - gets rid of consumers and bindings as well
                channel.queueDelete(queueName);
            }

            if (isDefaultQueue(queueName)) {
                // Just for test probe.
                channel.queueDelete(queueName);
            } else {
                channel.queueDeclare(queueName, true, false, false, null);
            }
        }
        brokerOffline.put(this.port, false);
        if (!this.assumeOnline) {
            Assume.assumeTrue(brokerOffline.get(this.port));
        }

        if (this.management) {
            Client client = new Client(getAdminUri(), this.adminUser, this.adminPassword);
            if (!client.alivenessTest("/")) {
                throw new RuntimeException(
                        "Aliveness test failed for localhost:15672 guest/quest; " + "management not available");
            }
        }
    } catch (Exception e) {
        logger.warn("Not executing tests because basic connectivity test failed: " + e.getMessage());
        brokerOnline.put(this.port, false);
        if (this.assumeOnline) {
            if (fatal()) {
                fail("RabbitMQ Broker is required, but not available");
            } else {
                Assume.assumeNoException(e);
            }
        }
    } finally {
        closeResources(connection, channel);
    }

    return super.apply(base, description);
}

From source file:org.springframework.amqp.rabbit.MulticastMain.java

License:Mozilla Public License

public static void main(String[] args) {
    Options options = getOptions();/*from   w  ww. j  ava  2 s  . c  o  m*/
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('?')) {
            usage(options);
            System.exit(0);
        }

        String hostName = strArg(cmd, 'h', "localhost");
        int portNumber = intArg(cmd, 'p', AMQP.PROTOCOL.PORT);
        String exchangeType = strArg(cmd, 't', "direct");
        String exchangeName = strArg(cmd, 'e', exchangeType);
        int samplingInterval = intArg(cmd, 'i', 1);
        int rateLimit = intArg(cmd, 'r', 0);
        int producerCount = intArg(cmd, 'x', 1);
        int messageCount = intArg(cmd, 'N', 0);
        int consumerCount = intArg(cmd, 'y', 1);
        int connectionCount = cmd.hasOption('c') ? 1 : consumerCount;
        int producerTxSize = intArg(cmd, 'm', 0);
        int consumerTxSize = intArg(cmd, 'n', 0);
        boolean autoAck = cmd.hasOption('a');
        int prefetchCount = intArg(cmd, 'q', 0);
        int minMsgSize = intArg(cmd, 's', 0);
        int timeLimit = intArg(cmd, 'z', 0);
        List<String> flags = lstArg(cmd, 'f');
        int frameMax = intArg(cmd, 'M', 0);
        int heartbeat = intArg(cmd, 'b', 0);

        // setup
        String id = UUID.randomUUID().toString();
        Stats stats = new Stats(1000L * samplingInterval);
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(hostName);
        factory.setPort(portNumber);
        factory.setRequestedFrameMax(frameMax);
        factory.setRequestedHeartbeat(heartbeat);

        Connection[] consumerConnections = new Connection[connectionCount];
        for (int i = 0; i < connectionCount; i++) {
            Connection conn = factory.newConnection();
            consumerConnections[i] = conn;
        }
        Thread[] consumerThreads = new Thread[consumerCount];
        for (int i = 0; i < consumerCount; i++) {
            System.out.println("starting consumer #" + i);
            Connection conn = consumerConnections[i % connectionCount];
            Channel channel = conn.createChannel();
            if (consumerTxSize > 0)
                channel.txSelect();
            channel.exchangeDeclare(exchangeName, exchangeType);
            String queueName = channel.queueDeclare("", flags.contains("persistent"), true, false, null)
                    .getQueue();
            QueueingConsumer consumer = new QueueingConsumer(channel);
            if (prefetchCount > 0)
                channel.basicQos(prefetchCount);
            channel.basicConsume(queueName, autoAck, consumer);
            channel.queueBind(queueName, exchangeName, id);
            Thread t = new Thread(new Consumer(consumer, id, consumerTxSize, autoAck, stats, timeLimit));
            consumerThreads[i] = t;
            t.start();
        }
        Thread[] producerThreads = new Thread[producerCount];
        Connection[] producerConnections = new Connection[producerCount];
        for (int i = 0; i < producerCount; i++) {
            System.out.println("starting producer #" + i);
            Connection conn = factory.newConnection();
            producerConnections[i] = conn;
            Channel channel = conn.createChannel();
            if (producerTxSize > 0)
                channel.txSelect();
            channel.exchangeDeclare(exchangeName, exchangeType);
            final Producer p = new Producer(channel, exchangeName, id, flags, producerTxSize,
                    1000L * samplingInterval, rateLimit, minMsgSize, timeLimit, messageCount);
            channel.addReturnListener(p);
            Thread t = new Thread(p);
            producerThreads[i] = t;
            t.start();
        }

        for (int i = 0; i < producerCount; i++) {
            producerThreads[i].join();
            producerConnections[i].close();
        }

        for (int i = 0; i < consumerCount; i++) {
            consumerThreads[i].join();
        }
        for (int i = 0; i < connectionCount; i++) {
            consumerConnections[i].close();
        }

    } catch (ParseException exp) {
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        usage(options);
    } catch (Exception e) {
        System.err.println("Main thread caught exception: " + e);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:org.springframework.integration.amqp.channel.DispatcherHasNoSubscribersTests.java

License:Apache License

@SuppressWarnings("unchecked")
@Test// w w w. j a va 2s  .  co  m
public void testPtP() throws Exception {
    final Channel channel = mock(Channel.class);
    DeclareOk declareOk = mock(DeclareOk.class);
    when(declareOk.getQueue()).thenReturn("noSubscribersChannel");
    when(channel.queueDeclare(anyString(), anyBoolean(), anyBoolean(), anyBoolean(), any(Map.class)))
            .thenReturn(declareOk);
    Connection connection = mock(Connection.class);
    doAnswer(new Answer<Channel>() {
        @Override
        public Channel answer(InvocationOnMock invocation) throws Throwable {
            return channel;
        }
    }).when(connection).createChannel(anyBoolean());
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    when(connectionFactory.createConnection()).thenReturn(connection);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    AmqpTemplate amqpTemplate = mock(AmqpTemplate.class);

    PointToPointSubscribableAmqpChannel amqpChannel = new PointToPointSubscribableAmqpChannel(
            "noSubscribersChannel", container, amqpTemplate);
    amqpChannel.setBeanName("noSubscribersChannel");
    amqpChannel.setBeanFactory(mock(BeanFactory.class));
    amqpChannel.afterPropertiesSet();

    MessageListener listener = (MessageListener) container.getMessageListener();
    try {
        listener.onMessage(new Message("Hello world!".getBytes(), null));
        fail("Exception expected");
    } catch (MessageDeliveryException e) {
        assertThat(e.getMessage(),
                containsString("Dispatcher has no subscribers for amqp-channel 'noSubscribersChannel'."));
    }
}