Example usage for com.rabbitmq.client Channel queueDeclarePassive

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

Introduction

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

Prototype

Queue.DeclareOk queueDeclarePassive(String queue) throws IOException;

Source Link

Document

Declare a queue passively; i.e., check if it exists.

Usage

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

License:Apache License

/**
 * Returns 3 properties {@link #QUEUE_NAME}, {@link #QUEUE_MESSAGE_COUNT},
 * {@link #QUEUE_CONSUMER_COUNT}, or null if the queue doesn't exist.
 *//*  ww  w . j  a  va2  s. c om*/
@Override
public Properties getQueueProperties(final String queueName) {
    Assert.hasText(queueName, "'queueName' cannot be null or empty");
    return this.rabbitTemplate.execute(new ChannelCallback<Properties>() {
        @Override
        public Properties doInRabbit(Channel channel) throws Exception {
            try {
                DeclareOk declareOk = channel.queueDeclarePassive(queueName);
                Properties props = new Properties();
                props.put(QUEUE_NAME, declareOk.getQueue());
                props.put(QUEUE_MESSAGE_COUNT, declareOk.getMessageCount());
                props.put(QUEUE_CONSUMER_COUNT, declareOk.getConsumerCount());
                return props;
            } catch (Exception e) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Queue '" + queueName + "' does not exist");
                }
                return null;
            }
        }
    });
}

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/*  www .  j  a va 2  s .  com*/
 * @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.junit.RabbitAvailableCTORInjectionTests.java

License:Apache License

@Test
public void test(ConnectionFactory cf) throws Exception {
    assertSame(cf, this.connectionFactory);
    Connection conn = this.connectionFactory.newConnection();
    Channel channel = conn.createChannel();
    DeclareOk declareOk = channel.queueDeclarePassive("rabbitAvailableTests.queue");
    assertEquals(0, declareOk.getConsumerCount());
    channel.close();//from ww  w.  j a  va  2s .c  om
    conn.close();
}

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

License:Apache License

@Test
public void test(ConnectionFactory connectionFactory) throws Exception {
    Connection conn = connectionFactory.newConnection();
    Channel channel = conn.createChannel();
    DeclareOk declareOk = channel.queueDeclarePassive("rabbitAvailableTests.queue");
    assertEquals(0, declareOk.getConsumerCount());
    channel.close();// w ww. ja  v a 2 s  . co m
    conn.close();
}

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

License:Apache License

private void checkMissingQueues() {
    long now = System.currentTimeMillis();
    if (now - this.retryDeclarationInterval > this.lastRetryDeclaration) {
        synchronized (this.missingQueues) {
            Iterator<String> iterator = this.missingQueues.iterator();
            while (iterator.hasNext()) {
                boolean available = true;
                String queue = iterator.next();
                Channel channel = null;
                try {
                    channel = this.connectionFactory.createConnection().createChannel(false);
                    channel.queueDeclarePassive(queue);
                    if (logger.isInfoEnabled()) {
                        logger.info("Queue '" + queue + "' is now available");
                    }//w w  w. jav  a 2 s  .c  om
                } catch (IOException e) {
                    available = false;
                    if (logger.isWarnEnabled()) {
                        logger.warn("Queue '" + queue + "' is still not available");
                    }
                } finally {
                    if (channel != null) {
                        try {
                            channel.close();
                        } catch (IOException e) {
                            //Ignore it
                        }
                    }
                }
                if (available) {
                    try {
                        this.consumeFromQueue(queue);
                        iterator.remove();
                    } catch (IOException e) {
                        throw RabbitExceptionTranslator.convertRabbitAccessException(e);
                    }
                }
            }
        }
        this.lastRetryDeclaration = now;
    }
}

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

License:Apache License

