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:net.nzcorp.hbase.tableevent_signaler.TableEventSignalerTest.java

License:Apache License

@Test(expected = IOException.class)
public void filterOnQualifiersThatDoesNotExistSilencesEvents() throws Exception {

    Map<String, String> kvs = configureHBase(primaryTableNameString, secondaryIdxTableNameString, "e", "eg",
            "a", amq_default_address, primaryTableNameString, "false", "one|some");
    setupHBase(kvs);/*w  ww . j a v  a2  s .  com*/

    //simulate population of secondary index as a result of the above
    Put idxPut = new Put("EFG1".getBytes());
    idxPut.addColumn("a".getBytes(), "EFB1".getBytes(), "".getBytes());
    secondaryIdxTable.put(idxPut);

    // Add a column to the primary table, which should trigger a data ripple to the downstream table
    Put tablePut = new Put("EFG1".getBytes());
    tablePut.addColumn("e".getBytes(), "some_key".getBytes(), "some_value".getBytes());
    primaryTable.put(tablePut);

    //check that values made it to the queue
    com.rabbitmq.client.ConnectionFactory factory = new com.rabbitmq.client.ConnectionFactory();
    factory.setUri(amq_default_address);
    com.rabbitmq.client.Connection conn = factory.newConnection();
    com.rabbitmq.client.Channel channel = conn.createChannel();

    System.out.println(String.format("is ok? %s", channel.queueDeclarePassive(primaryTableNameString)));
}

From source file:org.apache.axis2.transport.rabbitmq.RabbitMQMessageSender.java

License:Open Source License

/**
 * Perform the creation of exchange/queue and the Outputstream
 *
 * @param message    the RabbitMQ AMQP message
 * @param msgContext the Axis2 MessageContext
 */// ww  w . j  a  v  a  2  s.co m
public void send(RabbitMQMessage message, MessageContext msgContext) throws AxisRabbitMQException {

    String exchangeName = null;
    AMQP.BasicProperties basicProperties = null;
    byte[] messageBody = null;
    if (connection != null) {
        Channel channel = null;
        String queueName = properties.get(RabbitMQConstants.QUEUE_NAME);
        String routeKey = properties.get(RabbitMQConstants.QUEUE_ROUTING_KEY);
        exchangeName = properties.get(RabbitMQConstants.EXCHANGE_NAME);
        String exchangeType = properties.get(RabbitMQConstants.EXCHANGE_TYPE);
        String durable = properties.get(RabbitMQConstants.EXCHANGE_DURABLE);
        String replyTo = properties.get(RabbitMQConstants.RABBITMQ_REPLY_TO);

        //if the user defined any replyTo value it will be set
        if (replyTo != null) {
            message.setReplyTo(replyTo);
        }

        try {
            if (routeKey == null && !"x-consistent-hash".equals(exchangeType)) {
                log.info("rabbitmq.queue.routing.key property not found. Using queue name as "
                        + "the routing key.");
                routeKey = queueName;
            }

            channel = connection.createChannel();
            //Declaring the queue
            if (queueName != null && !queueName.equals("")) {

                Boolean queueAvailable = false;
                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);
                    queueAvailable = true;
                } catch (java.io.IOException e) {
                    log.info("Queue :" + queueName + " not found.Declaring queue.");
                }

                if (!queueAvailable) {
                    // Declare the named queue if it does not exists.
                    if (!channel.isOpen()) {
                        channel = connection.createChannel();
                    }
                    try {
                        channel.queueDeclare(queueName, RabbitMQUtils.isDurableQueue(properties),
                                RabbitMQUtils.isExclusiveQueue(properties),
                                RabbitMQUtils.isAutoDeleteQueue(properties), null);

                    } catch (java.io.IOException e) {
                        handleException("Error while creating queue: " + queueName + e);
                        return;
                    }
                }
            }

            //Declaring the exchange
            if (exchangeName != null && !exchangeName.equals("")) {
                Boolean exchangeAvailable = false;
                try {
                    // check availability of the named exchange
                    // Throws:java.io.IOException - the server will raise a
                    // 404 channel exception if the named exchange does not
                    // exists.
                    channel.exchangeDeclarePassive(exchangeName);
                    exchangeAvailable = true;
                } catch (java.io.IOException e) {
                    log.info("Exchange :" + exchangeName + " not found.Declaring exchange.");
                }

                if (!exchangeAvailable) {
                    // Declare the named exchange if it does not exists.
                    if (!channel.isOpen()) {
                        channel = connection.createChannel();
                    }
                    try {
                        if (exchangeType != null && !exchangeType.equals("")) {
                            if (durable != null && !durable.equals("")) {
                                channel.exchangeDeclare(exchangeName, exchangeType,
                                        Boolean.parseBoolean(durable));
                            } else {
                                channel.exchangeDeclare(exchangeName, exchangeType, true);
                            }
                        } else {
                            channel.exchangeDeclare(exchangeName, "direct", true);
                        }
                    } catch (java.io.IOException e) {
                        handleException("Error occurred while declaring exchange.");

                    }

                }

                if (queueName != null && !"x-consistent-hash".equals(exchangeType)) {
                    // Create bind between the queue &
                    // provided routeKey
                    try {
                        // no need to have configure permission to
                        // perform channel.queueBind
                        channel.queueBind(queueName, exchangeName, routeKey);
                    } catch (java.io.IOException e) {
                        handleException("Error occurred while creating the bind between the queue: " + queueName
                                + " & exchange: " + exchangeName + e);
                    }
                }

            }

            AMQP.BasicProperties.Builder builder = buildBasicProperties(message);

            // set delivery mode (default is Persistent): 1=NonPersistent , 2=Persistent
            String deliveryModeString = properties.get(RabbitMQConstants.QUEUE_DELIVERY_MODE);
            int deliveryMode = 2;
            if (deliveryModeString != null) {
                deliveryMode = Integer.parseInt(deliveryModeString);
            }
            builder.deliveryMode(deliveryMode);

            basicProperties = builder.build();
            OMOutputFormat format = BaseUtils.getOMOutputFormat(msgContext);
            MessageFormatter messageFormatter = null;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            try {
                messageFormatter = MessageProcessorSelector.getMessageFormatter(msgContext);
            } catch (AxisFault axisFault) {
                throw new AxisRabbitMQException("Unable to get the message formatter to use", axisFault);
            }

            //server plugging should be enabled before using x-consistent hashing
            //for x-consistent-hashing only exchangeName, exchangeType and routingKey should be
            // given. Queue/exchange creation, bindings should be done at the broker
            try {
                // generate random value as routeKey if the exchangeType is
                // x-consistent-hash type
                if (exchangeType != null && exchangeType.equals("x-consistent-hash")) {
                    routeKey = UUID.randomUUID().toString();
                }

            } catch (UnsupportedCharsetException ex) {
                handleException("Unsupported encoding " + format.getCharSetEncoding(), ex);
            }
            try {
                messageFormatter.writeTo(msgContext, format, out, false);
                messageBody = out.toByteArray();
            } catch (IOException e) {
                handleException("IO Error while creating BytesMessage", e);
            } finally {
                if (out != null) {
                    out.close();
                    channel.abort();
                }
            }

        } catch (IOException e) {
            handleException("Error while publishing message to the queue ", e);
        }
        try {
            if (connection != null) {

                try {
                    channel = connection.createChannel();
                    if (exchangeName != null && exchangeName != "")
                        channel.basicPublish(exchangeName, routeKey, basicProperties, messageBody);
                    else
                        channel.basicPublish("", routeKey, basicProperties, messageBody);

                } catch (IOException e) {
                    log.error("Error while publishing the message");
                } finally {
                    if (channel != null) {
                        channel.close();
                    }
                }

            }
        } catch (IOException e) {
            handleException("Error while publishing message to the queue ", e);
        }
    }
}

From source file:org.apache.synapse.message.store.impl.rabbitmq.RabbitMQStore.java

License:Open Source License

/**
 * Create a Queue to store messages, this will used queueName parameter
 *
 * @throws IOException : if its enable to create the queue or exchange
 *//*from   w  w  w.  java 2  s .c  o m*/
private void setQueue() throws IOException {
    Channel channel = null;
    try {
        channel = producerConnection.createChannel();
        try {
            channel.queueDeclarePassive(queueName);
        } catch (java.io.IOException e) {
            logger.info("Queue :" + queueName + " not found.Declaring queue.");
            if (!channel.isOpen()) {
                channel = producerConnection.createChannel();
            }
            //Hashmap with names and parameters can be used in the place of null argument
            //Eg: adding dead letter exchange to the queue
            //params: (queueName, durable, exclusive, autoDelete, paramMap)
            channel.queueDeclare(queueName, true, false, false, null);
        }
        //declaring exchange
        if (exchangeName != null) {
            try {
                channel.exchangeDeclarePassive(exchangeName);
            } catch (java.io.IOException e) {
                logger.info("Exchange :" + exchangeName + " not found. Declaring exchange.");
                if (!channel.isOpen()) {
                    channel = producerConnection.createChannel();
                }
                //params : ( exchangeName, exchangeType, durable, autoDelete, paramMap )
                channel.exchangeDeclare(exchangeName, "direct", true, false, null);
            }
            channel.queueBind(queueName, exchangeName, routeKey);
        }
    } finally {
        channel.close();
    }
}