@Test
public void testPrefetchIsSetOnFailedPassiveDeclaration() throws IOException {
    ConnectionFactory connectionFactory = mock(ConnectionFactory.class);
    Connection connection = mock(Connection.class);
    Channel channel = mock(Channel.class);

    when(connectionFactory.createConnection()).thenReturn(connection);
    when(connection.createChannel(Mockito.anyBoolean())).thenReturn(channel);
    when(channel.queueDeclarePassive(Mockito.anyString())).then(new Answer<Object>() {

        @Override/*from  ww w.j  a  va2 s .co  m*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            Object arg = invocation.getArguments()[0];
            if ("good".equals(arg)) {
                return Mockito.any(AMQP.Queue.DeclareOk.class);
            } else {
                throw new IOException();
            }
        }
    });

    BlockingQueueConsumer blockingQueueConsumer = new BlockingQueueConsumer(connectionFactory,
            new DefaultMessagePropertiesConverter(), new ActiveObjectCounter<BlockingQueueConsumer>(),
            AcknowledgeMode.AUTO, true, 20, "good", "bad");

    blockingQueueConsumer.start();

    verify(channel).basicQos(20);
}

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

License:Apache License

private void doConsumeFromQueue(String queue) {
    if (!isActive()) {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Consume from queue " + queue + " ignore, container stopping");
        }/*w  w  w . j  a  va  2s.  c  o  m*/
        return;
    }
    Connection connection = null; // NOSONAR (close)
    try {
        connection = getConnectionFactory().createConnection();
    } catch (Exception e) {
        this.consumersToRestart.add(new SimpleConsumer(null, null, queue));
        throw new AmqpConnectException(e);
    }
    Channel channel = null;
    SimpleConsumer consumer = null;
    try {
        channel = connection.createChannel(isChannelTransacted());
        channel.basicQos(getPrefetchCount());
        consumer = new SimpleConsumer(connection, channel, queue);
        channel.queueDeclarePassive(queue);
        consumer.consumerTag = channel.basicConsume(queue, getAcknowledgeMode().isAutoAck(),
                (getConsumerTagStrategy() != null ? getConsumerTagStrategy().createConsumerTag(queue) : ""),
                false, isExclusive(), getConsumerArguments(), consumer);
    } catch (IOException e) {
        RabbitUtils.closeChannel(channel);
        RabbitUtils.closeConnection(connection);

        if (e.getCause() instanceof ShutdownSignalException
                && e.getCause().getMessage().contains("in exclusive use")) {
            getExclusiveConsumerExceptionLogger().log(logger, "Exclusive consumer failure", e.getCause());
            publishConsumerFailedEvent("Consumer raised exception, attempting restart", false, e);
        } else if (this.logger.isDebugEnabled()) {
            this.logger.debug("Queue not present or basicConsume failed, scheduling consumer " + consumer
                    + " for restart");
        }
        this.consumersToRestart.add(consumer);
        consumer = null;
    }
    synchronized (this.consumersMonitor) {
        if (consumer != null) {
            this.cancellationLock.add(consumer);
            this.consumers.add(consumer);
            this.consumersByQueue.add(queue, consumer);
            if (this.logger.isInfoEnabled()) {
                this.logger.info(consumer + " started");
            }
        }
    }
}

From source file:org.wso2.carbon.event.adapter.rabbitmq.internal.util.RabbitMQEventAdapterUtils.java

License:Open Source License

/**
 * Check Whether Queue is available/* w  w w .  j  a v a 2 s. c  o  m*/
 *
 * @param connection Connection to the RabbitMQ
 * @param queueName  Name of the queue
 */
public static boolean isQueueAvailable(Connection connection, String queueName) throws IOException {
    Channel channel = connection.createChannel();
    try {
        // check availability of the named queue
        // if an error is encountered, including if the queue does not exist and if the
        // queue is exclusively owned by another connection
        channel.queueDeclarePassive(queueName);
        return true;
    } catch (IOException e) {
        return false;
    }
}

From source file:org.wso2.carbon.event.adaptor.rabbitmq.output.RabbitMQOutputEventAdaptorType.java

License:Open Source License

/**
 * <pre>//from  w  w w. j av  a2  s  .  c om
 * publish
 * <pre>
 * 
 * @param outputEventAdaptorMessageConfiguration
 * @param message
 * @param outputEventAdaptorConfiguration
 * @param tenantId
 * @see org.wso2.carbon.event.output.adaptor.core.AbstractOutputEventAdaptor#publish(org.wso2.carbon.event.output.adaptor.core.message.config.OutputEventAdaptorMessageConfiguration, java.lang.Object, org.wso2.carbon.event.output.adaptor.core.config.OutputEventAdaptorConfiguration, int)
 */
@Override
protected void publish(OutputEventAdaptorMessageConfiguration outputEventAdaptorMessageConfiguration,
        Object message, OutputEventAdaptorConfiguration outputEventAdaptorConfiguration, int tenantId) {

    LOGGER.debug("*** DEBUG RabbitMQOutputEventAdaptorType.publish()");

    try {
        Channel channel = getChannel(outputEventAdaptorConfiguration, tenantId);

        String queue = outputEventAdaptorMessageConfiguration.getOutputMessageProperties()
                .get(RabbitMQEventAdaptorConstants.ADAPTOR_RABBITMQ_QUEUE);

        boolean isExist = false;
        try {
            channel.queueDeclarePassive(queue);
            isExist = true;
        } catch (IOException e) {
            LOGGER.info("*** INFO : [" + queue + "] does not exist.");
        }

        if (!isExist) {
            String dlmExchangeName = "exchange_dlm";
            String routingKey = queue;

            if (!channel.isOpen()) {
                channel = getChannel(outputEventAdaptorConfiguration, tenantId);
            }

            /**
             *  Add configuration for DLM
             */
            Map<String, Object> arg = new HashMap<String, Object>();
            arg.put("x-dead-letter-exchange", dlmExchangeName);
            arg.put("x-dead-letter-routing-key", routingKey);

            /**
             *  Create a queue and binding with DLM
             */
            channel.queueDeclare(queue, true, false, false, arg);
            channel.queueBind(queue, dlmExchangeName, routingKey);
        }

        if (message instanceof String) {
            channel.basicPublish("", queue, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    ((String) message).getBytes());
        } else {
            channel.basicPublish("", queue, MessageProperties.PERSISTENT_TEXT_PLAIN,
                    message.toString().getBytes());
        }
        LOGGER.debug("*** DEBUG: [x] Sent " + message.getClass() + " type, '" + message + "'");
    } catch (IOException e) {
        throw new AdaptorRuntimeException(e);
    }
}

From source file:org.wso2.carbon.extension.analytics.receiver.rabbitmq.internal.util.RabbitMQUtils.java

License:Open Source License

public static boolean isQueueAvailable(Connection connection, String queueName) throws IOException {
    Channel channel = connection.createChannel();
    try {/*ww w  .  j  av  a2s. c om*/
        // check availability of the named queue
        // if an error is encountered, including if the queue does not exist and if the
        // queue is exclusively owned by another connection
        channel.queueDeclarePassive(queueName);
        return true;
    } catch (IOException e) {
        return false;
    }
}