From source file:org.eclipse.ditto.services.connectivity.messaging.rabbitmq.RabbitMQClientActor.java

License:Open Source License

private void ensureQueuesExist(final Channel channel) {
    final Collection<String> missingQueues = new ArrayList<>();
    getSourcesOrEmptyList().forEach(consumer -> consumer.getAddresses().forEach(address -> {
        try {//from  w w w. j  a  va  2 s .c  o  m
            channel.queueDeclarePassive(address);
        } catch (final IOException e) {
            missingQueues.add(address);
            log.warning("The queue <{}> does not exist.", address);
        } catch (final AlreadyClosedException e) {
            if (!missingQueues.isEmpty()) {
                // Our client will automatically close the connection if a queue does not exists. This will
                // cause an AlreadyClosedException for the following queue (e.g. ['existing1', 'notExisting', -->'existing2'])
                // That's why we will ignore this error if the missingQueues list isn't empty.
                log.warning(
                        "Received exception of type {} when trying to declare queue {}. This happens when a previous "
                                + "queue was missing and thus the connection got closed.",
                        e.getClass().getName(), address);
            } else {
                log.error("Exception while declaring queue {}", address, e);
                throw e;
            }
        }
    }));
    if (!missingQueues.isEmpty()) {
        log.warning("Stopping RMQ client actor for connection <{}> as queues to connect to are missing: <{}>",
                connectionId(), missingQueues);
        connectionLogger.failure("Can not connect to RabbitMQ as queues are missing: {0}", missingQueues);
        throw ConnectionFailedException.newBuilder(connectionId())
                .description("The queues " + missingQueues + " to connect to are missing.").build();
    }
}

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

License:Open Source License

public static String getOrCreateQueue(final Channel channel, final ImmutableEndpoint endpoint,
        final boolean activeDeclarationsOnly) throws IOException {
    final String exchangeName = getOrCreateExchange(channel, endpoint, activeDeclarationsOnly);
    final String routingKey = getRoutingKey(endpoint);

    if ((StringUtils.isBlank(exchangeName)) && (StringUtils.isNotBlank(routingKey))) {
        // no exchange name -> enforce routing key to be empty
        throw new MuleRuntimeException(MessageFactory.createStaticMessage(
                "An exchange name must be provided if a routing key is provided in endpoint: " + endpoint));
    }/*from   ww  w  .  j a v a2s  . co  m*/

    final String queueName = getQueueName(endpoint.getAddress());

    if (StringUtils.isBlank(queueName)) {
        // no queue name -> create a private one on the server
        final DeclareOk queueDeclareResult = channel.queueDeclare();

        final String privateQueueName = queueDeclareResult.getQueue();
        LOG.info("Declared private queue: " + privateQueueName);

        bindQueue(channel, endpoint, exchangeName, routingKey, privateQueueName);
        return privateQueueName;
    }

    // queue name -> either create or ensure the queue exists
    if (endpoint.getProperties().containsKey(QUEUE_DURABLE)
            || endpoint.getProperties().containsKey(QUEUE_AUTO_DELETE)
            || endpoint.getProperties().containsKey(QUEUE_EXCLUSIVE)) {
        // any of the queue declaration parameter provided -> declare the queue
        final boolean queueDurable = BooleanUtils.toBoolean((String) endpoint.getProperty(QUEUE_DURABLE));
        final boolean queueExclusive = BooleanUtils.toBoolean((String) endpoint.getProperty(QUEUE_EXCLUSIVE));
        final boolean queueAutoDelete = BooleanUtils
                .toBoolean((String) endpoint.getProperty(QUEUE_AUTO_DELETE));

        channel.queueDeclare(queueName, queueDurable, queueExclusive, queueAutoDelete, NO_ARGS);
        LOG.info("Declared queue: " + queueName + ", durable: " + queueDurable + ", exclusive: "
                + queueExclusive + ", autoDelete: " + queueAutoDelete);

        bindQueue(channel, endpoint, exchangeName, routingKey, queueName);
    } else if (!activeDeclarationsOnly) {
        // no declaration parameter -> ensure the queue exists
        channel.queueDeclarePassive(queueName);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Validated presence of queue: " + queueName);
        }
    }

    return queueName;
}

From source file:org.mule.transport.amqp.internal.client.AmqpDeclarer.java

License:Open Source License

public void declareQueuePassively(Channel channel, String queueName) throws IOException {
    channel.queueDeclarePassive(queueName);

    if (logger.isDebugEnabled()) {
        logger.debug("Validated presence of queue: " + queueName);
    }/*ww w  . ja v  a 2  s  .c om*/
}

From source file:org.objectweb.joram.mom.dest.amqp.AmqpAcquisition.java

License:Open Source License

/**
 * Create a new AMQP consumer for each connection available.
 *///from  w  w w.  jav a  2s.  c  om
public void updateConnections(List<LiveServerConnection> connections) {
    for (LiveServerConnection connection : connections) {
        if (!channels.containsKey(connection.getName())) {
            if (connectionNames == null || connectionNames.contains(connection.getName())) {
                if (logger.isLoggable(BasicLevel.DEBUG)) {
                    logger.log(BasicLevel.DEBUG, "Creating a new consumer on queue " + amqpQueue
                            + " for connection " + connection.getName());
                }
                try {
                    Channel channel = connection.getConnection().createChannel();
                    if (amqpQueuePassive) {
                        channel.queueDeclarePassive(amqpQueue);
                    } else {
                        channel.queueDeclare(amqpQueue, amqpQueueDurable, amqpQueueExclusive,
                                amqpQueueAutoDelete, null);
                    }
                    AmqpConsumer consumer = new AmqpConsumer(channel, connection.getName());
                    channel.basicConsume(amqpQueue, false, consumer);
                    channels.put(connection.getName(), channel);
                } catch (Exception e) {
                    logger.log(BasicLevel.ERROR,
                            "Error while starting consumer on connection: " + connection.getName(), e);
                }
            }
        }
    }
}

From source file:org.objectweb.joram.mom.dest.amqp.AmqpDistribution.java

License:Open Source License

public void distribute(Message message) throws Exception {

    List<String> connectionNames = this.connectionNames;

    // Convert message properties
    AMQP.BasicProperties props = new AMQP.BasicProperties();
    if (message.persistent) {
        props.setDeliveryMode(Integer.valueOf(2));
    } else {// w w  w  .j a va  2s.  c  o m
        props.setDeliveryMode(Integer.valueOf(1));
    }
    props.setCorrelationId(message.correlationId);
    props.setPriority(Integer.valueOf(message.priority));
    props.setTimestamp(new Date(message.timestamp));
    props.setMessageId(message.id);
    props.setType(String.valueOf(message.type));
    props.setExpiration(String.valueOf(message.expiration));

    if (message.properties != null) {
        Map<String, Object> headers = new HashMap<String, Object>();
        message.properties.copyInto(headers);
        props.setHeaders(headers);

        Object customRouting = message.properties.get(ROUTING_PROP);
        if (customRouting != null && customRouting instanceof String) {
            connectionNames = AmqpConnectionService.convertToList((String) customRouting);
        }
    }

    // Update channels if necessary
    long now = System.currentTimeMillis();
    if (now - lastUpdate > updatePeriod) {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "Updating channels.");
        }
        List<LiveServerConnection> connections = AmqpConnectionService.getInstance().getConnections();
        for (LiveServerConnection connection : connections) {
            if (!channels.containsKey(connection.getName())) {
                if (logger.isLoggable(BasicLevel.DEBUG)) {
                    logger.log(BasicLevel.DEBUG,
                            connection.getName() + ": New channel available for distribution.");
                }
                try {
                    Channel channel = connection.getConnection().createChannel();
                    if (amqpQueuePassive) {
                        channel.queueDeclarePassive(amqpQueue);
                    } else {
                        channel.queueDeclare(amqpQueue, amqpQueueDurable, amqpQueueExclusive,
                                amqpQueueAutoDelete, null);
                    }
                    channels.put(connection.getName(), channel);
                } catch (IOException exc) {
                    if (logger.isLoggable(BasicLevel.DEBUG)) {
                        logger.log(BasicLevel.DEBUG, "Channel is not usable.", exc);
                    }
                }
            }
        }
        lastUpdate = now;
    }

    // Send the message
    Iterator<Map.Entry<String, Channel>> iter = channels.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<String, Channel> entry = iter.next();
        try {
            Channel chan = entry.getValue();
            String cnxName = entry.getKey();
            if (!chan.isOpen()) {
                iter.remove();
                continue;
            }
            if (connectionNames != null && !connectionNames.contains(cnxName)) {
                continue;
            }
            if (logger.isLoggable(BasicLevel.DEBUG)) {
                logger.log(BasicLevel.DEBUG, "Sending message on " + cnxName);
            }
            chan.basicPublish("", amqpQueue, props, message.getBody());
            channels.get(cnxName); // Access the used connection to update the LRU map
            return;
        } catch (IOException exc) {
            if (logger.isLoggable(BasicLevel.DEBUG)) {
                logger.log(BasicLevel.DEBUG, "Channel is not usable, remove from table.", exc);
            }
            iter.remove();
        } catch (AlreadyClosedException exc) {
            if (logger.isLoggable(BasicLevel.DEBUG)) {
                logger.log(BasicLevel.DEBUG, "Channel is not usable, remove from table.", exc);
            }
            iter.remove();
        }
    }

    throw new Exception("Message could not be sent, no usable channel found.");
}

From source file:org.springframework.amqp.rabbit.config.MismatchedQueueDeclarationTests.java

License:Apache License

@Test
@Ignore//  w  ww  .  ja  v a2  s .c o  m
public void testAdminFailsWithMismatchedQueue() throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
    context.setConfigLocation(
            "org/springframework/amqp/rabbit/config/MismatchedQueueDeclarationTests-context.xml");
    StandardEnvironment env = new StandardEnvironment();
    env.addActiveProfile("basicAdmin");
    env.addActiveProfile("basic");
    context.setEnvironment(env);
    context.refresh();
    context.getBean(CachingConnectionFactory.class).createConnection();
    context.destroy();
    Channel channel = this.connectionFactory.createConnection().createChannel(false);
    channel.queueDeclarePassive("mismatch.bar");
    this.admin.deleteQueue("mismatch.bar");
    assertNotNull(this.admin.getQueueProperties("mismatch.foo"));
    assertNull(this.admin.getQueueProperties("mismatch.bar"));

    env = new StandardEnvironment();
    env.addActiveProfile("basicAdmin");
    env.addActiveProfile("ttl");
    context.setEnvironment(env);
    context.refresh();
    channel = this.connectionFactory.createConnection().createChannel(false);
    try {
        context.getBean(CachingConnectionFactory.class).createConnection();
        fail("Expected exception - basic admin fails with mismatched declarations");
    } catch (Exception e) {
        assertTrue(e.getCause().getCause().getMessage().contains("inequivalent arg 'x-message-ttl'"));
    }
    assertNotNull(this.admin.getQueueProperties("mismatch.foo"));
    assertNull(this.admin.getQueueProperties("mismatch.bar"));
    context.close();
}

From source file:org.springframework.amqp.rabbit.config.MismatchedQueueDeclarationTests.java

License:Apache License

@Test
public void testAdminSkipsMismatchedQueue() throws Exception {
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext();
    context.setConfigLocation(/*from ww  w.j a  va2s  .c o  m*/
            "org/springframework/amqp/rabbit/config/MismatchedQueueDeclarationTests-context.xml");
    StandardEnvironment env = new StandardEnvironment();
    env.addActiveProfile("advancedAdmin");
    env.addActiveProfile("basic");
    context.setEnvironment(env);
    context.refresh();
    context.getBean(CachingConnectionFactory.class).createConnection();
    context.destroy();
    Channel channel = this.connectionFactory.createConnection().createChannel(false);
    channel.queueDeclarePassive("mismatch.bar");
    this.admin.deleteQueue("mismatch.bar");
    assertNotNull(this.admin.getQueueProperties("mismatch.foo"));
    assertNull(this.admin.getQueueProperties("mismatch.bar"));

    env = new StandardEnvironment();
    env.addActiveProfile("advancedAdmin");
    env.addActiveProfile("ttl");
    context.setEnvironment(env);
    context.refresh();
    channel = this.connectionFactory.createConnection().createChannel(false);
    context.getBean(CachingConnectionFactory.class).createConnection();
    assertNotNull(this.admin.getQueueProperties("mismatch.foo"));
    assertNotNull(this.admin.getQueueProperties("mismatch.bar"));
    context.close();
}